0

I have a number of non-JPEG image files that I want to process using Google Cloud Vision, but the API only accepts certain formats (see question Cloud Vision API - PDF OCR and answer https://cloud.google.com/vision/docs/supported-files).

I can use PIL or some such to convert a TIFF to JPEG to be uploaded, but I'd like to avoid a temp file if possible.

So, in python, how do I convert a TIFF in-memory for upload to GCV? numpy array, base64, string..?

jtlz2
  • 7,700
  • 9
  • 64
  • 114
  • Consider writing to a string instead of to a disk file: https://docs.python.org/2/library/stringio.html –  Jul 24 '17 at 07:35
  • wouldn't it be more logic to go for a [BytesIO](https://docs.python.org/3/library/io.html#buffered-streams) instead of a string representation? – Maarten Fabré Jul 24 '17 at 08:18
  • @YvesDaoust So how exactly (example code) do I use to convert to stringio/BytesIO, and how do I send that to GCV? Thanks! – jtlz2 Jul 25 '17 at 06:07
  • Fine, but I don't think it's an unreasonable request. Nor is it straightforward question. Being a coding site, answers are often given in terms of code, no? – jtlz2 Jul 25 '17 at 06:16
  • Also, the GCV documentation is poor/internally written - stackoverflow seems like the obvious location to augment this – jtlz2 Jul 25 '17 at 06:19

1 Answers1

1

As suggested, you should use StringIO or BytesIO for Python 3.

See this question: Python resize image and send to google vision function

Example making a request string:

output = BytesIO()
image_object.save(output, 'JPEG', quality=90)
contents = output.getvalue()
output.close()
ctxt = b64encode(contents).decode()

request_string = [{
    'image': {'content': ctxt},
    'features': [{
        'type': 'TEXT_DETECTION',
        'maxResults': 1
        }]
}]
Pepijn
  • 383
  • 2
  • 13
  • Thank you - just what I was looking for - was all very opaque to me - will give it a whirl :) – jtlz2 Jul 25 '17 at 06:37
  • 1
    Pay attention to the quality setting. The default setting is 75 which might deteriorate your image quality and the subsequent results you get from Google. Setting it too high will increase your image size and you might hit the 4MB image size limit. – Pepijn Jul 25 '17 at 08:04
  • Thanks, indeed, noted! – jtlz2 Jul 25 '17 at 08:49