MATLAB how to get rid from whitespace when saving figures as JPG - matlab

I am writing a code for flowers recognition in MATLAB
but whenever I want to save a figure
it is saved with a white border - margin
how can I remove it
and save it as the exact size of the original image?
any help would be much appreciated

You can use getframe(gca) to grab the axes and not the entire figure (which is what would happen with simply getframe alone or getframe(gcf)). Then convert that frame to an image with frame2im. Then you can write that image to file with imwrite.
figure;
plot(x,y);
axis off
img = frame2im(getframe(gca));
imwrite(img,'myImage.png');

This might help:
figure('Color','none');
plot(1:10,1:10)
axis off
set(gca,'Color','none');
print ('-djpeg', 'no_background.jpg')

Related

MatLab reducing bitdepth in plotted images?

I am plotting the feature matches between two scenes like this:
%...import, preprocessing, and stuff
%"Sandwich" Image1 and Image2 in a new image Image
ImSize=[size(Image1,1)+size(Image2,1),max(size(Image2,2),size(Image2,2))];
Image=zeros(ImSize);
Image(1:size(Image1,1),1:size(Image1,2))=Image1;
Image(size(Image1,1)+1:end,1:size(Image2,2))=Image2;
%show Image
imshow(Image,[]);
hold on
%plot keypoints and matching lines in all colors
cc=hsv(size(Keypoints1,1));
for ii=1:size(Keypoints1,1)
plot(Keypoints1(ii,1),Keypoints1(ii,2),'o','color',cc(ii,:))
plot(Keypoints2(ii,1),Keypoints2(ii,2)+size(Image1,1),'o','color',cc(ii,:))
line([Keypoints1(ii,1),Keypoints2(ii,1)],[Keypoints1(ii,2),Keypoints2(ii,2)+size(Image1,1)],'color',cc(ii,:),'LineWidth',0.5)
end
This normaly works alright and Matlab plots the entire bitdepth
but with increasing number of lines, I will start seeing a reduction in the bitdepth leading to binary images and even all black:
I know plotting this many lines is far from ideal, but still I would like to know why this is happening. Are there any mechanisms of matlab figures I should understand to explain this behaviour?
Note: this is only a problem displaying the images, saving them as .bmp,jpg,... will produce normal pictures.
try different renderers? Add this at the beginning of your script
h=figure;
set(h,'renderer','opengl');
Instead of 'opengl', also try 'painters' and 'zbuffer'

Convert just the content of a figure to an image in MATLAB

I am currently using getframe() and frame2im in MATLAB to convert a figure of a plot to an image.
I just realized that this is working almost like a screenshot of the figure, with all the axes and labels taken into account as well.
How can I convert JUST the contents of the figure (aka the "plot") into an image?
I don't really want to save all of them to file first.
You can use the getframe / cdata idiom. What this will do is that if you call getframe on the current frame in focus without any parameters, it will return a structure to you that contains a structure element called cdata. This stores the RGB pixel array of just the figure contents themselves. The axes and labels are not captured - only what is painted onto the figure is captured.
Here's an example to get you started:
im = imread('cameraman.tif');
imshow(im);
h = getframe;
out = h.cdata;
figure;
imshow(out); %// Should give you the contents within the imshow frame.
FWIW, I also answered this same question here, though it was for a different situation: keep new image when drawing lines by dragging the mouse in matlab
As far as i know, cdata DOES NOT WORK. I had a major problem recently with the same thing - the only work around i could find is to crop each image after using getframe and cdata - this will work fine for images that are all the same size (ugly as it is - you just need to find the grey edges in the image), but if the images are all different, this wont work (well, it wont work well. there might be some way to automatically adjust the crop size)

MATLAB's 'saveas' saves my figure as squares. But I want them to be more rectangular

I am using MATLABs 'saveas' to save off one of my figures as a .png or .jpg or whatever.
So I just do:
y = randn(1,00);
plot(y); grid on;
saveas(gcf,'y','png');
Now the problem is that the png or final picture comes out as a perfect square - even if I manually stretch the figure before I use the 'saveas' command.
How do I get it so save something more rectangular?
Thanks!
Here's a short sample taken from a mathworks discussion
figure('units','pix','pos',[100 100 200 400]) % create a 200x400 image
>> imagesc(rand(10,10)) % put some random data in it
>> print(gcf,'-dbitmap','test.bmp') % save to bmp
Using print like this saves an image in the desired resolution.

Matlab Imread resizes tif file

so I'm using the imread function in matlab and when I save the TIFF file and open it in photoshop, it has a white border and I can't understand why. I want to maintain its resolution as a 512 by 512 image. Any ideas why? And how I can fix that?
Here's a sample code:
B = imread('W_noise1.tif');
for n = 1:5,
B = medfilt2(B);
end
B = filter2(fspecial('average',3),B)/255;
imshow(B)
Are you sure it's an issue with imread? I'd be surprised if it is.
See this link about medfilt2 where it explains that "medfilt2 pads the image with 0s on the edges, so the median values for the points within [m n]/2 of the edges might appear distorted."
EDIT: I tried to replicate your problem. This is an issue with print where it puts a white frame around the image after you save it. This functionality, print is made for printing plots. If you want to save the image, you should use imwrite.

how to make an image large enough to avoid tick label overlapping?

Assume that the data X has size 1000 *1000. X is displayed using the command:
imagesc(X);
and all the rows are labeld using:
set(gca, 'YTickLabel', somelabels);
Although the data X are properly polotted and the Ytick labels are also shown, the labels are highly overlapped because of the large number of rows. Is there any way to solve the problem? Any help will be highly appreciated.
Edit 1
I realize my question was not stated well to represent my problem. I am going to wrap up my understanding based on the answers and re-ask a question:
To show as many rows/labels in a Figure Window, the following helps:
set(gca,'FontSize',6),
or, alternate the distance (suggested by yuk),
or, set(gca,'YTick',1:10:1000,'YTickLabel',somelabels(1:10:1000));
The code
set(gca,'Units','pixels','Position',[20 20 10000 10000]);
will display a zoomed-in image by default. But if the zoomed-in image is too large to fit in the Figure Window, only part of the image will be displayed. However, neither zoom out nor the pan tool can reach to the rest part of that image.
The default behavior of the code
imagesc(X);
set(gca, 'ytick', 1:1000, 'yticklabe', ylabel);
displays the whole image fitting to the Figure Window with overlapping labels. Nevertheless, it does allow one to zoom into part of the image and to see the un-overlapped labels.
If I save the image into a pdf file:
imagesc(X);
set(gca, 'ytick', 1:1000, 'yticklabe', ylabel);
saveas(gcf, 'fig.pdf');
Then the saved pdf is only the image fit to the Figure Window with overlapping labels. However, unlike zoom in within Matlab figure window, zoom in within a pdf reader won't change the relative position/distance of labels. As a result, the zoomed-in image in pdf is still label-overlaped.
So my question is:
How to save the image into a pdf file or png such that it has a similar behavior as of point 3 above when opened in Adobe reader, rather than that of point 4?
You can also play with axes label font to make it smaller.
set(gca,'FontSize',6)
See also other axes properties to change font - FontName, FontWidth, FontUnits, etc.
Another solution: If your labels are short, you can alternate there distance from the axes, so the labels will not overlap. Check this example:
lbl = cellstr(reshape(sprintf('%3d',1:100),3,100)');
lbl(1:2:100) = strcat(lbl(1:2:100),{' '});
imagesc(rand(100))
set(gca,'ytick',1:100)
set(gca,'yticklabel',lbl)
Part of the resulted image:
UPDATE
To answer your updated question.
PDF document can contain only static images. Once you saved the figure to PDF (or any other graphic file), you cannot zoom in/out as with MATLAB figure tools.
You can zoom first on the MATLAB figure, then save PDF file. In this case the figure will be saved as is. But this way assumes user interactivity with the figure.
If you know your region of interest in advance, you can set axes limits with XLim/YLim properties, then save the figure.
Example:
imagesc(X);
set(gca, 'ytick', 1:1000, 'yticklabe', ylabel);
set(gca, 'XLim',[1 20], 'YLim', [20 40])
saveas(gcf, 'fig.pdf');
By the way, you can also save figure to file with PRINT function. More flexible. SAVEAS is just wrapper around it.
print('-dpdf','fig.pdf')
Another option is to rotate the tick labels which is discussed in this technical solution. You can find a number of easy-to-use implementations on the MATLAB File Exchange.