python - 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”时,它不起作用。
解决方案
是的,您应该在发送之前阅读图像:
# 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)
推荐阅读
- html - 根据所选货币在 HTML 页面中显示价格
- python - 使用海龟 Python 测量距离
- javascript - 如何自定义 ace 编辑器自动完成功能?
- cmake - CMAKE_EXPORT_COMPILE_COMMANDS 不起作用,因为许多 cpp 文件以某种方式内置到 1 个大文件中
- reactjs - %public% 变量上的 npx create-react-app 后 index.html 中的警告(在 IntelliJ 中)
- c# - 新手 ASP.net MVC 导出到 Excel
- python - 用 BeautifulSoup 刮 Json 表太熊猫
- javascript - 有什么方法可以仅使用 Leaflet.js 获得类似“超级任天堂模式 7 上的 JRPG”的平面 3D 地图?
- linux-kernel - USB 设备驱动程序的字符设备接口
- pine-script - 退出策略以达到一定的效果