python - 将原始二进制图像传递到 Azure 认知服务 API

标签 python azure azure-cognitive-services

我想使用Analyze Images API来自 Azure 的原始 Python 请求传递二进制图像数据而不是 URL。我使用 io 模块从图像中获取二进制数据

with io.BytesIO() as output:
    tmp_imp.save(output, format="JPEG")
    contents = output.getvalue()

payload = {
    {'url': contents}
}

然后我将其作为“url”传递给有效负载

response = requests.post(analyze_url, headers=headers, params=params, data=json.dumps(payload))

我收到的错误表明存在 JSON 格式错误,但我不明白如何修复它

{'error': {'code': 'InvalidArgument', 'innererror': {'code': 'BadArgument', 'message': 'JSON format error.'}, 'message': 'JSON format error.'}}

URL 工作正常,但我想使用专门的二进制图像数据,而不求助于 Azure Python 包。

最佳答案

根据场景,我重现了这个问题。 Image

要解决此问题,您可以直接传递图像数据并更改代码段中的内容类型

以下是更新后的脚本:

import  requests
import  io
def  analyze_image(image_data):
    analyze_url = "https://<endpoint>.cognitiveservices.azure.com/vision/v3.2/analyze"
    headers = {
        "Content-Type": "application/octet-stream",
        'Ocp-Apim-Subscription-Key': '<your-subscription-key>',
    
    params = {
    "visualFeatures": "Categories,Description,Color",
    }
    response = requests.post(analyze_url, headers=headers,params=params, data=image_data)
    return  response.json()
    
if  __name__ == '__main__':
    image_path = "OIP.jpg"
    with  open(image_path, "rb") as  image_file:
        image_data = image_file.read()
    result = analyze_image(image_data)
    print(result)

更新的脚本已成功执行。

输出Image

关于python - 将原始二进制图像传递到 Azure 认知服务 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76563838/

相关文章:

azure - 如何让 Microsoft Azure Speech To Text 在程序运行时开始转录? (统一,C#)

python - PIL Image as Bytes with BytesIO 防止硬盘保存

python - 在一行中打印输出

python - Gtk 3.0 窗口,扩展器内有 TreeView

python - 在 matplotlib 中添加径向轴标签

c# - 更改 Visual Studio 的默认 Azure 订阅

azure - PowerShell 通过 Azure 管道打开所有网络

python - 在Python REPL中,如何从所有文件中获取最新代码?

azure - 如何在 Multi-Tenancy Azure B2C 登录页面中允许本地帐户的注册选项?

Azure 认知服务 : Custom text classification answering 404 on retrieve request