When saving a 2-dimensional Numpy array (of single values) with Scipy toimage
or imsave
the pixel values do not exactly match those in the Numpy array. Instead there are areas, mostly at edges, where the image algorithm seems use some sort of interpolation.
Is there an option to stop that interpolation and retain the exact data (e.g. 7 always gets rgb(7,7,7) in a PNG?
If you have a 2D numpy array, then you are saving into a grayscale PNG so you never get an rgb image (only one channel). I'm not sure what you mean by single values, perhaps it is single precision floats? Although the PIL supports single precision floats, PNG does not. Saving to PNG you can either use 8-bits per channel (the default) or 16-bits per channel. This means that your array will be scaled to a maximum of 2^8/2^16 (8/16 bits), and converted to integer. It is in this conversion that results may vary slightly.
With
scipy.misc.image
there seems to be no option to save as 16-bit, so it will always write an 8-bit PNG. But you can usescipy.misc.toimage
to create a 16-bit image, just be sure to passmode='I'
. Also be sure to specify the array min and max to avoid scaling. Here's how to use it to save a 16-bit png:Note that in this example I used
int32
for data type. However, the data must still fit in auint16
. If you put negative values or values larger than 2^16, those will be clipped in the save to PNG. Conversely, even thoughsp.misc.imread
reads asint32
, the data will never be more thanuint16
.In summary: if you want to write exactly the same numpy array to a PNG you need to make sure it is of
uint8/uint16
type, and that you pass the correcthigh/low/mode
toscipy.misc.toimage
.