首页 > 解决方案 > 以字节为单位获取 Python 中的图像对象大小 - Azure 中的 BadRequest 错误

问题描述

我有一个通过流光接口接受的图像对象。这是它的类型:<class 'streamlit.uploaded_file_manager.UploadedFile'>

我需要以字节或兆字节为单位获取此图像的大小。图像未存储在我的设备上。我尝试使用

def img_resize(image):
    img2 = Image.open(image)
    img_file = io.BytesIO()
    img2.save(img_file, 'png')
    image_file_size = img_file.tell()
    print(image_file_size)
    img2.close()

# This function connects to azure services and generates the resources and generates the results
def azure_result(image_name, image):
    img_resize(image)

输出: 14386671 2021-08-12 12:57:01.892 Traceback(最近一次调用最后一次):文件“路径”,第 1709 行,在 read_in_stream 中引发模型。ComputerVisionOcrErrorException(self._deserialize,response)azure.cognitiveservices.vision.computervision。 models._models_py3.ComputerVisionOcrErrorException:操作返回了无效的状态代码“错误请求”

打印的文件大小为 14386671,根据系统的图像大小为 3.77 mb。当我进一步将图像对象传递给 Azure 认知服务时,我收到一个错误的请求错误。

我该如何解决这个问题?

标签: pythonpython-3.xazureimagepython-imaging-library

解决方案


我们可以通过将对象存储在变量中并按如下方式打印来获取对象的大小:

 print(sys.getsizeof(content))

或者我们可以将扩展名添加到 img_file 作为“. size”,这将获得以字节为单位的实际大小。

在此处输入图像描述

如果我们想以 KB、MB 和 GB 为单位获取文件大小并将它们转换为字节,我们可以按照下面的转换表:

在此处输入图像描述

我们可以在 img_resize(image) 函数中添加这些扩展,我们将能够捕获正确的字节。

连接到 Azure Cognito 服务之前的先决条件是在终端中安装 pip 库,如下所示:

pip install azure-cognitiveservices-vision-computervision

下面的代码让我们深入了解如何连接到 Azure Cognito 服务:

from azure.cognitiveservices.vision.computervision import ComputerVisionClient
from azure.cognitiveservices.vision.computervision.models import VisualFeatureTypes
from msrest.authentication import CognitiveServicesCredentials

import os
region = os.environ['ACCOUNT_REGION']
key = os.environ['ACCOUNT_KEY']

credentials = CognitiveServicesCredentials(key)
client = ComputerVisionClient(
    endpoint="https://" + region + ".api.cognitive.microsoft.com/",
    credentials=credentials
)

可以从Azure的Python 文档中获取更多信息。


推荐阅读