我想使用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 包。
最佳答案
根据场景,我重现了这个问题。
要解决此问题,您可以直接传递图像数据并更改代码段中的内容类型。
以下是更新后的脚本:
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)
更新的脚本已成功执行。
输出
关于python - 将原始二进制图像传递到 Azure 认知服务 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76563838/