Save figure with plots as a matrix for further processing in MATLAB - matlab

I have displayed an image and plotted a rectangle over all the useless areas. Now i need to save this image in the form of a matrix, so that i can use it further.
figure,imshow(colz);
hold on;
for i=1:num
if(i~=n)
img=rectangle('Position',box(i,:),'FaceColor','k');
end
end
This is a part of my whole code. I'm covering all the undesired parts with zeros. so now I'm left with my desired area and a background. How can i save the pixel values in another matrix so as to create a new image that contains this enhanced data?
Thanks

here try this
F = getframe(gcf);
% gcf is your figure currently displaying your image with the rectangle
%
y = F.cdata;
hold off
figure(2),imshow(y);

Related

Multiple Plot Matlab including image

I use the tiledlayout(2,2) command to create a plot in Matlab. The first three title fields filled with normal plots. The fourth and last field is a field with an image. I used the commands IMG = 'mypic.tif'and imshow(IMG).I wonder why I can not change the size of my image. Is this not possible with the tiledlayoutcommand? I have looked up the documentary for tiledlayout and imshow(), but found nothing which helps me.
It indeed seems as if this is not possible using the tiledlayout functionality. However, it is possible using the subplot functionality. Below, I will give an example how this works.
Consider the following script:
% Generate some dummy data for the four plots
x = linspace(0, 2*pi, 25);
y = sin(x);
% Load sample image
image = imread('ngc6543a.jpg');
% Generate the figure
fig = figure(1);
% The three subplots
for i = 1:3
subplot(2,2,i);
plot(x, y);
end
% The image
subplot(2,2,4);
imshow(image);
% Increase size of the image
size_factor = 1.4; % 1.0 is original size
im_ax = fig.Children(1); % axes belonging to image
dims = im_ax.Position(3:4); % current dimensions
dims_new = size_factor * dims; % scale old dimensions
dxdy = (dims_new - dims) / 2; % offset for left bottom corner of image
im_ax.Position = [im_ax.Position(1:2) - dxdy, dims_new]; % update position
In this script, we start by generating some dummy data for the three 'normal' plots and loading a sample image (this image came with my MATLAB installation). Subsequently, we create a figure. After the figure has been created, I add the three dummy plots to the figure using a for loop and the subplot functionality. Then, we plot the image using imshow in the fourth subplot.
Now, the interesting part begins. First of all, I define a scale factor for the image (size_factor). Then, I retrieve the axes in which the image is plotted and store it in im_ax. From this axes, I retrieve the last two elements of the Position field and store them in dims. These two elements define the size of the axes. Based on the value of size_factor, I calculate the new size of the axes and store this in dims_new. To ensure that the axes (and thus the image) remains centered, we need to calculate by how much we need to shift the left bottom corner of the axes (whose coordinates are stored in the first two elements of the Position field). This result is stored in dxdy. The last thing we do is simply updating the Position field of the axes in which the image is plotted.
Now, to show you some results:
size_factor equals 1.0:
size_factor equals 1.4:
size_factor equals 0.55:

How to merge results of multiple viscircles in MATLAB

I'm trying to plot a circle in a function using viscircles, and then come back to that function later on to plot another circle like the figure shown below:
At the moment, I can only plot single circles using these lines of code:
figure
center = [numberX numberY];
xlim([-0.1 10.1])
ylim([-0.1 10.1])
axis square
artwork = viscircles(center,size,'Color',colorControl)
After plotting the first viscircles, control rolls back over to a prompts function to get data for the next viscircles, but when it comes back around to plotting, the original viscircles is overwritten, even when I tried using hold on. Any advice would be much appreciated.
viscircles by default will flush the figure and draw only the circles specified by the inputs you provide it so hold on will not work.
What you can do instead is keep appending to your data so that the original data is displayed followed by a new circle each time you prompt for new data.
As such, do something like this. Assuming that you have a function called getNewCenter that returns a new center, the size of the circle and the colour, and matrices that contain the centers to display as well as their sizes:
centers = [];
sizes = []; % Matrices that contain the centers and sizes
while true % Keep iterating...
[numberX, numberY, size, colorControl] = getNewCenter; % Get new center, size and colour
% Add to the data
centers = [centers; numberX numberY];
sizes = [sizes; size];
% Plot the circles
xlim([-0.1 10.1]);
ylim([-0.1 10.1]);
axis square;
artwork = viscircles(centers, sizes, 'Color', colorControl);
end

Colorbar is empty when saving figure as a tiff or jpeg

I'm trying to plot some temperature data over a grayscale image, with the temperature data shown using a colorscale. I've been able to do so by overlaying a partially-transparent array with the temperature data over the image data. The problem comes when I try to save it as a tiff (or jpeg). While the colorbar (for the temperature data) shows up exactly as intended in the Matlab figure, when I save it as a tiff, the colorbar comes up empty (solid white). Any ideas?
figure
imagesc(xlims, ylims, image_data)
set(gca,'YDir','normal');
colormap(gray)
title(title)
xlabel('xlabel')
ylabel('ylabel')
hold on
axis equal
axis tight
%Skip lines of code where I build my temperature array (T) here
%Force a single pixel to 2200
T(1,1)=2200;
%Remove any data below 1000
T(T<1000)=0;
% Establish Transparency Mask for Temperature Data
transp = T~=0; % Binary matrix highlighting where temp data exists
% Overlay Temp Data on Background Image
imagesc(xlims, ylims, T,'AlphaData',transp)
% Create Colormaps and Combine Them
% Note: Assumes no overlap between background image values and temp data
% (highest value in background image is 73)
cmap1 = colormap(gray(73));
cmap2 = colormap(gray(999-73));
cmap3 = colormap(jet(2200-999));
cmap = [cmap1; cmap2; cmap3];
% Apply Combined Colormap to Figure
colormap(cmap)
% Add and Modify colorbar
h = colorbar;
set(h,'YLim',[1000 2200]) % Reduces Range of Colorbar to show only Temp Data
ylabel(h,'Temperature, Kelvin')
print(gcf, '-dtiff', 'filename');
When saved the colorbar looks like this:
In the Matlab figure it looks fine:
UPDATE: I had a bit of old code that I had done something kind of similar on and went line by line looking at differences. For some reason, having the figure visible matters? If I change
figure
to
figure ('visible','off');
the whole thing works. Still curious as to why????

Displaying whole image by clicking on a subplot

I croped some parts of images and displayed them in one figure with subplots. Number of subplots are not certain. I read images from a file then crop them. My aim is that when I click or double click on an subplot, I want to see whole image in new figure.
I want to give an example just to make clear my question. if I click on first subplot, I want to see whole cameraman image in new figure.
Is it possible? If it is possible, What is the way?
The example uses the ButtonDownFcn that can be added to most matlab plot commands.
Just copy both functions into one file and run the "interactivePlot" function.
The list_of_images contains all matrices that shall be plotted.
The number of matrices is flexible. However, you have to adjust the subplot command...
function interactivePlot
list_of_images = {rand(5), rand(10), rand(50), rand(100)}
for ii = 1:length(list_of_images)
subplot(2,2,ii)
imagesc(list_of_images{ii}, 'ButtonDownFcn', #newFigure1)
end
end
function newFigure1(h1, h2)
figure()
data = get(h1, 'CData');
imagesc(data)
end
I had same problem, change your function like below then it will be solved:
function newFigure1(h1, h2)
figure()
data = get(h1, 'CData');
colormap(gray);
imagesc(data)
end

Overlaying data on an image in matlab

I have two plots I want to overlay on top of each other as shown in the link below:
The inputs are the two images on the left and the output is the image on the right. Here's the code I used:
reference = imread('ref_foam.png');
figure, imshow(reference);
hold on;
h = imshow(data,[]);
hold off
colormap jet;
alphamap = zeros(size(reference,1),size(reference,2));
for i = 0:size(data,1)-1
for j = 0:size(data,2)-1
if(~(data(i+1,j+1) == 0))
alphamap(i+1,j+1) = 0.75;
end
end
end
set(h, 'AlphaData', alphamap);
Anytime there's a zero in the data array, it sets that transparency to zero or else it will set the transparency to 0.75.
Now, my questions are: How can I get the colormap to apply to only the data array? In this example it works but if I convert "reference" to a grayscale, the colormap applies to that as well. The input for the colormap is an axes handle, is there anyway to input the image's handle (h) so that it only applies to the top (data) array? Also, I'd like to implement a colorbar as well. Is there anyway to apply the colorbar only to the data array? Thanks.
You probably want to use the subimage command - it lets you create images on the same figure with different colormaps.
Once create and modified as in your script, overlay the images by setting their axes positions on top of each other.