使用Python将Computer Vision API图像URL替换为本地.jpg

问题描述 投票:0回答:2

我正在尝试在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”时,它无效。

python azure computer-vision microsoft-cognitive
2个回答
1
投票

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

# 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)

0
投票

Set image_path to the local path of an image that you want to analyze.

image_path =“图像位置(本地路径)”

Read the image into a byte array

image_data = open(image_path,“rb”)。read()

headers = {'Ocp-Apim-Subscription-Key':subscription_key,'Content-Type':'application / octet-stream'}

params = {'visualFeatures':'Categories,Description,Color'}

response = requests.post(ocr_url,headers = headers,params = params,data = image_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()

打印(分析)

© www.soinside.com 2019 - 2024. All rights reserved.