matlabpngimreadpaint.net

MATLAB imread() wrong gray scale


I made a simple grayscale image with paint.net:

image I drew

Then I simply read the image using MATLAB imread() and got something like this (same thing for Octave):

enter image description here

I checked the background value and it's 55 instead of 255.

I then tried the same thing in Python using pyplot.imread() and get the expected result:

enter image description here

I saw this a couple of times even when I was reading something like Lena in MATLAB -- the gray scale was totally messed up. Does anyone know what's wrong with imread in MATLAB (and Octave)?


Solution

  • Your PNG image is an RGB image, not a gray-value image. It was saved as an indexed image, meaning that 56 different RGB values were stored in a table, and the image references those RGB values by specifying an index for each pixel.

    The image you're seeing consists of the indices into the color table, not the actual RGB values saved.

    You need to read both the indices and the color map as follows:

    [img,cm] = imread('https://i.sstatic.net/rke2o.png');
    

    Next, you can recover the original RGB image using ind2rgb, or, given that you are looking for a gray-value image, you can recover the gray-values using ind2gray:

    img = ind2gray(img,cm);