2017-07-18 45 views
2

由於谷歌視覺有一些輸入圖像大小restrictions,我想先調整輸入圖像的大小,然後使用detect_labels()函數。Python調整圖像大小併發送到谷歌視覺功能

這裏是他們的sample code

def detect_labels(path): 
"""Detects labels in the file.""" 
vision_client = vision.Client() 

with io.open(path, 'rb') as image_file: 
    content = image_file.read() 

image = vision_client.image(content=content) 

labels = image.detect_labels() 
print('Labels:') 

for label in labels: 
    print(label.description) 

他們使用io打開圖像文件。我想知道如何調整內存的內存大小然後調用detect_labels()

+0

客戶是否引發任何異常,當你把它傳遞一個超大的圖像? – kristaps

+0

是的,它表示圖片太大:'google.gax.errors.RetryError:GaxError(重試方法中發生的異常未被歸類爲瞬態,由RPC的<_Rendezvous引起,終止於(StatusCode.INVALID_ARGUMENT,某些圖像爲太大)>)' – user21

回答

1

您可以通過PIL /枕頭調整圖像大小,然後將它傳遞給客戶端:

更換

with io.open(path, 'rb') as image_file: 
    content = image_file.read() 

# Warning: untested code, may require some fiddling 
import Image, StringIO 

img = Image.open(path) 
img.thumbnail((512, 512)) 
buffer = StringIO.StringIO() 
img.save(buffer, "PNG") 

content = buffer.getvalue() 
+0

有沒有一種方法來設置調整大小操作的上限(參考https://stackoverflow.com/questions/45322213/python-set-maximum-file-size-when-converting-pdf-對JPEG-使用 - 例如棍棒)? – jtlz2