Skip to content

matplotlib.pyplot.imsave colormaps some grayscale images before saving them #3657

Closed
@jni

Description

@jni

Some people may be using matplotlib as an image IO library. Those people may also be scientists that care about their data being accurately saved on disk. They will be disappointed, however, to find that imsave does nothing of the sort:

In [8]: mpl.pyplot.imsave('io4.png', np.array([[0, 1], [0, 4196]], dtype=np.uint16))

In [10]: im4 = mpl.pyplot.imread('io4.png')

In [11]: im4.shape
Out[11]: (2, 2, 4)

In [12]: np.rollaxis(im4, -1) # display the three channels + alpha of the array
Out[12]: 
array([[[ 0.        ,  0.        ],
        [ 0.        ,  0.49803922]],

       [[ 0.        ,  0.        ],
        [ 0.        ,  0.        ]],

       [[ 0.49803922,  0.49803922],
        [ 0.49803922,  0.        ]],

       [[ 1.        ,  1.        ],
        [ 1.        ,  1.        ]]], dtype=float32)

What is happening here is that imsave has encountered a data type it's not happy with (uint16, a commonly used data format in microscopy and probably other scientific imaging), and decided to silently colormap the values and save them as a uint8 RGBA image. (See #3616 for a longer discussion.) Adding insult to injury, the color mapping is to jet.

In summary:

  • Observed behaviour: imsave colormaps certain images before saving as uint8 RBGA.
  • Desired behaviour: either save the data exactly as given, or raise a ValueError, or at the very least raise a warning.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions