You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将已读取的OpenCV图像直接发送至Azure认知服务?

解决方案

要将OpenCV读取的图像(numpy数组格式)直接发送到Azure认知服务,无需重新读取文件,可通过以下步骤转换:

  1. 将OpenCV图像编码为二进制字节流:使用cv2.imencode()将numpy数组格式的图像编码为指定格式(如JPG/PNG)的字节缓冲区。
  2. 转换为类文件对象:将字节缓冲区包装成BytesIO对象,使其具备文件流的接口,符合Azure API的参数要求。

完整代码示例

import cv2
from io import BytesIO
from azure.cognitiveservices.vision.computervision import ComputerVisionClient
from msrest.authentication import CognitiveServicesCredentials

# 初始化Azure客户端
subscription_key = "你的订阅密钥"
endpoint = "你的服务端点"
computervision_client = ComputerVisionClient(endpoint, CognitiveServicesCredentials(subscription_key))

# OpenCV读取图像
cv_image = cv2.imread("图像文件路径")

# 转换为可用于Azure的流对象
# 编码为JPG格式(也可替换为'.png')
ret, buffer = cv2.imencode('.jpg', cv_image)
if not ret:
    raise ValueError("图像编码失败")

# 将字节缓冲区转为BytesIO流
image_stream = BytesIO(buffer)

# 调用Azure服务
read_response = computervision_client.read_in_stream(image_stream, raw=True)

关键说明

  • cv2.imencode()返回两个值:第一个是布尔值(表示编码是否成功),第二个是存储编码后图像的字节数组。
  • BytesIO对象模拟了文件的读写接口,和open()返回的文件对象行为一致,可直接传入read_in_stream方法。
  • 若需要指定图像质量,可在imencode中添加参数,例如cv2.imencode('.jpg', cv_image, [int(cv2.IMWRITE_JPEG_QUALITY), 90])。

内容的提问来源于stack exchange,提问作者granular_bastard

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 13:57:41