fit axes to contain the image EXACTLY using MATLAB - 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.

Related

Keep subplot in square while having (1,3) tiledlayout [duplicate]

So I have this matrix in MATLAB, 200 deep x 600 wide. It represents an image that is 2cm deep x 6cm wide. How can I plot this image so that it is locked into proper dimensions, i.e. 2cm x 6cm? If I use the image or imagesc commands it stretches it all out of shape and shows it the wrong size. Is there a way to lock it into showing an image where the x and y axes are proportional?
Second question, I need to then set this image into a 640x480 frame (20 pixel black margin on left and right, 280 pixel black margin on bottom). Is there a way to do this?
To keep aspect ratio, you can use axis equal or axis image commands.
Quoting the documentation:
axis equal sets the aspect ratio so that the data units are the same in every direction. The aspect ratio of the x-, y-, and z-axis is adjusted automatically according to the range of data units in the x, y, and z directions.
axis image is the same as axis equal except that the plot box fits tightly around the data`
For second question:
third_dimension_size=1; %# for b&w images, use 3 for rgb
framed_image=squeeze(zeros(640,480,third_dimension_size));
framed_image(20:20+600-1,140:140+200-1)= my_600_200_image;
imagesc(framed_image'); axis image;
set(gca,'DataAspectRatio',[1 1 1])
Second question:
new_image = zeros(480,640);
new_image(20:(200+20-1),20:(600+20-1)) = old_image;
As an alternative to the other answers, you might want:
set(gca, 'Units', 'centimeters', 'Position', [1 1 6 2])
Make sure you do this after plotting the image to get the other axis properties correct.
For the second question, take care with the number of colour channels:
new_image = zeros(480,640, size(old_image));
new_image(20:(200+20-1),20:(600+20-1),:) = old_image;

Matlab: Image plotting resolution/dpi

I am plotting x and y coordinates together with some images but the images are becoming extremely large compared to the axis. How can i set the figure resolution or size so that an image can fit in a small axis range rather than covering the whole graph and also modify the axis range.
Figure without images (below).
Matlab code:
for l = 1:size of array
colormap('gray');
imagesc(X,Y, imrotate(imresize(img,[100 100]),180));
end
By default, imagesc will plot the image using indexed coordinates (pixel spacing of 1). Note the axes limits on this figure:
You can change this by altering the XData and YData properties of the image.
him = imagesc(rand(4), 'XData', [0,1], 'YData', [0 1])
Notice that this changed the scaling of your image. I'm not sure what coordinate system your points are (and if you can provide a little more information I can help you better), but you can adjust the XData and YData to be the appropriate values to match your points.

How do I crop a 2-d surface plot in MATLAB, to remove axes and white margins?

I have written a program to process and print a 81x81 2D surface plot, which needs to be used as an input. Saving the plot made by Matlab includes side axes as well as white margins on the sides.
How do I crop this image to get just the (81pixels)x(81pixels) output as an image?
Try placing this after your figure code, it will remove the margins around your figure.
set(gca,'units','pixels') % set the axes units to pixels
xx = get(gca,'position'); % get the position of the axes;
set(gcf,'units','pixels') % set the figure units to pixels
yy = get(gcf,'position'); % get the figure position;
set(gcf,'position',[yy(1) yy(2) xx(3) xx(4)]) % set the position of the figure to the length and width of the axes
set(gca,'units','normalized','position',[0 0 1 1]) % set the axes units to pixels
You can avoid using surf plot and just save your array as image. So, you have 81x81 array. I'll use this one for the example:
a = magic(81);
Now you need to normalize image in order to have values from 0 to 255:
a = (a - min(min(a)))/(max(max(a))-min(min(a)))*255;
Finally you use imwrite to save your array as image.
imwrite(a,jet(256),'SO_4.png')
The first argument is your 81x81 array. The second argument is colormap. You can specify any colormap you want, but I like the heatmap jet(256). You can skip this argument, in this case the image would be grayscale. From here you can find what colormaps are available and what they look like. The last argument is image name. The result is shown below:
Hope that helps, good luck.

How to use a colormap in 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:

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.