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

use*_*r21 4 computer-vision python-2.7 google-cloud-vision

由于谷歌视觉对输入图像大小有一些限制,我想首先调整输入图像的大小,然后使用该detect_labels()功能。

这是他们的示例代码

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)
Run Code Online (Sandbox Code Playgroud)

他们用来io打开图像文件。我想知道这样,如何调整内存中图像的大小然后调用detect_labels()

kri*_*aps 5

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

代替

with io.open(path, 'rb') as image_file:
    content = image_file.read()
Run Code Online (Sandbox Code Playgroud)

# 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()
Run Code Online (Sandbox Code Playgroud)