首页 > 解决方案 > Ms Computer Vision API 图像 url 使用 Python 替换为本地 .jpg

问题描述

我正在尝试在 Pi 上编写一个 python 程序来捕获图像并从 Ms Computer Vision API 获取描述。它正在使用 image_url 作为http://website.com/abc.jpg,但是当我更改为我的本地图像“abc.jpg”时,它有一个错误。

文件“ms.py”,第 71 行,在 response.raise_for_status()

文件“C:\Python27\lib\site-packages\requests-2.19.1-py2.7.egg\requests\models.py”,第 939 行,在 raise_for_status 中引发 HTTPError(http_error_msg, response=self) requests.exceptions。 HTTPError:400 客户端错误:对 url 的错误请求:https ://westcentralus.api.cognitive.microsoft.com/vision/v2.0/analyze?visualFeatures=Categories%2CDescription%2CColor

原始工作代码如下:

import requests
import matplotlib.pyplot as plt
import simplejson as json
from PIL import Image
from io import BytesIO

subscription_key = "XXXX"
assert subscription_key

vision_base_url = "https://westcentralus.api.cognitive.microsoft.com/vision/v2.0/"

analyze_url = vision_base_url + "analyze"

# Set image_url to the URL of an image that you want to analyze.
image_url = "https://upload.wikimedia.org/wikipedia/commons/thumb/1/12/" + \
"Broadway_and_Times_Square_by_night.jpg/450px-Broadway_and_Times_Square_by_night.jpg"

headers = {'Ocp-Apim-Subscription-Key': subscription_key }
params  = {'visualFeatures': 'Categories,Description,Color'}
data    = {'url': image_url}
response = requests.post(analyze_url, headers=headers, params=params, json=data)
response.raise_for_status()

# The 'analysis' object contains various fields that describe the image. The most
# relevant caption for the image is obtained from the 'description' property.
analysis = response.json()
print(json.dumps(response.json()))
image_caption = analysis["description"]["captions"][0]["text"].capitalize()

# Display the image and overlay it with the caption.
image = Image.open(BytesIO(requests.get(image_url).content))
plt.imshow(image)
plt.axis("off")
_ = plt.title(image_caption, size="x-large", y=-0.1)
plt.show()

因此,当将 image_url 替换为“abc.jpg”或“C:/abc.jpg”时,它不起作用。

标签: pythonazurecomputer-visionmicrosoft-cognitive

解决方案


是的,您应该在发送之前阅读图像:

# Set image_path to the local path of an image that you want to analyze.
image_path = "C:/Documents/ImageToAnalyze.jpg"

# Read the image into a byte array
image_data = open(image_path, "rb").read()

response = requests.post(
    analyze_url, headers=headers, params=params, data=image_data)

推荐阅读