我正在尝试在Pi上编写一个python程序来捕获图像并从计算机视觉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 raise 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"时,它不起作用。
是的,您应该在发送之前阅读图像,如下所示:
# 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)
image_path设置为要分析的图像的本地路径。
image_path ="图像位置(本地路径(">
将图像读入字节数组
image_data = open(image_path, "rb"(.read((
headers = {'Ocp-Apim-Subscription-Key': subscription_key, 'Content-Type': 'application/octet-stream'}
params = {'visualFeatures': 'Categories,Description,Color'}
响应 = requests.post( ocr_url, headers=headers, params=params, data=image_data(
response.raise_for_status((
"分析"对象包含描述图像的各种字段。与图像最相关的标题是从"description"属性中获取的。
analysis = response.json((
打印(分析(