Python 调整图像大小并发送到 google 视觉函数

Python resize image and send to google vision function

由于google视觉对输入图像大小有一些restrictions,我想先调整输入图像的大小,然后使用detect_labels()函数。

这是他们的 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()

您可以通过PIL/Pillow调整图像大小,然后将其传递给客户端:

替换

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()

python3的代码:

致谢:@kristaps

import io
from PIL import Image
img = Image.open(path)
img.thumbnail((512, 512))
buffer = io.BytesIO()
img.save(buffer, "JPEG")
content = buffer.getvalue()