英文:
Passing raw binary image to Azure Cognitive Services API
问题
我想使用Azure的Analyze Images API,通过原始Python请求传递二进制图像数据,而不是URL。我使用io模块从图像中获取二进制数据。
with io.BytesIO() as output:
tmp_imp.save(output, format="JPEG")
contents = output.getvalue()
payload = {
{'url': contents}
}
然后将其作为'url'传递给payload。
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包。
英文:
I want to use Analyze Images API from Azure with raw Python requests passing binary image data rather than URL. I use the io module to get binary data from the image
with io.BytesIO() as output:
tmp_imp.save(output, format="JPEG")
contents = output.getvalue()
payload = {
{'url': contents}
}
Then I pass it as 'url' to payload
response = requests.post(analyze_url, headers=headers, params=params, data=json.dumps(payload))
The error I receive indicates there's a JSON format error, but I don't understand how to fix it
{'error': {'code': 'InvalidArgument', 'innererror': {'code': 'BadArgument', 'message': 'JSON format error.'}, 'message': 'JSON format error.'}}
URLs work fine, but I want to use specifically binary image data without resorting to Azure Python packages.
答案1
得分: 1
根据情景,我已经重现了这个问题。
要解决这个问题,您可以直接传递图像数据并在您的代码片段中更改内容类型。
以下是更新后的脚本:
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)
更新后的脚本成功执行。
输出
英文:
Based on the scenario, I have reproduced the issue.
To solve this, you can directly pass the image data and change the content type in your code snippet.
Below is the updated script:
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)
Updated Script successfully executed.
Output
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论