Search code examples
imagematlabimage-scalingimshow

what is the difference between image vs imagesc in matlab


I want to know the difference between imagesc & image in matlab

I used this example to try to figure out the difference beween the two but i couldn't explain the difference in the output images by myself; could you help me with that ?

I = rand(256,256);
for i=1:256

for j=1:256
    I(i,j) = j;


 end
end
figure('Name','Comparison between image et imagesc')
subplot(2,1,1);image(I);title('using image(I)');
subplot(2,1,2);imagesc(I);title('using imagesc(I)');
figure('Name','gray level of image');
image(I);colormap('gray');
figure('Name','gray level of imagesc');
 imagesc(I);colormap('gray');

Solution

  • image displays the input array as an image. When that input is a matrix, by default image has the CDataMapping property set to 'direct'. This means that each value of the input is interpreted directly as an index to a color in the colormap, and out of range values are clipped:

    image(C) [...] When C is a 2-dimensional MxN matrix, the elements of C are used as indices into the current colormap to determine the color. The value of the image object's CDataMapping property determines the method used to select a colormap entry. For 'direct' CDataMapping (the default), values in C are treated as colormap indices (1-based if double, 0-based if uint8 or uint16).

    Since Matlab colormaps have 64 colors by default (EDIT: since R2019b they have 256 colors by default), in your case this has the effect that values above 64 are clipped. This is what you see in your image graphs.

    Specifically, in the first figure the colormap is the default parula with 64 colors; and in the second figure colormap('gray') applies a gray colormap of 64 gray levels. If you try for example colormap(gray(256)) in this figure the image range will match the number of colors, and you'll get the same result as with imagesc.

    imagesc is like image but applying automatic scaling, so that the image range spans the full colormap:

    imagesc(...) is the same as image(...) except the data is scaled to use the full colormap.

    Specifically, imagesc corresponds to image with the CDataMapping property set to 'scaled':

    image(C) [...] For 'scaled' CDataMapping, values in C are first scaled according to the axes CLim and then the result is treated as a colormap index.

    That's why you don't see any clipping with imagesc.