有什么方法可以將PIL影像傳遞給google cloud vision嗎?
我試圖使用io.Bytes、io.String和Image.tobytes(),但我總是得到:
Traceback (most recent call last):
"C:Users...vision_api.py", line 20, in get_text
image = vision.Image(content)
檔案 "C:...venvlibsite-packagesprotomessage.py", line 494, in __init__
raise TypeError(
型別錯誤。無效的構造input for Image:b'Max81Max81Lax81Max81Max81Max81Max81Max81Max81Max81Lax81Max81Max81Max80Max81Lax81Max81Max81Max80Max81Max81Max81Max8 ...
或者,如果我直接傳遞PIL-Image,則這樣:
TypeError: Invalid constructor input for Image: <PIL.Image.Image image mode=RGB size=480x300 at 0x1D707131DC0>
這是我的代碼:
這是我的代碼。
image = Image.open(path).convert('RGB'/span>) # Opening the saved image
cropped_image = image.crop((30, 900, 510, 1200) # 裁剪影像。
vision_image = vision.Image(# 我傳遞了不同的選項) # 這里我需要傳遞影像,但我不知道如何傳遞。
client = vision.ImageAnnotatorClient()
response = client.text_detection(image=vision_image) # text detection using google-vision-api
為清晰起見:
我希望google文本檢測只分析保存在我的磁盤上的圖片的某一部分。所以我的想法是使用PIL裁剪影像,然后將裁剪后的影像傳遞給google-vision。但是不可能將一個PIL-Image傳遞給vision.Image,因為我得到了上面的錯誤。
來自Google的檔案。
這可以在vision.Image類中找到:
Attributes:
content(bytes)。
圖片內容,表示為作為一個bytes的流。注意:由于
與 所有 ``bytes``欄位,protobuffers使用純二進制
表示,而JSON表示則使用base64。
目前,這個欄位只適用于對于BatchAnnotateImages
請求。它不不作業為AsyncBatchAnnotateImages
請求。
一個可行的方案是將PIL-Image保存為我磁盤上的PNG/JPG,然后用以下方式加載它:
withio.open(file_name, 'rb'/span>) as image_file:
content = image_file.read()
vision_image = vision.Image(content=content)
但是這很慢,而且似乎沒有必要。對我來說,使用google-vision-api背后的全部意義在于與open-cv相比的速度。
CodePudding
如果有整個錯誤堆疊和更準確的代碼片段就好了。 但從所提供的資訊來看,這似乎是兩個不同的 "影像 "的混淆。可能是一些復制/粘貼錯誤,因為教程有完全相同的行:response = client.text_detection(image=image)
但是提到的教程image是由vision.Image()創建的,所以我認為在提出的代碼中應該是:
response = client.text_detection(image=vision_image)
因為,至少如果我正確理解代碼片段,image是PIL影像,而vision_image是Vision影像,應該傳遞給text_detection方法。因此,無論在vision.Image()中做什么,都不會對錯誤按摩產生影響。
uj5u.com熱心網友回復:
據我所知,你從一個PIL Image開始,你想在記憶體中獲得一個PNG影像而不去磁盤。所以你需要這樣:
#!/usr/bin/env python3。
from PIL import Image
from io import BytesIO
# Create PIL Image like you have - filled with red[/span]。
im = Image. new('RGB', (320, 240), (255,0, 0)
# Create in-memory PNG - like you want for Google Cloud Vision
buffer = BytesIO()
im.save(buffer, format="PNG"/span>)
#查看前幾個位元組 #查看前幾個位元組
PNG = buffer.getvalue()
print(PNG[:20] )
它列印了這個,這正是你將影像以PNG形式寫入磁盤,然后以二進制形式讀回的結果--只不過這是在記憶體中完成的,而不是在磁盤上:
span class="hljs-string">b'x89PNG
x1a
x00x00x00
IHDRx00x00x01@'
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/326121.html
標籤:
下一篇:移除面具影像中不需要的部分
