Matlab Extract images from a subplot in .fig format - matlab

How can I extract images from a subplot figure. fig with images plotted in it? See the subplot of the figure with images formated to png https://ibb.co/60jx8kX
I tried with this code but it didn't give me the output I needed.
fig = openfig( 'IC_01.fig' , 'new' , 'invisible' );
imgs = findobj(fig, 'type' , 'image' );
thiscmap = get(fig, 'colormap' );
for K = 1 : length(imgs)
thisimg = get(imgs(K), 'CData' );
% now do something with it for illustration purposes
thisfilename = sprintf( 'extracted_image_%03d.jpg' , K);
imwrite(thisimg, thiscmap, thisfilename);
end
Thank You.

here's a way to take the data from the first image to the image you want, the first lines are similar to what you did :
f=openfig('IC_02.fig')
imgs = findobj(f, 'type' , 'image' );
for n=1:numel(imgs)
C{n}=imgs(n).CData;
X{n}=imgs(n).XData;
Y{n}=imgs(n).YData;
cmap{n}=imgs(n).Parent.Colormap; % not assuming it the same for all axes...
end
Now some of the images will be the colorbar of the image you want (usually one after the other). We then take the Ydata of the colorbar to set the caxis limits of the image you want... for your case the data was in the 4th "image" object, and the limits are taken from the 3rd "image" (colorbar)...
imagesc(X{4},Y{4},C{4})
colormap(cmap{4})
set(gca,'Ydir','normal')
caxis([Y{3}(1) Y{3}(2)])

Related

Accumulating plot of data and fit in Matlab

I have a Matlab script that imports data from a file and creates an exponential fit. I want the script to plot the data points and the fit using the same colour. The legend should be the name of the data file. When I run this same script again for another input file I want the new data and fit to be displayed in the same plot window name of the new data file added to the legend.
What I have so far is this;
expfit = fit(x,y,'exp1')
figure(1)
hold all
plot(x,y,'*','DisplayName','fileName)
legend('Interpreter','none')
legend show
using
plot(expfit,x,y,'DisplayName','fileName')
does not work
How can I add the fitted line to each data using the same colour as the data and
adding the filenames to the legend ?
You're close...
An easy way is to get the colours up front
c = parula(7); % default colour map with 7 colours
figure(1); clf;
hold on
% filename is a variable e.g. filename = 'blah.csv'; from where the data was loaded
plot( x, y, '*', 'DisplayName', filename, 'color', c(1,:) );
plot( expfit, x, y, '-', 'HandleVisibility', 'off', 'color', c(1,:) );
legend('show');
Note by setting HandleVisibility off the fit will not show up in the legend. This is personal preference, I only like one entry for the data and the fit, you could instead use the DisplayName on the 2nd plot too.
Both plots use the same colour using the color input. I've used the first row of the colour map for both, if you plotted some other data you could use the 2nd row etc.
The alternative is to let MATLAB determine the colour automatically and just copy the colour over for the 2nd plot, you need to create a variable (p) of the first plot to get the colour
p = plot( x, y, '*', 'DisplayName', filename );
plot( expfit, x, y, '-', 'HandleVisibility', 'off', 'color', p.Color );
The other code would be the same.

Save axes in GUI as image MATLAB

I know there are a lot of answers regarding this issue but I didn’t found any one that help me..
I have a GUI in MATLAB with 2 axes and I want to save separately each axes as .jpeg or any other format.
Any way I have tried – I got either image that including all the GUI or cut figure.
Any idea how can I get 2 good images?
You could loop through all of the axes and call getframe to get just that axes. You can then save the cdata using imwrite.
% Get a list of all axes in the figure
allax = findall(gcf, 'type', 'axes');
for k = 1:numel(allax)
% Get the axes as an image
fr = getframe(allax(k));
% Save the image
imwrite(fr.cdata, sprintf('%d.png'));
end
If you already have axes handles you can just use those directly
fr = getframe(axes2);
imwrite(fr.cdata, 'axes2.png')
fr = getframe(axes1);
imwrite(fr.cdata, 'axes1.png')
If you want to include the X and Y axes labels, you could do something like
function axes2image(ax, filename)
hfig = ancestor(ax, 'figure');
rect = hgconvertunits(hfig, get(ax, 'OuterPosition'), ...
get(ax, 'Units'), 'pixels', get(ax, 'Parent'));
fr = getframe(hfig, rect);
imwrite(fr.cdata, filename);
end
axes2image(axes2, 'axes2.png')
axes2image(axes1, 'axes1.png')

Save montage as image matlab

I have 225 image with put together with the montage function in matlab. And I can show them with montage. But i cannot save the montage as a complete image, please help me.
path = uigetdir;
D=dir(fullfile(path,'*.tif'));
imcell = cell(1,numel(D));
imcropped = cell(1,numel(D));
figure(1);
title('Drag square to crop picture, end with a double click',...
'FontSize', 15 , 'HandleVisibility' , 'off' ) ;
axis equal
set( gca , 'NextPlot' , 'replacechildren') ;
imcell1 = imread(D(50).name);
[~, rect] = imcrop(imcell1);
close(figure(1));
%
for i = 1:numel(D)
imcell{i} = imread(D(i).name);
imcropped{i} = imcrop(imcell{i}, rect);
end
h=montage(cat(4,imcropped{:}),'Size', [15 15] );
The output on montage "h" is just a number.
I would like to point out a better way to do it. While Benoit_11's way is technically correct, it limits the resolution of the image to the size of your screen. When you use getframe(gca), Matlab is effectively taking a screenshot of the current axes contents, at whatever size your figure window is currently in.
A better way to do this is to use the handle, as it references the actual graphical output of montage() instead of what it displays as. To save an image from the handle, you need to get the cdata from the object it references with get:
h=montage(cat(4,imcropped{:}),'Size', [15 15] );
MyMontage = get(h, 'CData');
imwrite(MyMontage, 'FancyName.tif', 'tif');
This way you get the full resolution of the montage, not just the resolution from displaying it.
For more information on image handles: http://www.mathworks.com/help/matlab/creating_plots/the-image-object-and-its-properties.html
You're almost there! The value 'h' is actually the handles to the image object created by the montage you made in the figure. What you can do is use getframe to capture the content of the figure (graphics object) and save it as an image. Here is a very simple example, with the code going directly after yours
h=montage(cat(4,imcropped{:}),'Size', [15 15] );
MyMontage = getframe(gca) %// Get content of current axes. I did it with sample images.
The output is the following:
MyMontage =
cdata: [384x1024x3 uint8] % Yours will be different
colormap: []
Hence you can save the actual data, stored in cdata, in a new file and you're good to go!
imwrite(MyMontage.cdata,'FancyName.tif','tif');

How to save MATLAB figure as JPEG using saveas() without the image coming off badly?

In a MATLAB function I am writing, I am generating a figure. The figure is displayed when the function is executed. I need to save the figure as a JPEG image. To do that, I could do File->Save As in the figure window that displays the figure. But I'd like to automate this. I've tried to do that using the saveas() function. The problem is that the resulting image is undesirable. Here are the images for a demo problem to show you what I mean:
JPEG image saved manually using File->Save As in the MATLAB figure window:
JPEG Image saved using saveas() function (notice that the plots aren't as nice and the titles overlap):
Here is the MATLAB function in which I generate the figure and save the figure as a JPEG using saveas():
function JpgSaveIssueDemo( )
figure( 1 );
t = 0:0.1:8;
subplot( 2, 2, 1 );
plot( t, sin(t) );
title( 'Plot 1 of Example to Demonstrate JPG Save Issue', 'FontSize', 18 );
subplot( 2, 2, 2 );
plot( t, sin(t) );
title( 'Plot 2 of Example to Demonstrate JPG Save Issue', 'FontSize', 18 );
subplot( 2, 2, 3 );
plot( t, sin(t) );
title( 'Plot 3 of Example to Demonstrate JPG Save Issue', 'FontSize', 18 );
subplot( 2, 2, 4 );
plot( t, sin(t) );
title( 'Plot 4 of Example to Demonstrate JPG Save Issue', 'FontSize', 18 );
saveas( gcf, 'DemoPlot', 'jpg' );
end
The figure that is displayed when JpgSaveIssueDemo() is executed isn't maximized. So, I thought that if I could maximize it using function call/s in JpgSaveIssueDemo() before saveas() is executed, then the JPEG image saved would come out well.
So, I used this code before the saveas() line in JpgSaveIssueDemo() to maximize the figure:
drawnow;
jFrame = get(handle(gcf),'JavaFrame');
jFrame.setMaximized(true);
Then, the figure that is displayed is maximized. However, the result is the same: the JPEG image still comes out undesirably.
What can be done for this?
The Matlab figure export dialog and the saveas() function lack a lot of desirable functionality. Especially, savas() cannot create a custom resoultion image which is why your results look poor. For creation of bitmap images I highly recommend using the third-party function export_fig. By adding the following code to your function (including the maximizing trick)
set(gcf, 'Color', 'white'); % white bckgr
export_fig( gcf, ... % figure handle
'Export_fig_demo',... % name of output file without extension
'-painters', ... % renderer
'-jpg', ... % file format
'-r72' ); % resolution in dpi
I created this image: (use "show image" or similar in your browser to get the original size)
For higher quality use higher resolutions of 150 or even 300 dpi (for print). Instead of maximizing the figure window, for most applications it's suitable to define the axis size to obtain an image of the desired size:
unitSave = get(figureHandle, 'Unit'); % store original unit
set(figureHandle, 'Unit', 'centimeters'); % set unit to cm
set(figureHandle,'position',[0 0 width height]); % set size
set(figureHandle, 'Unit', unitSave); % restore original unit
Just use a lossless scalable format like EPS, see last line in the snippet below :)
h1=figure % create figure
plot(t,Data,'r');
legend('Myfunction');
% Create title with required font size
title({'Variance vs distance'},'LineWidth',4,'FontSize',18,...
'FontName','Droid Sans');
% Create xlabel with required font size
xlabel({'Distance (cm)'},'FontSize',14,...
'FontName','DejaVu Sans');
% Create ylabel with required font size
ylabel({'Variance of sobel gradients'},'FontSize',14,...
'FontName','DejaVu Sans');
print(h1,'-depsc','autofocus.eps') % print figure to a file
I cannot attach an EPS file here though, not supported, but its scalable and can be put in word processors or Latex without worrying about bad resolution.
I had the same problem, and here is what I used to solve it:
set(gcf,'PaperPositionMode','auto')
saveas(gcf,'file_to_save','png')
where gcf can be replaced by the handle to the desired figure.

to get last 20 columns of an image :Matlab

i have an image IMG ,i want to get its last (20) colums only.
i-e the image is of size 500x500 and i want the colums starting from 480 to 500 ,number of rows remain same.
You can put some basic math and the end keyword in your indexing. So you would have
smallerImage = rawImage(:, (end-20+1):end);
As a colormapped (NxMx1) example
load mandrill; %A colormapped (2d) Matlab demo image in the X variable
figure;
subplot(121)
image(X)
colormap(map)
title('Full picture')
subplot(122)
smallX = X( : , (end-20+1):end ); %This is the subsetting operation for a 2D image
image(smallX)
colormap(map)
title('Rightmost 20 columns')
An RGB example (NxMx3)
imdata = imread('ngc6543a.jpg');
figure;
subplot(121)
image(imdata )
colormap(map)
title('Full picture')
subplot(122)
smallImData = imdata ( : , (end-20+1):end , : ); %This is the subsetting operation for an RGB image, note 3rd dimension colon
image(smallImData )
colormap(map)
title('Rightmost 20 columns')
Try this:
cutImg = img(startrow:endrow,startcol:endcol);
Taken from:
Matlab Central
If you want to take the last n columns, use:
A(:,end-n+1:end)
For the first n columns use:
A(:,1:n)