ShineZero
ShineZero

Reputation: 89

MATLAB imread bmp image is not correct

I have a grayscale image.

When I load it in MATLAB, I found that the gray levels don't match the original image. The read in image with MATLAB is more brighter than the original image. What am I doing wrong? How can I solve it?

Left one is read matlab, right one is original

enter image description here

The original bmp file can be downloaded here.

Upvotes: 4

Views: 4231

Answers (1)

rayryeng
rayryeng

Reputation: 104493

It turns out your image has an associated colour map with it. When you do X = imread('Lena.bmp');, you are reading in an indexed image. This means that each value is an index into a colour map - this isn't the same the actual intensities themselves.

Therefore, read in the image with the colour map, then convert the indexed image with the colour map to an actual image. You'd have to call the two output variant of imread, then convert the indexed image accordingly with ind2rgb:

[X,map] = imread('Lena.bmp');
im = ind2rgb(X,map);
imshow(im);

I get this image, which matches with your right image:

enter image description here


In the future, if you're not sure whether your image has a colour map with it or not, call the two-output variant, then check to see if the second output, which contains the colour map, is non-empty. If it is, then call ind2rgb accordingly:

[im, map] = imread('...'); %// Place your input image location here
if ~isempty(map)
    im = ind2rgb(im,map);
end

Because your image is grayscale, if you want to convert this to single channel, either use rgb2gray, or extract any channel from the image. Grayscale works such that each channel in the RGB image is exactly the same.

Therefore:

im = rgb2gray(im); 
%// Or
%im = im(:,:,1);

The image will also be of type double, so to convert to uint8 (the most common type), simply do:

im = im2uint8(im);

Upvotes: 5

Related Questions