Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scikit-image save image to a bytestring

I'm using scikit-image to read an image:

img = skimage.io.imread(filename)

After doing some manipulations to img, I'd like to save it to an in-memory file (a la StringIO) to pass off to another function, but it looks like skimage.io.imsave requires a filename, not a file handle.

I'd like to avoid hitting the disk (imsave followed by read from another imaging library) if at all possible. Is there a nice way to get imsave (or some other scikit-image-friendly function) to work with StringIO?

like image 889
Jason Sundram Avatar asked Apr 23 '13 08:04

Jason Sundram


1 Answers

Update: 2020-05-07

We now recommend using the imageio library for image reading and writing. Also, with Python 3, StringIO changes to BytesIO:

from io import BytesIO
import imageio

buf = BytesIO()
imageio.imwrite(buf, image, format='png')

scikit-image stores images as numpy arrays, therefore you can use a package such as matplotlib to do so:

import matplotlib.pyplot as plt
from StringIO import StringIO

s = StringIO()

plt.imsave(s, img)

This may be worth adding as default behaviour to skimage.io.imsave, so if you want you can also file an issue at https://github.com/scikit-image/scikit-image.

like image 108
Stefan van der Walt Avatar answered Sep 18 '22 15:09

Stefan van der Walt