Python – Read 16-bit PNG image file using Python

png, python, python-imaging-library

I'm trying to read a PNG image file written in 16-bit data type. The data should be converted to a NumPy array. But I have no idea how to read the file in '16-bit'. I tried with PIL and SciPy, but they converted the 16-bit data to 8-bit when they load it. Could anyone please let me know how to read data from a 16-bit PNG file and convert it to NumPy array without changing the datatype?

The following is the script that I used.

from scipy import miscimport numpy as npfrom PIL import Image#make a png file    a = np.zeros((1304,960), dtype=np.uint16)a[:] = np.arange(960)misc.imsave('16bit.png',a)#read the png file using scipyb = misc.imread('16bit.png')print "scipy:" ,b.dtype#read the png file using PILc ='16bit.png')   d = np.array(c)print "PIL:", d.dtype               

Best Solution

I have the same problem here. I tested it even with 16 bit images i created by my own. All of them were opened correctly when i loaded them with the png package. Also the output of 'file ' looked okay.

Opening them with PIL always led to 8-bit numpy-arrays.

Working with Python 2.7.6 on Linux btw.

Like this it works for me:

import pngimport numpy as npreader = png.Reader( path-to-16bit-png )pngdata = = np.array( map( np.uint16, pngdata[2] ) print( px_array.dtype )

Maybe someone can give more information under which circumstances the former approach worked? (as this one is pretty slow)

Thanks in advance.