4

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

pm0733464
  • 2,862
  • 14
  • 16
user21
  • 329
  • 2
  • 15
  • Does the client throw any exception when you pass it an oversize image? – kristaps Jul 18 '17 at 20:58
  • Yes, it says image is too large: `google.gax.errors.RetryError: GaxError(Exception occurred in retry method that was not classified as transient, caused by <_Rendezvous of RPC that terminated with (StatusCode.INVALID_ARGUMENT, Some image is too large)>)` – user21 Jul 18 '17 at 21:02

2 Answers2

5

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()
kristaps
  • 1,705
  • 11
  • 15
  • Is there a way to set an upper limit on the resize operation (cf https://stackoverflow.com/questions/45322213/python-set-maximum-file-size-when-converting-pdf-to-jpeg-using-e-g-wand)? – jtlz2 Jul 26 '17 at 12:01
3

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()
DeWil
  • 362
  • 3
  • 10