saving python PIL image from Google cloud datalab to Google cloud storage

Viewed 1440

I am trying to save a PIL image to google cloud storage from Datalab.

from PIL import Image
out_image = Image.open( StringIO( gs_buck_obj.read_stream() ) )

# run through cloud vision api and do some stuff
....

my_file = StringIO()
out_image.save(my_file , "PNG")
**This is where I am not sure what to do but have tried next line
gs_buck_obj_out.write_stream(my_file.getvalue(), 'text/plain')
1 Answers

This stackoverflow question raises the question of a python open wrapper for all gs:// paths. A very clean solution lies in using the file_io module in tensorflow.

Example:

from tensorflow.python.lib.io.file_io import FileIO

with FileIO('gs://my-bucket/20180101/my-file.txt', 'r') as f:
   print(f.readlines()) # works

with FileIO('gs://my-bucket/20180101/my-file.txt', 'w') as f:
   f.write('I love roti prata.') # works

with FileIO('my-file.txt', 'w') as f:
   f.write('I love palak paneer.') 
   # also works with local files in reading and writing

As stated by this post, Cloud Datalab does supports tensorflow. And FileIO supports 'wb' (write byte) mode. So a solution to your problem would be

with FileIO('out_image.png', 'wb') as f:
    out_image.save(f, "PNG")
Related