Top Banner
Yair Moshe Andrew and Erna Viterbi Faculty of Electrical Engineering Signal and Image Processing Laboratory November 2020 Graphics and GUI Using MATLAB ®
55

GUI with Matlab - moodle.technion.ac.il

Oct 16, 2021

Download

Documents

dariahiddleston
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: GUI with Matlab - moodle.technion.ac.il

Yair Moshe

Andrew and Erna Viterbi Faculty of Electrical Engineering

Signal and Image Processing Laboratory

November 2020

Graphics and GUI

Using MATLAB®

Page 2: GUI with Matlab - moodle.technion.ac.il

2

Outline

• Graphics

• Animation

• Image and Video

• Graphics Objects

• Creating GUI

Page 3: GUI with Matlab - moodle.technion.ac.il

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')

Page 4: GUI with Matlab - moodle.technion.ac.il

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

Page 5: GUI with Matlab - moodle.technion.ac.il

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

Page 6: GUI with Matlab - moodle.technion.ac.il

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

Page 7: GUI with Matlab - moodle.technion.ac.il

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])

Page 8: GUI with Matlab - moodle.technion.ac.il

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

Page 9: GUI with Matlab - moodle.technion.ac.il

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

Page 10: GUI with Matlab - moodle.technion.ac.il

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')

Page 11: GUI with Matlab - moodle.technion.ac.il

11

Plot Gallery – Standard Plots

Page 12: GUI with Matlab - moodle.technion.ac.il

12

Plot Gallery – Standard Plots

Page 13: GUI with Matlab - moodle.technion.ac.il

13

Plot Gallery – Standard Plots

Page 14: GUI with Matlab - moodle.technion.ac.il

14

Plot Gallery – Standard Plots

Page 15: GUI with Matlab - moodle.technion.ac.il

15

Plot Gallery – Customizing Plots

Page 16: GUI with Matlab - moodle.technion.ac.il

16

Plot Gallery – Advanced Plots

Page 17: GUI with Matlab - moodle.technion.ac.il

17

Outline

• Graphics

• Animation

• Image and Video

• Graphics Objects

• Creating GUI

Page 18: GUI with Matlab - moodle.technion.ac.il

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

Page 19: GUI with Matlab - moodle.technion.ac.il

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

Page 20: GUI with Matlab - moodle.technion.ac.il

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]);

Page 21: GUI with Matlab - moodle.technion.ac.il

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

Page 22: GUI with Matlab - moodle.technion.ac.il

22

Outline

• Graphics

• Animation

• Image and Video

• Graphics Objects

• Creating GUI

Page 23: GUI with Matlab - moodle.technion.ac.il

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

Page 24: GUI with Matlab - moodle.technion.ac.il

24

Images

• Image viewer app

– imtool – Provides tools for pixel information, pixel region, distance, image information, adjust contrast, crop image, and display range

Page 25: GUI with Matlab - moodle.technion.ac.il

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

Page 26: GUI with Matlab - moodle.technion.ac.il

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);

Page 27: GUI with Matlab - moodle.technion.ac.il

27

Computer Vision System Toolbox

• VideoFileReader - Read video files

• VideoFileWriter - Write video files

• VideoPlayer- Play video

Page 28: GUI with Matlab - moodle.technion.ac.il

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);

Page 29: GUI with Matlab - moodle.technion.ac.il

29

Outline

• Graphics

• Animation

• Image and Video

• Graphics Objects

• Creating GUI

Page 30: GUI with Matlab - moodle.technion.ac.il

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

Page 31: GUI with Matlab - moodle.technion.ac.il

Graphics Object Hierarchy

31

Page 32: GUI with Matlab - moodle.technion.ac.il

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

Page 33: GUI with Matlab - moodle.technion.ac.il

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

Page 34: GUI with Matlab - moodle.technion.ac.il

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

Page 35: GUI with Matlab - moodle.technion.ac.il

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’)

Page 36: GUI with Matlab - moodle.technion.ac.il

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')

Page 37: GUI with Matlab - moodle.technion.ac.il

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;

Page 38: GUI with Matlab - moodle.technion.ac.il

38

Outline

• Graphics

• Animation

• Image and Video

• Graphics Objects

• Creating GUI

Page 39: GUI with Matlab - moodle.technion.ac.il

Creating GUI

• Three options:

39

1. GUIDE 2. App Designer

• Had been widely used

• Has many drawbacks

• Modern controls

• Better software design

Page 40: GUI with Matlab - moodle.technion.ac.il

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

Page 41: GUI with Matlab - moodle.technion.ac.il

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

Page 42: GUI with Matlab - moodle.technion.ac.il

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

Page 43: GUI with Matlab - moodle.technion.ac.il

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

Page 44: GUI with Matlab - moodle.technion.ac.il

GUIDE Example

44

Page 45: GUI with Matlab - moodle.technion.ac.il

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

Page 46: GUI with Matlab - moodle.technion.ac.il

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

Page 47: GUI with Matlab - moodle.technion.ac.il

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

Page 48: GUI with Matlab - moodle.technion.ac.il

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

Page 49: GUI with Matlab - moodle.technion.ac.il

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

Page 50: GUI with Matlab - moodle.technion.ac.il

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

Page 51: GUI with Matlab - moodle.technion.ac.il

App Designer Examples

51

Page 52: GUI with Matlab - moodle.technion.ac.il

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

Page 53: GUI with Matlab - moodle.technion.ac.il

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

Page 54: GUI with Matlab - moodle.technion.ac.il

More Information

• Mathworks documentation

– http://www.mathworks.com/help/

54

Page 55: GUI with Matlab - moodle.technion.ac.il

55