我一直在编写 Python 代码来传递包含图像的文件夹,以便使用 Cognitive Vision API 进行分析。当我对在线托管的任何图像使用 URL 时,我的代码工作正常。
但是,我在从本地机器传递图像时遇到了一些困难。我尝试使用以下方法将文件路径转换为 URL:
imageurl = pathlib.Path(path).as_uri()
有什么办法吗?我有大约 2000 张图像需要分析。
此帖Uploading an image to Microsoft Cognitive Services?提供了一些关于如何使用 C# 执行此操作的见解,但我没有找到任何类似的 python 文档。
提前致谢。
请您参考如下方法:
计算机视觉 API 文档说明如下:
Request body:
Input passed within the POST body. Supported input methods: raw image binary or image URL.
因此,如果无法在线获取图片(通过 URL),您需要将原始二进制文件作为 POST 请求的主体进行传递。
这是一个示例,使用 Requests图书馆。
import requests
img_filename = '<your image path and filename>'
with open(img_filename, 'rb') as f:
img_data = f.read()
# you'll need to define the following variables yourself:
# - params
# - header
r = requests.post(api_url,
params=params,
headers=header,
data=img_data)
我还有一篇博文可能会对您有所帮助:Using Microsoft Cognitive Services to perform OCR on images .这包含用于上传图像和检索结果的 Python 示例代码。它使用计算机视觉 API 的 OCR 部分,但它应该与您尝试做的类似。
