【问题标题】:PIL Image as Bytes with BytesIO to prevent hard disk savingPIL Image as Bytes with BytesIO 防止硬盘保存
【发布时间】:2020-12-18 11:17:18
【问题描述】:

有问题

我有一个 PIL 图像,我想将其转换为字节数组。我无法将图像保存在硬盘上,因此无法使用默认的open(file_path, 'rb') 功能。

我尝试了什么

为了解决这个问题,我正在尝试使用io 库来执行此操作:

buf = io.BytesIO()
image.save(buf, format='JPEG')
b_image = buf.getvalue()

将图像视为功能性 PIL 图像。

“b_image”将用作 Microsoft Azure 认知服务函数read_in_stream()的参数

如果我们查看文档,我们可以看到这个函数图像参数必须是:

图片 外部参照:生成器

必填

图像流。

提供文档here

问题

当我执行它时,我得到了错误:

文件“C:...\envs\trainer\lib\site-packages\msrest\service_client.py”,第 137 行,在 stream_upload 块 = data.read(self.config.connection.data_block_size)

AttributeError: 'bytes' 对象没有属性 'read'

客户端身份验证或其他方面没有错误,因为当我将使用此行导入的图像作为参数提供时:

image = open("./1.jpg", 'rb')

一切正常..

来源

我还看到了 this 帖子,它准确地解释了我想要做什么,但在我的情况下它不起作用。任何想法将不胜感激。

【问题讨论】:

    标签: python azure azure-cognitive-services bytesio


    【解决方案1】:

    当我们使用read_in_stream方法时,我们需要提供一个流。但是代码BytesIO.getvalue 将流的内容作为字符串或字节返回。所以请更新如下代码

    buf = io.BytesIO()
    image.save(buf, format='JPEG')
    computervision_client.read_in_stream(buf)
    

    更多详情请参考here


    更新

    关于这个问题,我建议你使用rest API来实现你的需求。

    import io
    import requests
    from PIL import Image
    import time
    url = "{your endpoint}/vision/v3.1/read/analyze"
    key = ''
    headers = {
        'Ocp-Apim-Subscription-Key': key,
        'Content-Type': 'application/octet-stream'
    }
    
    // process image
    ...
    with io.BytesIO() as buf:
        im.save(buf, 'jpeg')
        response = requests.request(
            "POST", url, headers=headers, data=buf.getvalue())
        
        # get result
    
        while True:
            res = requests.request(
                "GET", response.headers['Operation-Location'], headers=headers)
            status = res.json()['status']
            if status == 'succeeded':
                print(res.json()['analyzeResult'])
                break
            time.sleep(1)
    
    

    【讨论】:

    • 我也尝试过,但是当我这样做时,出现以下错误:> 第 1567 行,在 read_in_stream 中引发 models.ComputerVisionErrorException(self._deserialize, response) azure.cognitiveservices.vision.computervision.models。 _models_py3.ComputerVisionErrorException:操作返回无效状态代码“错误请求”
    • 但如果这样做:stream = io.BytesIO() image.save(stream, format='JPEG') f = open("file.txt", "wb") f.write(stream.getvalue()) f = open("file.txt", "rb") 并且我将 f 作为参数,它工作得很好,但我不想使用文件
    • 谢谢。它正在使用这种语法
    猜你喜欢
    • 2012-08-16
    • 2020-02-17
    • 1970-01-01
    • 2022-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-16
    • 1970-01-01
    相关资源
    最近更新 更多