Search code examples
pythonimagematlabmatlab-figure

Show image in python and matlab showing different colors


I'm working on matlab, but I noticed that the image I was loading becomes black-an-white, when the original image has grays in it. I decided to check the image using a imshow on a new file, but it really makes it black and white. My code is simply:

image_path = 'no.png';
img = imread(image_path);

imshow(img);

axis off;

Then I tried to make it grayscale, but the problem was not solved.

Then I tried to use python to show the image, and it showed the image correctly.

import matplotlib.pyplot as plt
import matplotlib.image as mpimg

def show_image(image_path):
    img = mpimg.imread(image_path)
    plt.imshow(img)
    plt.axis('off') 
    plt.show()

# Example usage
image_path = "no.png" 
show_image(image_path)

I don't know what's wrong. This is the original image:

original image

This is the image matlab shows:

matlab image

This is the image python shows:

python image


Solution

  • Actually, the problem comes from the fact that your image is not grayscale, but is indexed.

    image_path = 'no.png';
    [img,map] = imread(image_path); % Returns a non-empty map --> indexed image
    

    Now, you can get the expected output by using the map:

    imshow(img,map);
    axis off;
    

    enter image description here

    You can look at this answer for how to check what the type of your image is, in particular the following part (trimmed for clarity):

    [imageArray, colorMap] = imread(fullImageFileName);
    [rows, columns, numberOfColorChannels] = size(imageArray);
    %
    %
    %
      % Tell user the type of image it is.
      if numberOfColorChannels == 3
        % This is a true color, RGB image.
        %
      elseif numberOfColorChannels == 1 && isempty(colorMap)
        % This is a gray scale image, with no stored color map.
        %
      elseif numberOfColorChannels == 1 && ~isempty(colorMap)
        % This is an indexed image.  It has one "value" channel with a
        % stored color map that is used to pseudocolor it.