python – Save 16-bit numpy arrays as 16-bit PNG image

python – Save 16-bit numpy arrays as 16-bit PNG image

It looks like imageio.imwrite will do the right thing if you convert the data type of the array to numpy.uint16 before writing the PNG file:

imageio.imwrite(result.png, im.astype(np.uint16))

When I do that, result.png is a 16 bit gray-scale PNG file.

If you want the image to have the full grayscale range from black to white, youll have to scale the values to the range [0, 65535]. E.g. something like:

im2 = (65535*(im - im.min())/im.ptp()).astype(np.uint16)

Then you can save that array with

imageio.imwrite(result2.png, im2)

For writing a NumPy array to a PNG file, an alternative is numpngw (a package that I created). For example,

from numpngw import write_png

im2 = (65535*(im - im.min())/im.ptp()).astype(np.uint16)
write_png(result2.png, im2)

If you are already using imageio, there is probably no signficant advantage to using numpngw. It is, however, a much lighter dependency than imageio–it depends only on NumPy (no dependence on PIL/Pillow and no dependence on libpng).

python – Save 16-bit numpy arrays as 16-bit PNG image

Leave a Reply

Your email address will not be published.