Import figures to MATLAB GUI using handles? - matlab

How can I literally take these figures and place them in the axes windows of my GUI?
I am not sure where to place handles in my user-defined code in the example below. I have 4 figures in total which look similar to this example. I want the 4 figures to be displayed in my GUI window and not in separate windows, so i've created 4 axes windows in the .fig file.
The code for this particular figure draws a grid of 66 black and white rectangles based on whether or not a value in MyVariable is a 1 or a 0. Black if MyVariable is a 1, White if MyVariable is 0. I have a file for my .fig GUI, one file to control the GUI and one with user-defined code that links to the GUI.
function test = MyScript(handles)
lots of code in between
% Initialize and clear plot window
figure(2); clf;
% Plot the west wall array panels depending on whether or not they are
% shaded or unshaded
for x = 1:11
for y = 1:6
if (MyVariable(x,y) == 1)
rectangle('position', [x-1, y-1, 1, 1] ,'EdgeColor', 'w', 'facecolor', 'k')
else if(MyVariable(x,y) == 0)
rectangle('position', [x-1, y-1, 1, 1], 'facecolor', 'w')
end
end
end
end
title('West Wall Array',...
'FontWeight','bold')
axis off
The figure for the above code looks like this:
The function definition contains all of my script code for all 4 plots because I didn't partition my script into individual functions earlier on.
My GUI script code contains:
MyScript(handles);

As DMR sais, it's necesary to set the 'CurrentAxes'. For example, if you want to plot into the axis with the tag name 'axis1' you should simply add:
axes(handles.axes1);
to your code. Below is a very simple example for a figure containing a 'axis1' and 'axis2' using your code (corrected) code from above. Im not really shure wether you want to plot on an axis on your gui itself or a separate figure. I hope I covered both cases.
function varargout = Test(varargin)
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', #Test_OpeningFcn, ...
'gui_OutputFcn', #Test_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before Test is made visible.
function Test_OpeningFcn(hObject, eventdata, handles, varargin)
% Choose default command line output for Test
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
plot(handles.axes2,-2*pi:0.1:2*pi,sin(-2*pi:0.1:2*pi));
% Initialize and clear plot window
MyVariable = ones(11,6);
MyVariable(1:5,1) = 0;
axes(handles.axes1);
for x = 1:11
for y = 1:6
if (MyVariable(x,y) == 1)
rectangle('position', [x-1, y-1, 1, 1] ,'EdgeColor', 'w', 'facecolor', 'k');
elseif(MyVariable(x,y) == 0)
rectangle('position', [x-1, y-1, 1, 1], 'facecolor', 'w');
end
end
end
title('West Wall Array',...
'FontWeight','bold')
figure(2); clf;
for x = 1:11
for y = 1:6
if (MyVariable(x,y) == 1)
rectangle('position', [x-1, y-1, 1, 1] ,'EdgeColor', 'w', 'facecolor', 'k');
elseif(MyVariable(x,y) == 0)
rectangle('position', [x-1, y-1, 1, 1], 'facecolor', 'w');
end
end
end
title('West Wall Array',...
'FontWeight','bold')
function varargout = Test_OutputFcn(hObject, eventdata, handles)
varargout{1} = handles.output;
Your guide GUI should look like this:
And your result like this:

You can set the axis to plot into prior each plot command by setting the 'CurrentAxes' property of the figure.
Within GUIDE, you can tag a given axis, for example: http://www.mathworks.com/help/matlab/creating_guis/gui-with-multiple-axes-guide.html . Then within your drawing code, indicate which axis should be plotted into via the 'set' function and 'CurrentAxes' property.
A simple example is below, though it doesn't use GUIDE, only basic subplot axis handles:
% plots in most recent axis by default (ax2)
fig = figure;
ax1 = subplot(1,2,1);
ax2 = subplot(1,2,2);
plot(rand(1,10));
% indicate that you want to plot in ax1 instead
fig = figure;
ax1 = subplot(1,2,1);
ax2 = subplot(1,2,2);
set(gcf, 'CurrentAxes', ax1);
plot(rand(1,10));

Related

Matlab GUI: Problems while using imfreehand()

I have applied Canny edge detection on am image and now want to crop a part of it for further procession. I have created 4 axes with the tags axes1, axes2, axes3 and axes4. I want to display the image first in axes1, then the edge detected again in axes1. Finally the cropped image is to be displayed in axes3 and the image after removal of holes in axes4.
I am including a sample code which recreates the problem:
function varargout = samp_GUI(varargin)
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, 'gui_Singleton', gui_Singleton, 'gui_OpeningFcn', #samp_GUI_OpeningFcn, 'gui_OutputFcn', #samp_GUI_OutputFcn, 'gui_LayoutFcn', [] , 'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before samp_GUI is made visible.
function samp_GUI_OpeningFcn(hObject, eventdata, handles, varargin)
handles.output = hObject;
guidata(hObject, handles);
% --- Outputs from this function are returned to the command line.
function varargout = samp_GUI_OutputFcn(hObject, eventdata, handles)
varargout{1} = handles.output;
% --- Executes on button press in browse.
function browse_Callback(hObject, eventdata, handles)
[filename pathname] = uigetfile({'*.jpg';'*.bmp'},'File Selector');
handles.myImage = strcat(pathname, filename);
axes(handles.axes1);
imshow(handles.myImage)
im=imread(handles.myImage);
bw3=im2bw(im,0.3); %threshold value taken as 0.3
BW3=edge(bw3,'canny');
edge_im = BW3;
axes(handles.axes1);
imshow(BW3);
h=imfreehand(handles.axes1);
M=~h.createMask();
I(M) = 0;
axes(handles.axes2);
imshow(I);title('Cropped Image')
I = bwareaopen(I, 50);
axes(handles.axes3);
imshow(I),title('Removed Holes');
% save the updated handles object
guidata(hObject,handles);
When i execute the code in a .m file, it runs perfectly with different images opening in different windows but when the same code is run for the GUI, blank images are problems. I do not seem understand where the problem lies.
I think that you're suffering from some form of copy/paste issue. If you look at the line in your code where I(M) = 0 this doesn't really make sense (given your example) since I is not defined.
MATLAB will not throw any errors at this point though, because it's perfectly valid to create a matrix in this way; however, doing so actually produces a row vector rather than the image you're wanting.
>> M = logical(eye(100));
>> size(M)
ans =
100 100
>> clear I
>> I(M) = 0;
>> size(I)
ans =
1 10000
I imagine what you wanted to do was to apply the mask to your image (im) in which case you should get what you want. I have provided an example below (not sure what you're trying to display in axes1).
load mri
img = double(D(:,:,12));
im = img ./ max(img(:));
figure
handles.axes1 = subplot(2,2,1);
handles.axes2 = subplot(2,2,2);
handles.axes3 = subplot(2,2,3);
handles.axes4 = subplot(2,2,4);
bw3=im2bw(im,0.3); %threshold value taken as 0.3
BW3=edge(bw3,'canny');
edge_im = BW3;
axes(handles.axes1);
imshow(BW3);
h=imfreehand(handles.axes1);
M=~h.createMask();
% Assign im to I to ensure proper cropping.
I = im;
I(M) = 0;
axes(handles.axes3);
imshow(I);title('Cropped Image')
M_noholes = bwareaopen(M, 50);
I(M_noholes) = 0;
axes(handles.axes4);
imshow(I),title('Removed Holes');
If you provide more information it will be easier to help you figure out what you need.

MATLAB newbie - Display Photos above panel in guide

i want to display photo above the panel , i see the documentation here : http://www.mathworks.com/help/matlab/ref/uistack.html
but it only mention how to use this function (uistack) only in figure
my program till now :
my code :
function varargout = panel(varargin)
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', #panel_OpeningFcn, ...
'gui_OutputFcn', #panel_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
handles.output = hObject;
guidata(hObject, handles);
function varargout = panel_OutputFcn(hObject, eventdata, handles)
varargout{1} = handles.output;
function pushbutton1_Callback(hObject, eventdata, handles)
k = 1;
[filename pathname] = uigetfile({'*.*'},'File Selector','MultiSelect', 'on')
iscellstr(filename)
celldata1 = cellstr(pathname)
celldata2 = cellstr(filename)
celldata3 = strcat(celldata1,celldata2)
subplot(3,4,1),imshow(celldata3{1})
subplot(3,4,2),imshow(celldata3{2})
subplot(3,4,3),imshow(celldata3{3})
subplot(3,4,4),imshow(celldata3{4})
subplot(3,4,5),imshow(celldata3{5})
subplot(3,4,6),imshow(celldata3{6})
The reason I asked for the version was that if you were using an older version (than R2014b) you could set the BackgroundColor property of the uipanel to be 'none' which would make it transparent. This "feature" doesn't work in R2014b onwards...
%% Only HG1 (pre R2014b)
f = figure;
subplot ( 3, 3, 4 )
uipanel ( 'parent', f, 'Position', [0. 0. 0.6 0.6], 'BackgroundColor', 'none' );
Im afraid other options will require more knowledge of how GUI's work - specifically creating GUI's from the commandline (and not in GUIDE):
% Create a figure
f = figure;
% Create a uicontainer (this is a way of grouping controls together
uic = uicontainer ( 'parent', f, 'position', [0.1 0.1 0.5 0.5] );
% Create an axes -> which is a child of the UICONTAINER
ax = axes ( 'parent', uic, 'position', [0 0 1 1] );
% Create a uipanel -> which is a chilf of the FIGURE
uipanel ( 'parent', f, 'position', [0 0 0.4 0.7] );
% Some data to plot
image(rand(100)*255,'parent',ax)
% Note at this point the axes is underneath the uipanel
%%
% Hey presto we can move the uicontainer to the top and the axes appears! :)
uistack ( uic, 'top' )
Note: If you create the uicontainer after creating the uipanel then you dont need to use uistack - I put it in that order to show that uistack will move the 'axes' in the stack order...
I'm not sure I've correctly undestood what you need, nevertheless ...
you can first create the panel (uipanel) specifying its position (which includes size), then create as many axes as you need (consider the number of imagery you want to add) in order to crate a sort of chessboard (you can do this by properly setting their position and size).
You can now load the images over the axis by specifying the parent property.
In the following example I create a uipanel which contains three images, notice the coupling "axes-handle - parent property" in the calls to imshow.
In the "pushbutton1_Callback" of your code, you can "automate" this procedure.
uipanel ('position', [0 0 0.33 0.95],'title','PLOK');
a1=axes('position',[0 0 .3 .3])
a2=axes('position',[0 0.3 .3 .3])
a3=axes('position',[0 0.6 .3 .3])
imshow('curva_con_linee_verticali.jpg','parent',a1)
imshow('grafico_3d_assi_cartesiani.jpg','parent',a2)
imshow('prod_punt.jpg','parent',a3)
This is how the Figure looks like (the three graphs are actually three jpg images):
Hope this helps.

Print ONLY plot on MATLAB GUI

How can I print ONLY the plot created by my MATLAB GUI into a PDF document?
I know about the function available online called export_fig, but we are not allowed to make use of externally coded tools for this.
I currently have the following
function PrintButton_Callback(hObject, eventdata, handles)
set(gcf,'PaperType','A4','PaperOrientation','landscape','PaperPositionMode','auto');
print(get(handles.Axes,'Parent'), '-dpdf','Results.pdf');
However, this results in my entire GUI figure being saved.
How can I select ONLY the plot made by my axes ("Axes")?
The print command only accepts a figure as handle parameter ...
To print specified axis only a trick is to copy this axis to a new temporary figure using copyobj and use print command on the new figure.
Here is some sample code:
%% -- Test code
function [] = TestPrint()
%[
% Create figure with two axes
fig = figure(1); clf;
ax1 = subplot(1,2,1);
plot(rand(1, 12));
ax2 = subplot(1,2,2);
plot(rand(1, 12));
% Print the whole figure
print(fig, '-dpdf', 'figure.pdf');
% Print ONLY second axis
printAxis(ax2, '-dpdf', 'axis.pdf');
%]
end
%% --- Print specified axis only
% NB: Accept same arguments as 'print' except for first one which now is an axis.
function [] = printAxis(ax, varargin)
%[
% Create a temporary figure
visibility = 'on'; % You can set it to off if you want
tempFigure = figure('Visible', visibility);
cuo = onCleanup(#()clearTempFigure(tempFigure)); % Just to be sure to destroy the figure
% Copy selected axis to the temporary figure
newAx = copyobj(ax, tempFigure);
% Make it fill whole figure space
set(newAx, 'OuterPosition', [0 0 1 1]);
% Print temporary figure
print(tempFigure, varargin{1:end});
%]
end
function [] = clearTempFigure(h)
%[
if (ishandle(h)), delete(h); end
%]
end
Disable axes visibility: set(gca,'Visible','off') before printing.

How to remove axis in MATLAB

axis off Not working.
function displayResults(filename,hObject, eventdata, handles)
% Open 'filename' file... for reading...
fid = fopen(filename);
for N=6:1:10
imagename = fgetl(fid);
if ~ischar(imagename), break, end % Meaning: End of File...
[x,map]=imread(imagename);
rgb=ind2rgb(x,map);
ax = handles.(sprintf('axes%d', N));
axis off;
image(rgb, 'Parent', ax);
end
guidata(hObject,handles)
Above code results in following output:
I've highlighted axis in above figure.
All images I've used is bitmap with bit depth of 8. I don't want those axis, how can I remove that?
insert the following at the end of each loop:
set(ax, 'Visible','off')
or you can do this once for all axes in the figure:
set(findobj(gcf, 'type','axes'), 'Visible','off')

Handling multiple plots in MATLAB

I am using plot(X) whereX is an n-by-k matrix, which produces k plots with n points.
How do I show the legend for this plot? More importantly, is there an easy way to show checkboxes to show or not show certain plots?
I think you can find this section of Documentation useful.
GUI that Displays and Graphs Tabular Data
http://www.mathworks.com/help/techdoc/creating_guis/bropmbk-1.html
Please use this body for plot_callback function in tableplot.m file to get a dirty implementation of the flexible legend.
function plot_callback(hObject, eventdata, column)
% hObject Handle to Plot menu
% eventdata Not used
% column Number of column to plot or clear
colors = {'b','m','r'}; % Use consistent color for lines
colnames = get(htable, 'ColumnName');
colname = colnames{column};
lgidx = get(haxes, 'UserData');
if isempty(lgidx)
lgidx = false(size(colnames));
end
if get(hObject, 'Value')
% Turn off the advisory text; it never comes back
set(hprompt, 'Visible', 'off')
% Obtain the data for that column
ydata = get(htable, 'Data');
set(haxes, 'NextPlot', 'Add')
% Draw the line plot for column
hplot = plot(haxes, ydata(:,column),...
'DisplayName', colname,...
'Color', colors{column});
lgidx(column) = true;
else % Adding a line to the plot
% Find the lineseries object and delete it
hplot = findobj(haxes, 'DisplayName', colname);
lgidx(column) = false;
delete(hplot);
end
if any(lgidx)
legend(haxes, colnames{lgidx} );
else
legend(haxes, 'off')
end
set(haxes, 'UserData', lgidx);
end
An example:
x = cumsum(rand(100,3)-0.5); %# three series with 100 points each
h = plot(x);
legend(h, {'first' 'second' 'third'})