Python调整图像大小并发送到谷歌视觉功能

问题描述 投票:2回答:2

由于谷歌视觉在输入图像大小上有一些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()

python-2.7 computer-vision google-cloud-vision
2个回答
3
投票

您可以通过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()

1
投票

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()
© www.soinside.com 2019 - 2024. All rights reserved.