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