Python 如何通过表单识别器使用Azure函数Blob触发器中的图像
我正在尝试使用Azure函数包装一个使用Python编写的表单识别器的应用程序。我的问题是使用BlobTrigger将JPEG格式转换为表单识别器可以使用的格式 打开图像的基本代码是Python 如何通过表单识别器使用Azure函数Blob触发器中的图像,python,azure-functions,microsoft-cognitive,form-recognizer,Python,Azure Functions,Microsoft Cognitive,Form Recognizer,我正在尝试使用Azure函数包装一个使用Python编写的表单识别器的应用程序。我的问题是使用BlobTrigger将JPEG格式转换为表单识别器可以使用的格式 打开图像的基本代码是 从PIL导入图像 从io导入字节io 将azure.1函数导入为func def main(blobin:func.InputStream,blobout:func.Out[bytes],context:func.context): image=image.open(blobin) 该图像具有类:“PIL.Jpe
从PIL导入图像
从io导入字节io
将azure.1函数导入为func
def main(blobin:func.InputStream,blobout:func.Out[bytes],context:func.context):
image=image.open(blobin)
该图像具有类:“PIL.JpegImagePlugin.JpegImageFile”
调用表单识别器分析的代码如下所示:
base\u url=r”“+”/formrecognizer/v1.0-preview/custom
model_id=“”
标题={
“内容类型”:“图像/jpeg”,
“Ocp Apim订阅密钥”:“,
}
resp=无
尝试:
url=base\u url+“/models/”+model\u id+“/analyze”
resp=http_post(url=url,data=image,headers=headers)
打印(“响应状态代码:%d”%resp.status\u code)
例外情况除外,如e:
打印(str(e))
不幸的是,http_post中的data=image需要是类:“bytes”
因此,我尝试了各种方法使用PIL将输入图像转换为字节格式
我的两个主要方法是
以BytesIO()作为输出的:
使用Image.open(输入图像)作为img:
img.save(输出“JPEG”)
image=output.getvalue()
及
image=image.open(输入图像)
imgByteArr=io.BytesIO()
image.save(imgByteArr,format='JPEG')
imgByteArr=imgByteArr.getvalue()
这两种方法都为我提供了字节格式,但它仍然不起作用。不管怎样,我最终的回答是:
{'error': {'code': '2018', 'innerError': {'requestId': '8cff8e76-c11a-4893-8b5d-33d11f7e7646'}, 'message': 'Content parsing error.'}}
有人知道解决这个问题的正确方法吗?根据GitHub repo提供的类
func.InputStream
的源代码,您可以通过read
函数直接从func.InputStream
类的blobin
变量获取图像字节,如下图所示
同时,请参阅文档,内容类型
标题应为多部分/表单数据
因此,我将官方示例代码更改为在Azure函数中使用,如下所示
import http.client, urllib.request, urllib.parse, urllib.error, base64
import azure.functions as func
headers = {
# Request headers
'Content-Type': 'multipart/form-data',
'Ocp-Apim-Subscription-Key': '{subscription key}',
}
params = urllib.parse.urlencode({
# Request parameters
'keys': '{string}',
})
def main(blobin: func.InputStream):
body = blobin.read()
try:
conn = http.client.HTTPSConnection('westus2.api.cognitive.microsoft.com')
conn.request("POST", "/formrecognizer/v1.0-preview/custom/models/{id}/analyze?%s" % params, body, headers)
response = conn.getresponse()
data = response.read()
print(data)
conn.close()
except Exception as e:
print("[Errno {0}] {1}".format(e.errno, e.strerror))
请不要在仅支持Python 3.6的Azure函数中使用任何Python 2函数