numpy.array to PNG file and back

Jonathan Livni picture Jonathan Livni · Aug 27, 2014 · Viewed 8.3k times · Source

I have a 2d numpy.array object of dtype=uint16 representing a grayscale image. How do I save it to a PNG file and then read it back, obtaining the same array?

Answer

ChrisB picture ChrisB · Aug 27, 2014

scikit-image makes this pretty easy:

from skimage.io import imread, imsave
import numpy as np

x = np.ones((100, 100), dtype=np.uint16)
imsave('test.png', x)
y = imread('test.png')
(x == y).all()  # True