将本地图像用于Read 3.0,Azure认知服务,计算机视觉

问题描述

我正在尝试在文本识别脚本中使用本地图像,该文档具有以下示例(https://docs.microsoft.com/en-us/azure/cognitive-services/computer-vision/quickstarts/python-hand-text):

enter image description here

但是,当我将image_url更改为本地文件路径时,它将发送HTTPError:400客户端错误错误的url请求。我尝试了其他教程,但似乎无济于事。

任何帮助将不胜感激:)

解决方法

认知服务API将无法通过本地计算机上文件的URL找到图像。相反,您可以在请求的正文中使用图像的二进制数据调用相同的端点。

在示例Python代码中替换以下几行

image_url = "https://raw.githubusercontent.com/MicrosoftDocs/azure-docs/master/articles/cognitive-services/Computer-vision/Images/readsample.jpg"

headers = {'Ocp-Apim-Subscription-Key': subscription_key}
data = {'url': image_url}
response = requests.post(
    text_recognition_url,headers=headers,json=data)

使用

headers = {'Ocp-Apim-Subscription-Key': subscription_key,'Content-Type': 'application/octet-stream'}
with open('YOUR_LOCAL_IMAGE_FILE','rb') as f:
    data = f.read()
response = requests.post(
    text_recognition_url,data=data)

并替换以下行:

image = Image.open(BytesIO(requests.get(image_url).content))

使用

image = Image.open('./YOUR_LOCAL_IMAGE_FILE.png')