如何将 PIL.Image 作为图像流传递给 ComputerVisionClient read_in_stream

问题描述 投票:0回答:1

我正在开发一个 python 服务,其中我提供了一个图像作为

PIL
图像。 我想使用
ComputerVisionClient
将此图像传递到 Azure Vision。

我的设置是正确的,因为我可以在本地测试时传入本地文件和 URL,并且它们工作正常。

我目前正在尝试将图像转换为 BufferedReader,但对 read_in_stream 的调用最终会返回错误的请求。

我最终得到了一个 BufferedReader 对象,但它显然不是它需要的形状。

computervision_client = ComputerVisionClient(_self.AV_LABEL_URL, CognitiveServicesCredentials(_self.AV_LABEL_SERVICE_KEY))
        
buffered = BytesIO()
image.save(buffered, format="JPEG")
buffered.mode = "rb"
buffered.name = "image.JPEG"
stream = io.BufferedReader(buffered);

results = computervision_client.read_in_stream(stream, raw = True)  

关于我需要做什么才能使其可接受的任何想法,或者将 PIL 图像转换为 read_in_stream 的流的另一种方法?

python python-imaging-library bufferedreader
1个回答
0
投票

我遇到的问题是调用保存后我没有将蒸汽重置回起始位置。即seek(0) 下面的代码有效。

computervision_client = ComputerVisionClient(_self.AV_LABEL_URL, CognitiveServicesCredentials(_self.AV_LABEL_SERVICE_KEY))

buffered = BytesIO()
image.save(buffered, "JPEG")

with io.BufferedReader(buffered) as image_stream:
    image_stream.seek(0) # reset the file location. The file would be at the end of the file after saving the image above.
    results = computervision_client.read_in_stream(image_stream, raw = True)  

operation_location = results.headers["Operation-Location"]
operation_id = operation_location.split("/")[-1]

# Wait for the asynchronous operation to complete. This is just POC and should look at other ways to do this.
exit = 0
while exit < 30:
    read_results = computervision_client.get_read_result(operation_id)
    if read_results.status not in [OperationStatusCodes.running, OperationStatusCodes.not_started]:
        break
    time.sleep(1)
    exit = exit + 1
© www.soinside.com 2019 - 2024. All rights reserved.