Top Banner
MATLAB Tutorial Course A.H. Taherinia
92

MATLAB Tutorial Course - Sharif

Mar 23, 2022

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: MATLAB Tutorial Course - Sharif

MATLAB Tutorial Course

A.H. Taherinia

Page 2: MATLAB Tutorial Course - Sharif

Matlab Environment

Page 3: MATLAB Tutorial Course - Sharif

Contents Continued

Desktop toolsmatricesLogical &Mathematical operationsHandle Graphics

1

Page 4: MATLAB Tutorial Course - Sharif

MATLAB Desktop Tools

Command WindowCommand HistoryHelp BrowserWorkspace BrowserEditor/Debugger

2

Page 5: MATLAB Tutorial Course - Sharif

3

Page 6: MATLAB Tutorial Course - Sharif

Calculations at the Command Line

» a = 2;

» b = 5;

» a^b

ans =

32

» x = 5/2*pi;

» y = sin(x)

y =

1

» z = asin(y)

z =

1.5708

» a = 2;

» b = 5;

» a^b

ans =

32

» x = 5/2*pi;

» y = sin(x)

y =

1

» z = asin(y)

z =

1.5708

Results assigned to “ans” if name not specified

() parentheses for function inputs

Semicolon suppresses screen output

MATLAB as a calculator Assigning Variables

A Note about Workspace:Numbers stored in double-precision floating point format

» -5/(4.8+5.32)^2ans =

-0.0488» (3+4i)*(3-4i)ans =

25» cos(pi/2)ans =6.1230e-017

» exp(acos(0.3))ans =

3.5470

» -5/(4.8+5.32)^2ans =

-0.0488» (3+4i)*(3-4i)ans =

25» cos(pi/2)ans =6.1230e-017

» exp(acos(0.3))ans =

3.5470

4

Page 7: MATLAB Tutorial Course - Sharif

General Functionswhos: List current variablesclear: Clear variables and functions from memoryClose: Closes last figurescd: Change current working directorydir: List files in directoryecho: Echo commands in M-filesformat: Set output format

5

Page 8: MATLAB Tutorial Course - Sharif

Matlab Help

6

Page 9: MATLAB Tutorial Course - Sharif

Getting helphelp command (>>help)

lookfor command (>>lookfor)

Help Browser (>>doc)

helpwin command (>>helpwin)

Search EnginePrintable Documents

“Matlabroot\help\pdf_doc\”Link to The MathWorks

7

Page 10: MATLAB Tutorial Course - Sharif

Matrices

Entering and Generating MatricesConcatenationDeleting Rows and ColumnsArray ExtractionMatrix and Array Multiplication

8

Page 11: MATLAB Tutorial Course - Sharif

» a=[1 2;3 4]

a =

1 2

3 4

» b=[-2.8, sqrt(-7), (3+5+6)*3/4]

b =

-2.8000 0 + 2.6458i 10.5000

» b(2,5) = 23

b =

-2.8000 0 + 2.6458i 10.5000 0 0

0 0 0 0 23.0000

» a=[1 2;3 4]

a =

1 2

3 4

» b=[-2.8, sqrt(-7), (3+5+6)*3/4]

b =

-2.8000 0 + 2.6458i 10.5000

» b(2,5) = 23

b =

-2.8000 0 + 2.6458i 10.5000 0 0

0 0 0 0 23.0000

• Any MATLAB expression can be entered as a matrix element• Matrices must be rectangular. (Set undefined elements to zero)

Entering Numeric Arrays

Row separatorsemicolon (;)

Column separatorspace / comma (,)

Use square brackets [ ]

9

Page 12: MATLAB Tutorial Course - Sharif

The Matrix in MATLAB

4 10 1 6 2

8 1.2 9 4 25

7.2 5 7 1 11

0 0.5 4 5 56

23 83 13 0 10

1

2

Rows (m) 3

4

5

Columns(n)

1 2 3 4 51 6 11 16 21

2 7 12 17 22

3 8 13 18 23

4 9 14 19 24

5 10 15 20 25

A = A (2,4)

A (17)

Rectangular Matrix:Scalar: 1-by-1 arrayVector: m-by-1 array

1-by-n arrayMatrix: m-by-n array

10

Page 13: MATLAB Tutorial Course - Sharif

» w=[1 2;3 4] + 5w =

6 78 9

» x = 1:5

x =1 2 3 4 5

» y = 2:-0.5:0

y = 2.0000 1.5000 1.0000 0.5000 0

» z = rand(2,4)

z =

0.9501 0.6068 0.8913 0.45650.2311 0.4860 0.7621 0.0185

» w=[1 2;3 4] + 5w =

6 78 9

» x = 1:5

x =1 2 3 4 5

» y = 2:-0.5:0

y = 2.0000 1.5000 1.0000 0.5000 0

» z = rand(2,4)

z =

0.9501 0.6068 0.8913 0.45650.2311 0.4860 0.7621 0.0185

Scalar expansion

Creating sequences:colon operator (:)

Utility functions for creating matrices.

Entering Numeric Arrays

11

Page 14: MATLAB Tutorial Course - Sharif

Numerical Array Concatenation» a=[1 2;3 4]

a =

1 2

3 4

» cat_a=[a, 2*a; 3*a, 4*a; 5*a, 6*a]cat_a =

1 2 2 43 4 6 83 6 4 89 12 12 165 10 6 12

15 20 18 24

» a=[1 2;3 4]

a =

1 2

3 4

» cat_a=[a, 2*a; 3*a, 4*a; 5*a, 6*a]cat_a =

1 2 2 43 4 6 83 6 4 89 12 12 165 10 6 12

15 20 18 24

Use [ ] to combine existing arrays as matrix “elements”

Row separator:semicolon (;)

Column separator:space / comma (,)

Use square brackets [ ]

Note:The resulting matrix must be rectangular

4*a

12

Page 15: MATLAB Tutorial Course - Sharif

Deleting Rows and Columns » A=[1 5 9;4 3 2.5; 0.1 10 3i+1]

A =

1.0000 5.0000 9.0000

4.0000 3.0000 2.5000

0.1000 10.0000 1.0000+3.0000i

» A(:,2)=[]

A =

1.0000 9.0000

4.0000 2.5000

0.1000 1.0000 + 3.0000i

» A(2,2)=[]

??? Indexed empty matrix assignment is not allowed.

» A=[1 5 9;4 3 2.5; 0.1 10 3i+1]

A =

1.0000 5.0000 9.0000

4.0000 3.0000 2.5000

0.1000 10.0000 1.0000+3.0000i

» A(:,2)=[]

A =

1.0000 9.0000

4.0000 2.5000

0.1000 1.0000 + 3.0000i

» A(2,2)=[]

??? Indexed empty matrix assignment is not allowed.

13

Page 16: MATLAB Tutorial Course - Sharif

Array Subscripting / Indexing

4 10 1 6 2

8 1.2 9 4 25

7.2 5 7 1 11

0 0.5 4 5 56

23 83 13 0 10

1

2

3

4

5

1 2 3 4 51 6 11 16 21

2 7 12 17 22

3 8 13 18 23

4 9 14 19 24

5 10 15 20 25

A =

A(3,1)A(3)

A(1:5,5)A(:,5) A(21:25)

A(4:5,2:3)A([9 14;10 15])

A(1:end,end) A(:,end)A(21:end)’

14

Page 17: MATLAB Tutorial Course - Sharif

Matrix Multiplication» a = [1 2 3 4; 5 6 7 8];

» b = ones(4,3);

» c = a*b

c =

10 10 1026 26 26

» a = [1 2 3 4; 5 6 7 8];

» b = ones(4,3);

» c = a*b

c =

10 10 1026 26 26

[2x4][4x3]

[2x4]*[4x3] [2x3]

a(2nd row).b(3rd column)

» a = [1 2 3 4; 5 6 7 8];

» b = [1:4; 1:4];

» c = a.*b

c =

1 4 9 165 12 21 32

» a = [1 2 3 4; 5 6 7 8];

» b = [1:4; 1:4];

» c = a.*b

c =

1 4 9 165 12 21 32 c(2,4) = a(2,4)*b(2,4)

Array Multiplication

15

Page 18: MATLAB Tutorial Course - Sharif

Matrix Manipulation Functions• zeros: Create an array of all zeros• ones: Create an array of all ones• eye: Identity Matrix• rand: Uniformly distributed random numbers• diag: Diagonal matrices and diagonal of a matrix• size: Return array dimensions

16

Page 19: MATLAB Tutorial Course - Sharif

Matrix Manipulation Functions• transpose (’): Transpose matrix• rot90: rotate matrix 90• tril: Lower triangular part of a matrix• triu: Upper triangular part of a matrix• cross: Vector cross product• dot: Vector dot product• det: Matrix determinant• inv: Matrix inverse • rank: Rank of matrix

17

Page 20: MATLAB Tutorial Course - Sharif

Elementary Math

Logical Operators

Math Functions

18

Page 21: MATLAB Tutorial Course - Sharif

Logical Operations» Mass = [-2 10 NaN 30 -11 Inf 31];» each_pos = Mass>=0each_pos =

0 1 0 1 0 1 1» all_pos = all(Mass>=0)all_pos =

0» all_pos = any(Mass>=0)all_pos =

1» pos_fin = (Mass>=0)&(isfinite(Mass))pos_fin =

0 1 0 1 0 0 1

» Mass = [-2 10 NaN 30 -11 Inf 31];» each_pos = Mass>=0each_pos =

0 1 0 1 0 1 1» all_pos = all(Mass>=0)all_pos =

0» all_pos = any(Mass>=0)all_pos =

1» pos_fin = (Mass>=0)&(isfinite(Mass))pos_fin =

0 1 0 1 0 0 1

= = equal to> greater than

< less than

>= Greater or equal

<= less or equal

~ not

& and

| or

isfinite(), etc. . . .

all(), any()

find

Note:• 1 = TRUE• 0 = FALSE

19

Page 22: MATLAB Tutorial Course - Sharif

Elementary Math Function• abs, sign: Absolute value and Signum Function• sin, cos, asin, acos…: Triangular functions• exp, log, log10: Exponential, Natural and

Common (base 10) logarithm• ceil, floor: Round toward infinities• fix: Round toward zero

20

Page 23: MATLAB Tutorial Course - Sharif

Elementary Math Functionround: Round to the nearest integergcd: Greatest common devisorlcm: Least common multiplesqrt: Square root functionreal, imag: Real and Image part of

complexrem: Remainder after division

21

Page 24: MATLAB Tutorial Course - Sharif

Elementary Math Function• max, min: Maximum and Minimum of arrays• mean, median: Average and Median of arrays• std, var: Standard deviation and variance• sort: Sort elements in ascending order• sum, prod: Summation & Product of Elements

22

Page 25: MATLAB Tutorial Course - Sharif

Graphics Fundamentals

23

Page 26: MATLAB Tutorial Course - Sharif

GraphicsBasic Plotting

plot, title, xlabel, grid,legend, hold, axis

Editing PlotsProperty Editor

24

Page 27: MATLAB Tutorial Course - Sharif

2-D PlottingSyntax:

Example:plot(x1, y1, 'clm1', x2, y2, 'clm2', ...)plot(x1, y1, 'clm1', x2, y2, 'clm2', ...)

x=[0:0.1:2*pi];y=sin(x);z=cos(x);plot(x,y,x,z,'fontsize',14);legend('Y data','Z data ,'linewidth',2)title('Sample Plot','fontsize',14);xlabel('X values','fontsize',14);ylabel('Y values','fontsize',14);grid on

x=[0:0.1:2*pi];y=sin(x);z=cos(x);plot(x,y,x,z,'fontsize',14);legend('Y data','Z data ,'linewidth',2)title('Sample Plot','fontsize',14);xlabel('X values','fontsize',14);ylabel('Y values','fontsize',14);grid on

25

Page 28: MATLAB Tutorial Course - Sharif

Sample PlotTitle

Ylabel

Xlabel

Grid

Legend

26

Page 29: MATLAB Tutorial Course - Sharif

Subplot

subplot(m,n,p)

income = [3.2 4.1 5.0 5.6];outgo = [2.5 4.0 3.35 4.9];subplot(2,1,1); plot(income);subplot(2,1,2); plot(outgo);

income = [3.2 4.1 5.0 5.6];outgo = [2.5 4.0 3.35 4.9];subplot(2,1,1); plot(income);subplot(2,1,2); plot(outgo);

27

Page 30: MATLAB Tutorial Course - Sharif

Subplot

28

Page 31: MATLAB Tutorial Course - Sharif

Subplot

subplot(m,n,p)

income = [3.2 4.1 5.0 5.6];outgo = [2.5 4.0 3.35 4.9];subplot(2,2,[1 3]); plot(income);subplot(2,2,2); plot(outgo);subplot(2,2,4); plot(income+outgo);

income = [3.2 4.1 5.0 5.6];outgo = [2.5 4.0 3.35 4.9];subplot(2,2,[1 3]); plot(income);subplot(2,2,2); plot(outgo);subplot(2,2,4); plot(income+outgo);

29

Page 32: MATLAB Tutorial Course - Sharif

Subplot

30

Page 33: MATLAB Tutorial Course - Sharif

SubplotsSyntax:

»subplot(2,2,1); » …

»subplot(2,2,2)» ...

»subplot(2,2,3)» ...

»subplot(2,2,4)» ...

»subplot(2,2,1); » …

»subplot(2,2,2)» ...

»subplot(2,2,3)» ...

»subplot(2,2,4)» ...

subplot(rows,cols,index)subplot(rows,cols,index)

31

Page 34: MATLAB Tutorial Course - Sharif

Programming andApplication Development

32

Page 35: MATLAB Tutorial Course - Sharif

Script and Function Files• Script Files

• Work as though you typed commands into MATLAB prompt

• Variable are stored in MATLAB workspace

• Function Files• Let you make your own MATLAB Functions• All variables within a function are local• All information must be passed to functions as

parameters• Sub functions are supported

33

Page 36: MATLAB Tutorial Course - Sharif

Basic Parts of a Function M-File

function y = mean (x)% MEAN Average or mean value.% For vectors, MEAN(x) returns the mean value.% For matrices, MEAN(x) is a row vector% containing the mean value of each column.[m,n] = size(x);if m == 1

m = n;endy = sum(x)/m;

Output Arguments Input ArgumentsFunction Name

Online Help

Function Code

34

Page 37: MATLAB Tutorial Course - Sharif

eps = 1;

while (1+eps) > 1

eps = eps/2;

end

eps = eps*2

eps = 1;

while (1+eps) > 1

eps = eps/2;

end

eps = eps*2

while Loops

Flow Control Statements

35

a = zeros(k,k) % Preallocate matrix

for m = 1:k

for n = 1:k

a(m,n) = 1/(m+n -1);

end

end

a = zeros(k,k) % Preallocate matrix

for m = 1:k

for n = 1:k

a(m,n) = 1/(m+n -1);

end

end

for Loop

Page 38: MATLAB Tutorial Course - Sharif

method = 'Bilinear';

switch lower(method)

case {'linear','bilinear'}

disp('Method is linear')

case 'cubic'

disp('Method is cubic')

otherwise

disp('Unknown method.')

end

Method is linear

method = 'Bilinear';

switch lower(method)

case {'linear','bilinear'}

disp('Method is linear')

case 'cubic'

disp('Method is cubic')

otherwise

disp('Unknown method.')

end

Method is linear

Switch Statement

Flow Control Statements

36

if ((attendance >= 0.90) & (grade_average >= 60))

pass = 1;

end;

if ((attendance >= 0.90) & (grade_average >= 60))

pass = 1;

end;

if Statement

Page 39: MATLAB Tutorial Course - Sharif

Function M-file

function r = ourrank(X,tol)% rank of a matrixs = svd(X);if (nargin == 1)

tol = max(size(X)) * s(1)* eps;endr = sum(s > tol);

function r = ourrank(X,tol)% rank of a matrixs = svd(X);if (nargin == 1)

tol = max(size(X)) * s(1)* eps;endr = sum(s > tol);

function [mean,stdev] = ourstat(x)[m,n] = size(x);if m == 1

m = n;endmean = sum(x)/m;stdev = sqrt(sum(x.^2)/m – mean.^2);

function [mean,stdev] = ourstat(x)[m,n] = size(x);if m == 1

m = n;endmean = sum(x)/m;stdev = sqrt(sum(x.^2)/m – mean.^2);

Multiple Input Argumentsuse ( )

Multiple Output Arguments, use [ ]

»r=ourrank(rand(5),.1);

»[m std]=ourstat(1:9);

37

Page 40: MATLAB Tutorial Course - Sharif

38

Image Processing Toolbox

Page 41: MATLAB Tutorial Course - Sharif

Introduction

Collection of functions (MATLAB files) that supports a wide range of image processing operations

Page 42: MATLAB Tutorial Course - Sharif

Image Coordinate

Page 43: MATLAB Tutorial Course - Sharif

Read an ImageRead in an imageValidates the graphic format

(bmp, hdf, jpeg, pcx, png, tiff, xwd)

Store it in an arrayclear, close all;I = imread(‘pout.tif`);[X, map] = imread(‘pout.tif’);

Page 44: MATLAB Tutorial Course - Sharif

Display an Imageimshow(I)

Page 45: MATLAB Tutorial Course - Sharif

Check the Image in Memory< Name, Size, Bytes, Class >

whosName Size Bytes Classans 291x240 69840 uint8 array

Grand total is 69840 elements using 69840 bytes

[0, 1]double[0, 65535]uint16[0, 255]uint8

Page 46: MATLAB Tutorial Course - Sharif

Data Classes

Page 47: MATLAB Tutorial Course - Sharif

Convert between image Classes

Page 48: MATLAB Tutorial Course - Sharif

Histogram EqualizationHistogram: distribution of intensities

figure, imhist(I)

Equalize Image (contrast)I2 = histeq(I);

figure, imshow(I2)figure, imhist(I2)

Page 49: MATLAB Tutorial Course - Sharif

Histogram Equalization (cont.)

Page 50: MATLAB Tutorial Course - Sharif

Histogram Equalization (cont.)

Page 51: MATLAB Tutorial Course - Sharif

Write the Image

Validates the extensionWrites the image to disk

imwrite(I2, ’pout2.png’);imwrite(I2, ‘pout2.png’, ‘BitDepth’, 4);

Page 52: MATLAB Tutorial Course - Sharif

Filtering Using imfilter

Filtering of images, either by correlation or convolution, can be performed using the toolbox function imfilter.

This example filters an image with a 5-by-5 filter containing equal weights. Such a filter is often called an averaging averaging filterfilter..

Page 53: MATLAB Tutorial Course - Sharif

Filtering Using imfilterI = imread('coins.png');h = ones(5,5) / 25;I2 = imfilter(I,h);imshow(I), title('Original Image');figure, imshow(I2), title('Filtered Image')

Page 54: MATLAB Tutorial Course - Sharif

Create special 2-D filters

h = fspecial(type) creates a two-dimensional filter h of the specified type.

Syntaxh = fspecial(type)h = fspecial(type,parameters)

Page 55: MATLAB Tutorial Course - Sharif

Create special 2-D filters

Page 56: MATLAB Tutorial Course - Sharif

Using Median Filtering

Median filtering is similar to using an averaging filter, in that each output pixel is set to an average of the pixel values in the neighborhood of the corresponding input pixel.

B = medfilt2(A,[m n])B = medfilt2(A)B = medfilt2(A,'indexed',...)

Page 57: MATLAB Tutorial Course - Sharif

Using Median Filtering

I = imread('eight.tif');subplot(2,2,1), imshow(I), title('Original image');J = imnoise(I,'salt & pepper',0.02);subplot(2,2,2), imshow(J), title('Salt & pepper noise add');K = imfilter(J, fspecial('average',3));subplot(2,2,3), imshow(K), title('averaging filter');L = medfilt2(J,[3 3]);subplot(2,2,4), imshow(L), title('median filter');

Page 58: MATLAB Tutorial Course - Sharif

Median Filtering

Page 59: MATLAB Tutorial Course - Sharif

Image Arithmetic

imabsdiffimaddimcomplementimdivide

imlincombimmultiplyimsubtract

Page 60: MATLAB Tutorial Course - Sharif

Adding Images

X = uint8([ 255 0 75; 44 225 100]);Y = uint8([ 50 50 50; 50 50 50 ]);Z = imadd(X,Y)Z =

255 50 125 94 255 150

Page 61: MATLAB Tutorial Course - Sharif

Adding Images (cont.)I = imread(‘rice.tif’);

J = imread(‘cameraman.tif’);K = imadd(I, J);imshow(K)

Page 62: MATLAB Tutorial Course - Sharif

Adding Images (cont.)Brighten an image results saturation

RGB = imread(‘flowers.tif’);RGB2 = imadd(RGB, 50);subplot(1, 2, 1); imshow(RGB);subplot(1, 2, 2); imshow(RGB2);

Page 63: MATLAB Tutorial Course - Sharif

Subtracting Images

Background of a scenerice = imread(‘rice.tif’);background = imopen(rice, strel(‘disk’, 15));rice2 = imsubtract(rice, background);imshow(rice), figure, imshow(rice2);

Negative valuesimabsdiff

Page 64: MATLAB Tutorial Course - Sharif

Subtracting Images (cont.)

Page 65: MATLAB Tutorial Course - Sharif

Multiplying Images

Scaling: multiply by a constant(brightens >1, darkens <1)

Preserves relative contrastI = imread(‘moon.tif’);J = immultiply(I, 1.2);imshow(I);figure, imshow(J)

Page 66: MATLAB Tutorial Course - Sharif

Multiplying Images (cont.)

Page 67: MATLAB Tutorial Course - Sharif

Dividing Images (Ratioing)I = imread('rice.png'); J = imdivide(I,2);subplot(1,2,1), imshow(I)subplot(1,2,2), imshow(J)

Page 68: MATLAB Tutorial Course - Sharif

Spatial Transformations

Map pixel locations in an input image to new locations in an output image

ResizingRotationCropping

Page 69: MATLAB Tutorial Course - Sharif

Resizing Images

Change the size of an imageI = imread(‘ic.tif’); J = imresize(I, 1.25);K = imresize(I, [100 150]);figure, imshow(J)figure, imshow(K)

Page 70: MATLAB Tutorial Course - Sharif

Resizing Images (cont.)

Page 71: MATLAB Tutorial Course - Sharif

Rotating Images

Rotate an image by an angle in degreesI = imread(‘ic.tif’); J = imrotate(I, 35, ‘bilinear’);imshow(I)figure, imshow(J)

Page 72: MATLAB Tutorial Course - Sharif

Rotating Images (cont.)

Page 73: MATLAB Tutorial Course - Sharif

Cropping Images

Extract a rectangular portion of an image

imshow ic.tifI = imcrop;

Page 74: MATLAB Tutorial Course - Sharif

GUIDE

GUIDE:Graphical User Interface Design Environment

Page 75: MATLAB Tutorial Course - Sharif

GUIDE

Page 76: MATLAB Tutorial Course - Sharif

Morphological Opening

Remove objects that cannot completely contain a structuring element

Estimate background illuminationclear, close allI = imread(‘rice.png’);imshow(I)background = imopen(I, strel(‘disk’, 15));imshow(background)

Page 77: MATLAB Tutorial Course - Sharif

Morphological Opening (cont.)

Page 78: MATLAB Tutorial Course - Sharif

Subtract Images

Create a more uniform backgroundI2 = imsubtract(I, background);figure, imshow(I2)

Page 79: MATLAB Tutorial Course - Sharif

Adjust the Image Contrast

stretchlim computes [low hight] to be mapped into [bottom top]

I3 = imadjust(I2, stretchlim(I2), [0 1]);figure, imshow(I3)

Page 80: MATLAB Tutorial Course - Sharif

Apply Thresholding to the Image

Create a binary thresholded image1. Compute a threshold to convert the intensity

image to binary2. Perform thresholding creating a logical matrix

(binary image)level = graythresh(I3);bw = im2bw(I3, level);figure, imshow(bw)

Page 81: MATLAB Tutorial Course - Sharif

Apply Thresholding to the Image (cont.)

Page 82: MATLAB Tutorial Course - Sharif

Labeling Connected Components

Determine the number of objects in the imageAccuracy

(size of objects, approximated background, connectivity parameter, touching objects)

[labeled, numObjects] = bwlabel(bw, 4);numObjects {= 80}

max(labeled(:))

Page 83: MATLAB Tutorial Course - Sharif

Select and Display Pixels in a Region

Interactive selectiongrain = imcrop(labeled)

Colormap creation functionRGB_label = label2rgb(labeled,

@spring, ‘c’, ‘shuffle’);imshow(RGB_label);rect = [15 25 10 10];roi = imcrop(labeled, rect)

Page 84: MATLAB Tutorial Course - Sharif

Object Properties

Measure object or region propertiesgraindata = regionprops(labeled, ‘basic’)graindata(51).Area {296}graindata(51).BoundingBox {142.5 89.5 24.0 26.0}graindata(51).Centroid {155.3953 102.1791}

Create a vector which holds just one property for each object

allgrains = [graindata.Area];whos

Page 85: MATLAB Tutorial Course - Sharif

Statistical Properties of Objects

max(allgrains) { 695 }

Return the component label of a grain size

biggrain = find(allgrains == 695) { 68 }

Mean grain sizemean(allgrains) { 249 }

Histogram (#bins)hist(allgrains, 20)

Page 86: MATLAB Tutorial Course - Sharif

Statistical Properties of Objects (cont.)

Page 87: MATLAB Tutorial Course - Sharif

Storage Classes

double (64-bit), uint8 (8-bit), and uint16 (16-bit)

Converting (rescale or offset)doubleim2double (automatic rescale and offsetting)RGB2 = im2uint8(RGB1);im2uint16imapprox (reduce number of colors: indexed images)

Page 88: MATLAB Tutorial Course - Sharif

Image Types

IndexData matrix (uint8, uint16, double)Colormap matrix (m x 3 array of double [0 1])

Intensity (black = 0, white = ∞)Binary (0, 1)

B = logical(uint8(round(A))); (logical flag on)

B = +A; (logical flag off)

RGB (m x n x 3 of truecolor)

Page 89: MATLAB Tutorial Course - Sharif

Converting Image Types

dithergray2indgraysliceim2bwind2gray

ind2rgbmat2grayrgb2grayrgb2ind

Page 90: MATLAB Tutorial Course - Sharif

Multiframe Image Arrays

Same size, #planes, colormapStore separate images into one multiframe array

A = cat(4, A1, A2, A3, A4, A5)

Extract frames from a multiframe arrayFRM3 = MULTI(:, :, :, 3)

Display a frameimshow(MULTI(:, :, :, 7))

Page 91: MATLAB Tutorial Course - Sharif

Coordinate Systems

Pixel CoordinatesDiscrete unit (integer)(r, c)⎡ = (1, 1)

Spatial CoordinatesContinuous unit(x, y)⎡= (0.5, 0.5)

123

Page 92: MATLAB Tutorial Course - Sharif

Non-default Spatial Coordinate System

A = magic(5);x = [19.5 23.5];y = [8.0 12.0];image(A, ‘xData’, x, ‘yData’, y), axis image, colormap(jet(25))