Yair Moshe Andrew and Erna Viterbi Faculty of Electrical Engineering Signal and Image Processing Laboratory November 2020 Graphics and GUI Using MATLAB ®
Yair Moshe
Andrew and Erna Viterbi Faculty of Electrical Engineering
Signal and Image Processing Laboratory
November 2020
Graphics and GUI
Using MATLAB®
2
Outline
• Graphics
• Animation
• Image and Video
• Graphics Objects
• Creating GUI
3
2D Plotting
x=0:.1:2*pi;
y=sin(x);
plot(x,y)
grid on
hold on
plot(x, exp(-x), 'r:*')hold off
axis([0 2*pi 0 1])
title('2-D Plot')
xlabel('Time')
ylabel('F(t)')
text(pi/3, sin(pi/3), '<--sin(\pi/3) ')
legend('Sine Wave','Decaying Exponential')
Line Specification
Specifier Line Color Specifier Marker
r red . point
g green o circle
b blue x cross
c cyan + plus
m magenta * asterix
y yellow s square
k black d diamond
w white v triangle down
Specifier Line Style ^ triangle up
- solid < triangle left
-- dashed > triangle right
: dotted p pentagram
-. dash-dot h hexagram4
5
The Figure Window
The figure window contains useful actions in its menu and toolbars:• Zooming in and out • Panning• Rotating 3-D axes (and other camera actions)• Copying & pasting• Interactive plotting
– Plot Edit Mode– Insert menu– Plot Bowser, Figure Palette, Property Editor/Inspector,
• Data Cursor Mode• Data brushing and linking
6
The Figure Window
• Generate M-Code to reproduce the figure
• Saving & exporting
– Figures can be saved in a binary .fig file format
– Figures can be exported to many standard graphics file formats such as EPS, EMF (both recommended), TIFF, JPEG, GIF, PNG, BMP
• Printing
7
Subplots & Scales for Axes
h = tiledlayout(2,2);
h.TileSpacing = 'compact';
h.Padding = 'compact';
title(h,'My Subplots’);
nexttile
x=0:.1:2*pi;
plot(x, exp(-x))
nexttile
semilogy(x, exp(-x))
nexttile
t = 0:900;
z = 1000*exp(-0.005*t);
yyaxis left
semilogy(t,z);
z = sin(0.005*t);
yyaxis right
plot(t,z);
nexttile
plot(peaks)
xlim([0 50])
8
Data Brushing and Linking
• Data Brushing
– Manually select observations on an interactive data display
– Can select, remove, and replace individual data values
• Data Linking
– Linked plots visibly respond to changes in the current workspace variables they display and vice versa
• Each one of these tools is useful by itself but when used together they are very powerful
9
Data Statistics & Curve Fitting
• Data Statistics Tool
– Calculates basic statistics about the central tendency and variability of data plotted in a graph
– Plots any of the statistics on the graph
• Basic Fitting Interface
– Fits data using a spline interpolant, a shape-preserving interpolant, or a polynomial up to degree 10
– Plots multiple fits simultaneously for a given data set
– Annotates the plot with the numerical fit results and the norm of residuals
10
3-D Plotting
z = 0:0.1:10*pi;
x = exp(-z/20).*cos(z);
y = exp(-z/20).*sin(z);
plot3(x,y,z,'LineWidth',2)
grid on
xlabel('x')
ylabel('y')
zlabel('z')
11
Plot Gallery – Standard Plots
12
Plot Gallery – Standard Plots
13
Plot Gallery – Standard Plots
14
Plot Gallery – Standard Plots
15
Plot Gallery – Customizing Plots
16
Plot Gallery – Advanced Plots
17
Outline
• Graphics
• Animation
• Image and Video
• Graphics Objects
• Creating GUI
18
Animation
MATLAB provides two techniques for creating animations:
1. Update properties of objects
• When most of the graph remains the same
• Update the properties of graphics objects and display the updates on the screen
• Can also update the position and orientation of a group of objects together using an hgtransform object
2. Create a movie
• When the animation is complex, or you want to store the animation to replay it
19
Update Properties Animation Example
t = 0:pi/20:2*pi;
y = exp(sin(t));
h = plot(t,y);
for k = 1:.1:10
y = exp(sin(t.*k));
h.XData = t;
h.YData = y;
drawnow;
pause(.1)
end
20
Create a Movie Animation Example
[x,y] = meshgrid(-10:0.5:10);
for j = 1:15
z = besselj(0, (j-1)*0.2 + sqrt(x.^2 +y.^2));
surf(x,y,z)
axis([-10 10 -10 10 -.5 1])
M(j) = getframe;
end
frame_order = [1:15 14:-1:1];
number_repeats = 5;
movie(M, [number_repeats frame_order]);
21
Animation
There is also an animatedline function for creating animated lines
h = animatedline;
h.LineWidth = 3;
axis([0,4*pi,-1,1])
x = linspace(0,4*pi,1000);
y = sin(x);
for k = 1:length(x)
addpoints(h,x(k),y(k));
drawnow
end
22
Outline
• Graphics
• Animation
• Image and Video
• Graphics Objects
• Creating GUI
23
Images
[x,map] = imread('peppers.png');
image(x)
colormap(map)
• Image I/O
– imread, imwrite, iminfo
• Image display
– imshow – Display
– image – Display from array
– imagesc – Display from array with scaled colors
24
Images
• Image viewer app
– imtool – Provides tools for pixel information, pixel region, distance, image information, adjust contrast, crop image, and display range
25
Video
• Video information
– mmfileinfo - Information about multimedia file
• Video viewer
– implay - View video from MATLAB workspace or video file
• Video reader & writer
– VideoReader, VideoWriter - Read and write video files
– Replace deprecated AVI functions
26
VideoReader & VideoWriter Example
% Open input and output files
inFile = VideoReader('xylophone.mp4');
outFile = VideoWriter('out.avi');
open(outFile);
% Read one frame at a time
while hasFrame(inFile)
curFrame = readFrame(inFile);
outFrame = imrotate(curFrame, 180);
writeVideo(outFile, outFrame); % Write to output file
% Show input and output
…
end
close(outFile);
27
Computer Vision System Toolbox
• VideoFileReader - Read video files
• VideoFileWriter - Write video files
• VideoPlayer- Play video
28
Computer Vision System Toolbox Example
videoFReader = vision.VideoFileReader('xylophone.mp4');
videoPlayer = vision.VideoPlayer;
while ~isDone(videoFReader)
videoFrame = videoFReader();
videoPlayer(videoFrame);
pause(0.05)
end
release(videoPlayer);
release(videoFReader);
29
Outline
• Graphics
• Animation
• Image and Video
• Graphics Objects
• Creating GUI
Graphics Objects
• Graphics objects are the visual components used to display data
• Can represent data or contain other objects
• Every graphics object has:
– A unique identifier, called a handle
– A set of characteristics, called properties
30
Graphics Object Hierarchy
31
Graphics Objects
• Root
– Graphics environment and state information
• Figures
– The windows in which graphics is displayed
– Contain graphics or user interface components
• Axes
– Define the coordinate system of each graph
– Contain the graphics objects that represent data
• Primitive objects
– Line, image, text, polygon, …32
Graphics Objects
• Chart objects
– Bar, stair, stem, scatter, contour, quiver, …
• Group objects
– Allow to treat a set of objects as a single entity
• Annotation objects
– Arrow, text box, …
• Illustration objects
– Legend, colorbar
• UI objects
– We’ll talk about them later33
Obtaining an Object’s Handle
• Upon creation, for example:
– h = plot(x_data, y_data, …)
• Using utility functions:
– groot - root object handle (graphics environment info)
– gcf – return the handle of the current figure
– gca - return the handle of the current axes
– gco - return the handle of the current object
– allchild(handles) – return all children of specified objects
– ancestor(handle,type) – return closest ancestor of specified object of one of the specified graphics objects types
– findobj(handles,’PropertyName’,PropertyValue) – return the handles of objects with specific property values
34
Getting Properties
• Return a list of all object properties and their current values:– get(handle)
• Return the current value of an object property:1. Use dot notation
2. Use get(handle, ‘PropertyName’)
35
h = gcf;
h.Color
get(gcf, ‘Color’)
Setting Properties
• Return a list of all user-settable object properties and their values:– set(handle)
• Return a list of all possible values for an object property:– set(handle,’PropertyName’)
• Set an object property to a new value:1. Use dot notation
2. Use set(handle, ‘PropertyName’, ‘NewPropertyValue’)
36
set(gca, 'XDir')
h = gca;
h.XDir = 'reverse';
set(gca, 'XDir', 'reverse')
37
Example – Specifying Figure Position
space = 5;
top_space = 80;
hgroot = groot;
scn_size = hgroot.ScreenSize;
pos1 = [space, 2/3*scn_size(4) + space,...
scn_size(3)/2 - 2*space, scn_size(4)/3 - (top_space + space)];
pos2 = [pos1(1) + scn_size(3)/2, pos1(2), pos1(3), pos1(4)];
h1 = figure(1);
peaks;
h2 = figure(2);
membrane;
h1.Position = pos1;
h2.Position = pos2;
38
Outline
• Graphics
• Animation
• Image and Video
• Graphics Objects
• Creating GUI
Creating GUI
• Three options:
39
1. GUIDE 2. App Designer
• Had been widely used
• Has many drawbacks
• Modern controls
• Better software design
Creating GUI
3. Create a GUI programmatically
– More control over design and development
– More difficult
– Usually not necessary
• GUIDE to App Designer Migration Tool
40
What is GUIDE?
• GUIDE is MATLAB’s Graphical User Interface (GUI) Development Environment
• Stores GUIs in two files:
– .fig file - Contains a complete description of the GUI layout and the GUI components
• Changes to this file are made in the Layout Editor
– .m file - Contains the code that controls the GUI
• Initialization code and callbacks
• You can program the behavior of the GUI in this file using theM-file Editor 41
Creating a GUI
Typical phases of creating a GUI are:
1. Designing the GUI
2. Laying out the GUI
– Using the Layout Editor
3. Programming the GUI
– Writing callbacks in the M-file Editor
4. Saving and Running the GUI
42
The Layout Editor
43
Component Palette
Align Objects
M-file Editor
Run GUI
Object Browser
Property Inspector
Layout Area
Resize Box
Menu Editor
Tab Order Editor
Toolbar Editor
GUIDE Example
44
Callbacks
• A callback is a function that executes in response to some predefined user action on a graphics object
– Called an event handler in some programming languages
• A property of a graphics object
– All graphics objects: ButtonDownFnc, CreateFnc, DeleteFnc
– Figure and user interface controls: Callback, KeyPressFcn, KeyReleaseFcn
– Figure: CloseRequestFcn, ResizeFcn, WindowButtonDownFcn, WindowButtonUpFcn, WindowButtonMotionFcn,
– …
• Stored in the GUI’s M-file45
Writing Callbacks
A callback is usually made of the following stages:
1. Getting the handle of the object initiating the action
2. Getting the handles of the objects being affected
3. Getting necessary information / values
4. Doing some calculations and processing
5. Setting relevant object properties to effect action
6. Save any changes that have been made to the handles structure by using
guidata(hObject, handles)
– hObject is the handle to the component object that triggered the callback 46
47
Writing Callbacks Example% --- Executes on button press in plot_button.
function plot_button_Callback(hObject, eventdata, handles)
% hObject handle to plot_button (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get user input from GUI
f1 = str2double(get(handles.f1_input,'String'));
f2 = str2double(get(handles.f2_input,'String'));
t = eval(get(handles.t_input,'String'));
% Calculate data
…
% Create frequency plot
axes(handles.frequency_axes) % Select the proper axes
plot(f,m(1:257))
xlabel('Frequency');
set(handles.frequency_axes,'XMinorTick','on')
grid on
…
Managing Data
• Most GUIs generate or use data specific to the application
• GUI components often need to communicate data to one another
• Several mechanisms serve this need:
– UserData property
– Application data (getappdata, setappdata)
– Using the handles structure (guidata)
– Nested callback functions
• It is also possible to make several different GUIs work together
– Communicate by setting each other’s properties or by returning outputs
48
App Designer
• Provides modern UI controls
– Gauges, lamps, knobs, switches, tree, date picker, enhanced table
• Better software design
– Object oriented code
• Allows to deploy web apps
49
App Designer vs. GUIDE
• Single MLAPP file
• uifigure and uiaxes instead of figure and axes
• MATLAB class instead of a set of functions
• Only callback code, utility functions, and user-defined properties are editable
• Dot notation instead of get and set
• Action-specific callbacks
• Improved callback arguments and data sharing mechanism
50
App Designer Examples
51
Creating a GUI Programmatically
• UI controls
– uicontrol, uipanel, uibuttongroup
• Predefined dialog boxes
– errordlg, warndlg, msgbox, helpdlg, waitbar
– questdlg, inputdlg, listdlg, uisetcolor, uisetfont, …
– uigetfile, uiputfile, uigetdir, uiopen, uisave
– …
52
Image Processing Toolbox
• Interactive tools
– imageinfo, imcolormaptool, imcontrast, imcrop, imdisplayrange, imdistline, impixelinfo, impixelinfoval, impixelregion, impixelregionpanel, immagbox, imoverview, imoverviewpanel, imsave, imscrollpane
• Region-of-Interest
– Point, crosshair, line, rectangle, polyline, polygon, circle, ellipse cuboid, freehand
53
More Information
• Mathworks documentation
– http://www.mathworks.com/help/
54
55