How to use a colormap in matlab? - matlab

I'd like to read a custom image and apply a colormap like in the example from matlab. How can I do that? I see the example imageext uses custom images and applies colormaps and I'd like to do the same with my images. How can it be done? I want just to use my own picture for an example like imageext in matlab.
This does not work:
I = im2double(imread('niklas3.png')); figure(1); imshow(I,[]); daspect([1 1 1]); axis off; colormap gray;
niklas3.png:
But this code works:
I = im2double(imread('cameraman.tif')); figure(1); imshow(I,[]); daspect([1 1 1]); axis off; colormap summer;

You can apply a colormap in any image you want if it was previously displayed into a figure.
I recommend you to use imagesc or imshow to display images. In order to do that, you need to load the image with imread. A good practice is to convert your image data to double precision.
I = im2double(imread('cameraman.tif'));
As you can see, im2double converts image data to double precision ranging from 0 values to 1 values. If you do not want this, you can use the double function, ranging from 0 values to 255 value.
Later, you need to display the image into a figure. I strongly recommend to use imagesc instead of imshow, because imagesc allows you to customize your data and your display (for example, adding a different colormap).
figure(1); imagesc(I); daspect([1 1 1]); axis off;
Now, you can use the colormap you want. Type help colormap for more information, but you can use a jet colormap (default), gray, hot, bones, or whatever you want, just typing:
colormap gray;
If you plotted several images, you need to indicate the aimed image with:
figure(1); colormap gray;
If you want to use imshow, just type:
figure(1); imshow(I,[]); daspect([1 1 1]); axis off; colormap gray;
Edited: Once I saw your image, I knew your problem is that you are trying to apply a colormap into a RGB image. That is, you are trying to apply it into a 3D matrix, where rows and columns identify the pixel value and the third dimension identifies the RGB components.
So, you need to convert your RGB image into a 2D matrix (a black and white one). You can do it by performing the mean along the third dimension.
I = nanmean(I,3);
Finally, you should apply the colormap as I said it before. The final code would be:
I = im2double(imread('niklas3.jpg'));
I = nanmean(I,3);
figure(1); imshow(I,[]); daspect([1 1 1 ]); axis off;
colormap jet;
This is the result using a jet colormap:

Related

Colorbar limits not respecting axes clims when displaying an image

Im trying to superimpose a trimesh-plot over a image imshow using hold on. This works fine so far. I'd additionally like to display a colorbar, which works too, but unfortunately it does not adjust to the range specified by caxis, does anyone have an idea how to fix this?
This is an example output: The colourbar should display a range from 1 to z, not from 0 to 60. If we remove imshow everything works fine.
Here my MCVE:
clc;clf;clear
T = [1,2,3;3,1,4]; % triangulation
X = [0,1,1,0]*300; % grid coordinates
Y = [0,0,1,1]*300;
for z = 2:20;
clf;
imshow(imread('board.tif')) % plot image (this is a built in matlab test image)
hold on
Z = [1,1,1,z];
trisurf(T,X,Y,Z) % superimpose plot
colormap hot
caxis([1,z])
colorbar
drawnow
pause(0.5)
end
This appears to be a bug in how older versions of MATLAB handled the colorbar (it's not present with HG2). The "correct" behavior would be that if you have any objects in the current axes that use scaled values, then the colorbar should respect your clims. It seems that MATLAB is using the first child in the current axes to determine whether to respect your clims or not. imshow does not use scaled CDataMapping so colorbar simply ignores your clims.
It looks like you have three options:
Use imagesc rather than imshow
clf;
imagesc(imread('board.tif'));
axis image
hold on
Z = [1,1,1,z];
trisurf(T,X,Y,Z) % superimpose plot
colormap hot
caxis([1,z])
drawnow
colorbar
drawnow
pause(0.5)
Call imshow after you've created your trisurf object
clf;
hold on
Z = [1,1,1,z];
trisurf(T,X,Y,Z) % superimpose plot
colormap hot
him = imshow(imread('board.tif'));
caxis([1,z])
drawnow
colorbar
drawnow
pause(0.5)
Set the CDataMapping property of the image object to 'scaled' (will be ignored when displaying the image since it's RGB but it will allow the colorbar to function properly)
clf;
him = imshow(imread('board.tif'));
set(him, 'CDataMapping', 'scaled')
hold on
Z = [1,1,1,z];
trisurf(T,X,Y,Z) % superimpose plot
colormap hot
caxis([1,z])
drawnow
colorbar
drawnow
pause(0.5)

MATLAB: imagesc() and image() display the same colormap differently

I have some data I would like to display in a picture form. In one case I want to rescale the x and y axis, which leads me to using imagesc. The issue is that the same colormap (jet) looks different in imagesc as compared to image.
Is there a way to make them the same?
I am using MATLAB R2014a.
Demonstration:
Here is how I show them:
figure; image(cancelledmap); colormap(jet); %image
figure; imagesc(y,x,cancelledmap); colormap(jet); %imagesc
And the output:
The colormap settings for both figures are somehow the same, however:
imagesc scales the color axis, whereas image does not. That's why the colors look different. If you click the colorbar button you'll see that they are on different color scales.
You can change the colorscale with caxis.
By the way, if you only want to scale the X- and Y-axes, you can use either function. Just supply your own scaled x and y vectors.

fit axes to contain the image EXACTLY using MATLAB

i have an axes named "axes1" and an image named "im"
How to make image dimensions equal to axes dimensions?
I mean I want to fit axes to contain the image EXACTLY (don't image stretching or image compression)?
Use the command axis image after displaying the image.
I interpret your question you want 1 pixel of your image to be one pixel in the axis.
You will need to do some calculating for that.
I would do it like this:
imagesc(magic(64)) % example image
set(gca,'Units','pixel') % set units to pixel
pos_in_px=get(gca,'Position')
set(gca,'XLim',[1,pos_in_px(3)-pos_in_px(1)]) % set xaxis to the pixel range
set(gca,'YLim',[1,pos_in_px(4)-pos_in_px(2)]) % set yaxis to the pixel range
of course this is a fragile solution - as you zoom or resize the window things may change.
I assume you want to display a color image. Try this (copy-paste in Matlab CLI) :
RGB = imread('ngc6543a.jpg');
[m,n,~] = size(RGB);
figure('Units', 'pixels', 'Position', [40 40 n m]);
image(RGB);
set(gca, 'Position', [0 0 1 1]);
axis equal;
'ngc6543a.jpg' is a standard image provided by Matlab.

MATLAB: Show colorbar of a grayscale image in a figure containing a RGB image

Suppose we have two images:
1) RGB Image:
% initialize RGB image:
rgbIm = zeros(100, 100, 3);
rgbIm(20:80, 20:80, 1) = 1;
2) Grayscale Image:
% initialize grayscale image:
grayIm = zeros(100);
grayIm(20:80, 20:80) = 1;
Lets show both of them:
figure, imshow(rgbIm), colormap('jet'), colorbar;
figure, imshow(grayIm), colormap('jet'), colorbar;
As we can see, the colorbar in the 2nd figure (i.e. grayscale image) makes total sense. On the other hand I can't really understand the information given by the colormap in the 1st figure.
What I would like to achieve is to display the colorbar of the grayscale image in the figure corresponding to the RGB image.
It might seem that this does not make sense but this is just a very minimal example that I just made up to show what I would like to do in a larger project.
Any thoughts?
Thanks a lot :)
EDIT1: Allow me to explain why I would need this
Suppose I compute some physiological parameters one MRI slice in certain regions of interest, yielding something like this:
Now I want to superimpose these parameters on top of the original slice, and I create one RGB image to achieve this:
The colormap does not make sense, and this is why I would like to display the colormap corresponding to the parametric image in the RGB image (i.e. the superimposition image).
Any ideas?
Thank you for your attention.
I still think what you are asking does not make sense.
Let me explain:
What is colorbar? Colorbar is a representation of a function (mapping) from gray-level (scalar) to color. Using jet, in your example, you map the 0 to dark blue and 1 to red.
By asking for a colorbar for an RGB image, you are actually asking for a mapping from RGB triplet to RGB color -- this mapping is the identity mapping! you do not need a colorbar to see this mapping, each pixel represent it!
EDIT
After seeing the edited question, I revise my answer a bit:
Since both MRI signal and whatever physiological parameters you computed makes no sense in RGB space, you have two 1D mappings:
1. MRI signal at each voxel to gray level ("gray" colormap)
2. Physiological measure at each voxel to "jet" color
What I usually do in this cases is convert the 2D MRI slice into RGB gray image by simply replicate it along the third dimension
rgbSlice = twoDSlice(:,:,[1 1 1]);
Now show the images on top of each other
figure;
imshow( rgbSlice );
hold on;
h = imshow( physiologicalParams );
colormap jet;
set(h, 'AlphaData', .5 );
colorbar
You might need to play with the color mapping of the axes using caxis or clim to get it right.
(Answering my own question so I can hopefully help someone in the future)
I just accomplished what I intended, with the help of the above answer and a post from Steve Eddins' blog.
Here's how:
baseImage = baseImage/(max(baseImage(:))); % normalize base (anatomical) image
rgbSlice = baseImage(:,:,[1 1 1]); % converting to RGB (ignore colormaps)
imshow(parameterROIImage, []); % show parametric image
colormap('jet'); % apply colormap
hold on;
h = imshow(rgbSlice); % superimpose anatomical image
set(h, 'AlphaData', ~bwROIlocations); % make pixels in the ROI transparent
colorbar;
where parameterROIImage is:
bwROIlocations is the logical matrix containing the ROI pixels:
Final result:
Thanks for the help Shai.

How can I make a "color map" plot in matlab?

I have some data (a function of two parameters) stored in a matlab format, and I'd like to use matlab to plot it. Once I read the data in, I use mesh() to make a plot. My mesh() plot gives me the the value of the function as a color and a surface height, like this:
What matlab plotting function should I use to make a 2D mesh plot where the dependent variable is represented as only a color? I'm looking for something like pm3d map in gnuplot.
By default mesh will color surface values based on the (default) jet colormap (i.e. hot is higher). You can additionally use surf for filled surface patches and set the 'EdgeColor' property to 'None' (so the patch edges are non-visible).
[X,Y] = meshgrid(-8:.5:8);
R = sqrt(X.^2 + Y.^2) + eps;
Z = sin(R)./R;
% surface in 3D
figure;
surf(Z,'EdgeColor','None');
2D map: You can get a 2D map by switching the view property of the figure
% 2D map using view
figure;
surf(Z,'EdgeColor','None');
view(2);
... or treating the values in Z as a matrix, viewing it as a scaled image using imagesc and selecting an appropriate colormap.
% using imagesc to view just Z
figure;
imagesc(Z);
colormap jet;
The color pallet of the map is controlled by colormap(map), where map can be custom or any of the built-in colormaps provided by MATLAB:
Update/Refining the map: Several design options on the map (resolution, smoothing, axis etc.) can be controlled by the regular MATLAB options. As #Floris points out, here is a smoothed, equal-axis, no-axis labels maps, adapted to this example:
figure;
surf(X, Y, Z,'EdgeColor', 'None', 'facecolor', 'interp');
view(2);
axis equal;
axis off;
gevang's answer is great. There's another way as well to do this directly by using pcolor. Code:
[X,Y] = meshgrid(-8:.5:8);
R = sqrt(X.^2 + Y.^2) + eps;
Z = sin(R)./R;
figure;
subplot(1,3,1);
pcolor(X,Y,Z);
subplot(1,3,2);
pcolor(X,Y,Z); shading flat;
subplot(1,3,3);
pcolor(X,Y,Z); shading interp;
Output:
Also, pcolor is flat too, as show here (pcolor is the 2d base; the 3d figure above it is generated using mesh):
Note that both pcolor and "surf + view(2)" do not show the last row and the last column of your 2D data.
On the other hand, using imagesc, you have to be careful with the axes. The surf and the imagesc examples in gevang's answer only (almost -- apart from the last row and column) correspond to each other because the 2D sinc function is symmetric.
To illustrate these 2 points, I produced the figure below with the following code:
[x, y] = meshgrid(1:10,1:5);
z = x.^3 + y.^3;
subplot(3,1,1)
imagesc(flipud(z)), axis equal tight, colorbar
set(gca, 'YTick', 1:5, 'YTickLabel', 5:-1:1);
title('imagesc')
subplot(3,1,2)
surf(x,y,z,'EdgeColor','None'), view(2), axis equal tight, colorbar
title('surf with view(2)')
subplot(3,1,3)
imagesc(flipud(z)), axis equal tight, colorbar
axis([0.5 9.5 1.5 5.5])
set(gca, 'YTick', 1:5, 'YTickLabel', 5:-1:1);
title('imagesc cropped')
colormap jet
As you can see the 10th row and 5th column are missing in the surf plot. (You can also see this in images in the other answers.)
Note how you can use the "set(gca, 'YTick'..." (and Xtick) command to set the x and y tick labels properly if x and y are not 1:1:N.
Also note that imagesc only makes sense if your z data correspond to xs and ys are (each) equally spaced. If not you can use surf (and possibly duplicate the last column and row and one more "(end,end)" value -- although that's a kind of a dirty approach).
I also suggest using contourf(Z). For my problem, I wanted to visualize a 3D histogram in 2D, but the contours were too smooth to represent a top view of histogram bars.
So in my case, I prefer to use jucestain's answer. The default shading faceted of pcolor() is more suitable.
However, pcolor() does not use the last row and column of the plotted matrix. For this, I used the padarray() function:
pcolor(padarray(Z,[1 1],0,'post'))
Sorry if that is not really related to the original post