python - 以字节为单位获取 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 认知服务时,我收到一个错误的请求错误。
我该如何解决这个问题?
解决方案
我们可以通过将对象存储在变量中并按如下方式打印来获取对象的大小:
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 文档中获取更多信息。
推荐阅读
- c# - ASP.NET MVC EF Core,视图中的属性访问,同时在不同模型的选定 ID 上
- google-maps - 如何在谷歌地图颤动中获取当前相机位置latlng
- android - 安卓wordpress自动fcm通知收不到
- javascript - JavaScript 动态加载脚本文件以创建一个对象,然后在该对象上运行 .init()
- wordpress - 自定义帖子类型的多个用户角色
- sql - 更改 SQL 中列的显示顺序
- next.js - Nextjs 和工作箱集成
- angular - 有什么方法可以在 Ag-Grid(Angular)中使用 API 调用中的 coldefs 字段值?
- angular - GitLab 管道因异常而失败:无法读取未定义的属性“减号”
- ruby - 有没有办法使用 RuboCop 进行增量 linting?