Python resize image and send to google vision func

2019-05-19 16:12发布

Since google vision has some restrictions on input image size, I want to first resize input image and then use the detect_labels() function.

Here's their 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)

they use io to open the image file. I wonder in this way, how to resize the image in memory and then call detect_labels() ?

2条回答
对你真心纯属浪费
2楼-- · 2019-05-19 16:20

You can resize the image via PIL/Pillow and then pass it to the client:

replace

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

with

# 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()
查看更多
Evening l夕情丶
3楼-- · 2019-05-19 16:25

Code for python3:

Credits : @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()
查看更多
登录 后发表回答