我正在尝试使用Azure函数来包装一个使用Python编写的Form-Recognizer的应用程序。我的问题是使用BlobTrigger将JPEG格式转换为Form-Recognizer可以使用的格式。
打开图像的基本代码是
from PIL import Image
from io import BytesIO
import azure.functions as func
def main(blobin: func.InputStream, blobout: func.Out[bytes], context: func.Context):
image = Image.open(blobin)图像有类:'PIL.JpegImagePlugin.JpegImageFile‘。
调用Form-Recognizer analyze的代码如下:
base_url = r"<url>" + "/formrecognizer/v1.0-preview/custom"
model_id = "<model-id>"
headers = {
'Content-Type': 'image/jpeg',
'Ocp-Apim-Subscription-Key': '<subscription-key>',
}
resp = None
try:
url = base_url + "/models/" + model_id + "/analyze"
resp = http_post(url = url, data = image, headers = headers)
print("Response status code: %d" % resp.status_code)
except Exception as e:
print(str(e))不幸的是,http_post中的data = image需要是类:'bytes‘。
因此,我尝试了各种方法,使用PIL将输入图像转换为字节格式。
我的两个主要方法是
with BytesIO() as output:
with Image.open(input_image) as img:
img.save(output, 'JPEG')
image = output.getvalue()和
image = Image.open(input_image)
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.'}}有谁知道解决这个问题的正确方法吗?
发布于 2019-09-03 14:17:20
根据GitHub repo Azure/azure-functions-python-library中func.InputStream类的源代码blob.py,您可以通过func.InputStream类的read函数直接从该类的blobin变量中获取图片字节,如下图所示。

同时,参考文档Form Recognizer API,Content-Type头部应为multipart/form-data。
因此,我将官方的示例代码更改为在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函数。
https://stackoverflow.com/questions/57715004
复制相似问题