45
1 I I n n t t r r o o d d u u c c t t i i o o n n t t o o M M A A T T L L A A B B - MATLAB: Mat rix Lab oratory ( ( a a ) ) O O p p e e r r a a t t i i o o n n m m o o d d e e s s - MATLAB may be executed in interpreter, compiler, or background mode Interpreter mode * Type commands (statements) in the command window # A statement with semicolon at end: do not display result # A statement without semicolon: display result # Statements with commas: connect statements and display results # A statement of a single variable: just display the value # Percentage ('%'): comments # Each line is a single statement or connected statements

Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

  • Upload
    others

  • View
    9

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

1

IInnttrroodduuccttiioonn ttoo MMAATTLLAABB

- MATLAB: Matrix Laboratory

((aa)) OOppeerraattiioonn mmooddeess - MATLAB may be executed in interpreter, compiler, or background

mode Interpreter mode * Type commands (statements) in the command window

# A statement with semicolon at end: do not display result # A statement without semicolon: display result # Statements with commas: connect statements and display results # A statement of a single variable: just display the value # Percentage ('%'): comments # Each line is a single statement or connected statements

Page 2: Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

2

# Use “…” for connecting a lengthy statement # E.g.:

>> (4+5)*20 % ans: built-in variable for storing the last computation result ans = 180 >> a = (5-4)*20 a = 20 >> ans ans = 180 >> a = (4+5)*20; >> if a+b>=c+d && … m+n < x+y a = 0; end

* Use a text editor to write scripts (script file or M-file, with file extension “.m”), and then type the main filename in the command window # E.g., “test.m” file:

Page 3: Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

3

% test.m --> Script example; x and y already have values a = x + y

# Type main filename in the command window: >> x = 4, y = 5; >> test a = 9

* Execute DOS command in the command window, e.g., “>> !dir” * Use a text editor to write functions (function file or M-function, with file

extension “.m”), and then invoke with the main filename, e.g., “add2.m”: # The main filename is better the same as the function name

If different, the function should be invoked by the main filename # If there are comments after the function name, they can be displayed

by typing “help add2”: function z = add2(x, y) % A simple function example: add2.m file z = x + y;

Page 4: Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

4

# Type the following in the command window: >> x = 4, y = 5; >> help add2 A simple function example: add2.m file >> z = add2(x, y) z = 9

# Multiple input arguments and ouputs: function [x, y, z] = addm(a, b, c, d) if nargin-nargout ~= 1 disp('Incorrect number of input and output arguments'); return end switch nargout case 1 x=a+b; case 2 x=a+b; y=b+c; case 3 x=a+b; y=b+c; z=c+d; end

Page 5: Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

5

Compiler mode * Use a text editor to write a function file and then type “mcc –m add2.m”

in the command window to produce standalone .exe file, e.g.: function add(x, y) % add2.m file x = str2num(x), y = str2num(y); % Convert x, y strings to numbers z = x + y; fprintf('Result: %g', z);

# Execute DOS command in the command window (or in the DOS environment): >> !add2 4 5 Result: 9

Background mode Redirect standard input/output, eliminate the graphical output, and call MATLAB as a background process

* csh or tcsh: unsetenv DISPLAY

Page 6: Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

6

nohup nice matlab < commands.m >& results.log & * ksh or bash:

unset DISPLAY nohup nice matlab < commands.m > results.log 2>&1 & nohup matlab nodisplay nodesktop -nojvm -r test\(\'fig.tif\'\) &

((bb)) VVaarriiaabblleess aanndd ccoommmmaannddss - Variables

Every variable is an array (or matrix) * Scalar: 1×1 * Vector: 1×n (row vector) or n×1 (column vector) * Array: m×n range: 1…m (row), 1…n (column) * Mutidimensional array: m×n×p... Basic data types * Logical: 0 or 1 (false or true) * Char and string: enclosed by single quotation marks * Numeric

Page 7: Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

7

# 8, 16, 32, 64 bits unsigned integer: uint8, uint16, uint32, uint64 # 8, 16, 32, 64 bits integer: int8, int16, int32, int64 # 32-bit single precision floating point number: single # 64-bit double precision floating point number: double (default type) # Complex number: complex

No need to declare variables * Variables may dynamically change their data types or dimensions

>> a = 1; % 1x1 array >> a(2, 3) = 4 % Change dimension: 2x3 array a = 1 0 0 0 0 4

Build-in variables Function Return Value

ans Most recent answer (variable). If you do not assign an output variable to an expression, MATLAB automatically stores the result in ans.

eps Floating-point relative accuracy. This is the tolerance MATLAB uses in its calculations. Usually, eps is used to avoid division by zero, e.g.: z = x/(y+eps)

Page 8: Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

8

intmax Largest 8-, 16-, 32-, or 64-bit integer your computer can represent. intmin Smallest 8-, 16-, 32-, or 64-bit integer your computer can represent. realmax Largest floating-point number your computer can represent. realmin Smallest positive floating-point number your computer can represent. pi 3.1415926535897... i, j Imaginary unit. inf Infinity. Calculations like n/0, where n is any nonzero real value, result in inf. NaN Not a Number, an invalid numeric value. Expressions like 0/0 and inf/inf result in a NaN, as

do arithmetic operations involving a NaN. Also, if n is complex with a zero real part, then n/0 returns a value with a NaN real part.

computer Computer type. version MATLAB version string.

- Useful commands >> who % List all workspace variables >> who a % List workspace variable a >> whos % List all workspace variables with detailed information >> clear % Clear all workspace variables >> clear a % Clear workspace variable a >> close all % Close all windows

Page 9: Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

9

>> save filename % Save all workspace variable in a binary file “filename.mat” >> save filename x y z % Save workspace variables x, y, and z in “filename.mat” >> load filename >> tic % tic, toc: measures the computation time >> toc

- Special matrices >> eye(3) % Identity matrix ans = 1 0 0 0 1 0 0 0 1 >> ones(2, 3) % Matrix with all ones ans = 1 1 1 1 1 1 >> zeros(2) % Matrix with all zeros 0 0 0 0 >> rand(2, 5) % Random number matrix, range: [0, 1] ans = 0.6154 0.9218 0.1763 0.9355 0.4103

Page 10: Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

10

0.7919 0.7382 0.4057 0.9169 0.8936 >> [eye(2) rand(2)] % Build a matrix with blocks ans = 1.0000 0 0.5028 0.4289 0 1.0000 0.7095 0.3046 >> rand('seed', 2); % Seeding a random number generator >> magic(4) % Magic matrix: sums of each row or column are equal ans = 16 2 3 13 5 11 10 8 9 7 6 12 4 14 15 1

- Relational operators: <, <=, ==, >=, >, ~= - Logical operators

Scalars: &&, ||, ~ Element-wise: &, |, ~, xor() Bit-wise: bitand(), bitor(), bitcmp(), bitxor()

- Basic vector and matrix operations >> A = [1, -1, 0, 2]

Page 11: Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

11

A = 1 –1 0 2 >> A = [1 -1 0 2] % Commas between elements in a same row may be ommitted A = 1 –1 0 2 >> A(1, 2) % The elements of row 1 and column 2 of vector A ans = –1 >> A(1:3) % Colon means range ans = 1 –1 0 >> A(:) % Sole colon means all ans = 1 –1 0 2 >> A(2) = [ ] % Remove second element; [ ] means empty set A = 1 0 2 >> A = [1 2; 3 4] % Set a matrix A = 1 2 3 4 >> A + 2 % Matrix added by a scalar ans =

3 4

Page 12: Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

12

5 6 >> A * 2 % Matrix A multiplied by a scalar ans =

2 4 6 8

>> B = A(:) % One column vector B = 1 3 2 4 >> % MATLAB functions performs column computation in default >> sum(A) % Sums of every column in A ans = 5 7 9 >> sum(sum(A)) % Sum of all elements in A ans = 21 >> sum(A(:)) % Sum of all elements in A ans = 21 >> max(A) ans = 4 5 6

Page 13: Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

13

>> A + B; % Matrix A plus matrix B >> A – B; % A minus B >> A * B; % A multiplies B >> A .* B; % Multiplication of corresponding elements in A and B >> A / B; % Equals A*inv(B) >> A ./ B; % Division of corresponding elements in A and B >> A \ B; % Equals inv(A)*B >> A ^ N; % A to the N >> A .^ N; % Each element to the N >> B = A'; % Transposition >> A = [3 4 5 6; 7 8 9 10] % Set matrix A ans = 3 4 5 6 7 8 9 10 11 12 >> B = A(2, 1:3) % Elements from A’ second row, columns 1 to 3 B = 8 9 10 >> A(:, 2) = [ ] % Remove elements of column 2 A = 3 5 6 7 8 10 11 12 >> A(:, 2:4) = ones(2, 3) % Set the elements of 2 and 3 columns to 1 ans = 3 1 1 1

Page 14: Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

14

8 1 1 1 >> B = [10; 100]; >> new = [A B] % Append one column ans = 3 1 1 1 10 8 1 1 1 100 >> new(:, [1 5]) = [ ] % Remove first and 5th column new = 1 1 1 1 1 1 >> A = [1 2 3; 4 5 6]; >> B = A < 3 % Test if elements are less than 3 B = 1 1 0 0 0 0 >> C = A(B(:)) % A’s elements which correspond to 1’s in B (column vector) C = 1 2 >> A(B(:)) = 9 % Set A’s elements which correspond to elements 1’s in B ans = 9 9 3 4 5 6 >> A = [0 5 6; 7 0 0]; find(A) % Find nonzero elements in A (column order)

Page 15: Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

15

2 3 5 >> [x y v] = find(A); % Find nonzero elements and their coordinates (column order) >> [x y v ] = ans = 2 1 7 1 2 5 1 3 6 >> find(A>5 & A<8) % Find elements greater than 5 and less than 8 ans = 2 5

- Inline function >> f = inline('sqrt(x.^2+y.^2)', 'x', 'y') f = Inline function: f(x,y) = sqrt(x.^2+y.^2) >> A = [1, 2; 3, 4] >> B = ones(2) >> f(A, B) ans =

Page 16: Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

16

1.4142 2.2361 3.1623 4.1231

- Control for loop

for n=1:10 … end

while loop while n>2 … end

if…then control

if n>1 && m==3 … end if n~=1 && m==3 … elseif n>1 || m>=3 …

Page 17: Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

17

else … end

switch control switch n+3 case 2 … case 3 … otherwise … end

((cc)) IImmaaggee pprroocceessssiinngg ttoooollkkiitt ((IIPPTT)) - Image file formats supported: BMP, HDF, JPEG, PCX, PBM, PGM,

PNG, PNM, PPM, RAS, TIFF, XWD… - Image processing functions of IPT

Geometric operations

Page 18: Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

18

Neighborhood and block operations Linear filtering and filter design Transforms Image analysis and enhancement Binary image operations Region of interest operations

- Image types supported by IPT Indexed images: two matrices * A colormap: M×3 double array (M colors: R, G, B of range [0 ,1]) * An m×n image matrix: an integer pointing to an entry of the colormap

# Class double 1: row 1, 2: row 2, … # Class uint8 0: row 1, 1: row 2, …

Intensity images * An m×n matrix: uint8: range [0, 255], double: range [0, 1] Binary images * An m×n matrix of values 0 or 1

Page 19: Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

19

RGB images * An m×n×3 matrix R, G, B of range: uint8: [0, 255], double: [0, 1]

Indexed image

Intensity Image

Page 20: Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

20

Binary image

RGB image

- Image type conversions

Function Purpose dither Create a binary image from a grayscale intensity image by dithering; create an indexed image

from an RGB image by dithering gray2ind Create an indexed image from a grayscale intensity image grayslice Create an indexed image from a grayscale intensity image by thresholding Im2double Converts the intensity image to double precision, rescaling the data if necessary (range: [0, 1]). im2bw Create a binary image from an intensity image, indexed image, or RGB image, based on a

luminance threshold (values: 0, 1).

Page 21: Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

21

ind2gray Create a grayscale intensity image from an indexed image ind2rgb Create an RGB image from an indexed image mat2gray Create a grayscale intensity image from data in a matrix, by scaling the data rgb2gray Create a grayscale intensity image from an RGB image rgb2ind Create an indexed image from an RGB image

- Image coordinate systems Pixel coordinates: represented by row and column [r c] integers Spatial coordinates: represented by coordinate [x y] real numbers

1

2

3

1 2 3 c

r

0.5 1 2 1.5 x

y

2.5 3 0.5

1

2

1.5

2.5

3

3.5

3.5

Page 22: Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

22

- Read and write image files im = imread('lena.tif', 'tif'), imwrite(im, 'lena.jpg', 'jpg')

- Image file information: imfinfo('lena.tif')

- Image type double im2double(im): convert an intensity image to double precision, with values normalized to range [0, 1]

double(im): convert an intensity image to double precision, without normalization

- See the source code: type <function_name> - Display an image

imshow(im) imshow(im, [ ]) Normalize the pixel values to [0, 255] before display figure, imshow(im), impixelinfo Fix the display window and show pixel values

- Image size: [r c] = size(im) Numbers of rows and columns

Page 23: Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

23

r = size(im, 1) Take the first element: number of rows c = size(im, 2) Take the second element: number of columns

- Plotting plot(x, y) Plot y versus index x, e.g. (Fig. 1) : x = -pi:pi/10:pi; y = tan(sin(x)) - sin(tan(x)); plot(x, y, '--rs', 'LineWidth', 2, 'MarkerEdgeColor', 'k', 'MarkerFaceColor','g', ... 'MarkerSize',10)

Fig. 1 Fig. 2

Page 24: Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

24

subplot(r, c, n) Plot multiple figures: r rows, c columns, n=1:r×c * E.g. (Fig. 2):

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)

hold on: holds current plot on; allows overlap plotting hold off: turns off the hold; next plot will overwrite current plot

((dd)) GGeeoommeettrriicc ooppeerraattiioonnss - Resizing

im = imresize(im, 2, method) * method: 'nearest', 'bilinear', 'bicubic' (interpolation) im = imresize(im, 2, 'bilinear') Double the height and width im = imresize(im, [100, 200], 'bilinear') Set the size to be 100×200

- Rotation

Page 25: Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

25

im = imrotate(im, 30, 'bilinear') Rotate 30 degrees counter-clockwise im = imrotate(im, 30, 'bilinear', 'crop') Keep the original size by cropping the additional part resulted from rotation

- Cropping im = imcrop(im) Interactive cropping (controlled by the mouse) im = imcrop(im, [20 40 50 70]) From location (20, 40), crop 50×70 area

((ee)) NNeeiigghhbboorrhhoooodd aanndd bblloocckk pprroocceessssiinngg - Types of block processing operations

Sliding neighborhood operations Output pixel value = some algorithm performed on the neighborhood (with zero padding) of the corresponding input pixel (same operation on every pixel)

* Operation is performed one pixel at a time, e.g., sobel edge detection >> s = [1 2 1; 0 0 0; –1 –2 –1]; % Sobel operator >> E = conv2(im, s); % Convolution to detect horizontal edges

Page 26: Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

26

>> E = conv2(E, s'); % Convolution to detect vertical edges

Distinct block operations Divide the image into same-size and nonoverlapping blocks (with zero padding), and then perform operations on each block

* E.g., set every pixel in an 8×8 block to the intensity average im = blkproc(im, [8 8], 'mean2(x)*ones(size(x))');

Sliding neighborhood operation

Distinct block operation

Page 27: Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

27

((ff)) LLiinneeaarr ffiilltteerriinngg - Linear filtering: output pixel value is a linear combination of the

neighborhood pixel values Convolution, e.g.:

>> k = [4 –3 1; 4 6 2]; % Convolution kernel >> B = conv2(im, k, 'same');

Correlation, e.g.: >> h = [2 6 4; 1 –3 4]; % Convolution kernel >> B = filter2(im, h, 'same');

Using a predefined filter type, e.g., Gaussian smoothing operation: >> im = imread('lenna.tif'); % Read input image >> h = fspecial('gaussian', 3, 0.5); % A 3×3 Gaussian filter with σ = 0.5 >> imf = imfilter(im, h, 'replicate'); % Filter (smooth) the image

* Filter types # 'gaussian', 'sobel', 'prewitt', 'laplacian', 'log', 'average', 'unsharp'

Page 28: Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

28

((gg)) NNoonnlliinneeaarr ffiilltteerriinngg - Nonlinear filtering: output pixel value is a nonlinear combination of

the neighborhood pixel values - MATLAB nonlinear filtering: nlfilter( )

var = nlfilter(g, [m n], 'std2(x).^2'); var: local variance # Compute var using an inline function:

fun1 = inline('std2(x)^2'); var = nlfilter(g, [m n], fun1);

# Compute var using a function handle @: var = nlfilter(g, [m n], @fun2);

M-file fun2.m: function v = fun2(x) v = std2(x)^2;

# Compute var using colfilt (column filtering: much faster): fun3 = inline('std(x).^2')

Page 29: Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

29

var = colfilt(g, [m n], 'sliding', fun3);

((hh)) TTrraannssffoorrmmss - Image transforms

Discrete Fourier transform (DFT): F = fft2(im), f = ifft2(F) * im1 = fft2(im), imshow(abs(im1), [ ]) * im1 = fftshift(fft2(im)), imshow(log(1+abs(im1)), [ ]) Shift origin to center

and scale the values (original range: [0, 2040000])

Discrete cosine transform (DCT): D = dct2(im), d = idct2(D) * im = dct2('lena.tif'), imshow(log(abs(im)), [ ]), colormap(jet), colorbar

u

v

v

u

Page 30: Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

30

Discrete wavelet transform (DWT) * [cA, cH, cV, cD] = dwt2(im, 'db1'), x = idwt2([cA, cH, cV, cD], 'db1')

- Affine transform: rotation, scaling, shearing, and translation Note: in MATLAB the transformation matrix is on the right side

[ ] [ ] [ ]

==′′

100

1 11

3231

2221

1211

tttttt

yxTyxyx

Page 31: Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

31

Identity: x' = x y' = y

=

100010001

I

Rotation (clockwise): x' = xcosθ – ysinθ y' = xsinθ + ycosθ

−=

1000cossin0sincos

θθθθ

R

Scaling : x' = Sxx y' = Syy

=

1000000

y

x

SS

S

Shearing (horizontal): x' = x + αy y' = y

=

10001001

αxS

Page 32: Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

32

Shearing (vertical):x' = x y' = βx + y

=

10001001 β

yS

Translation: x' = x + δ x y' = y + δy

=1010001

yx

Tδδ

MATLAB point transform: * Create spatial transformation structure: tform = maketform(type,

Transform_matrix) * Type: 'affine', 'projective', 'custom', 'box', 'composit' * E.g., XY is a matrix of points, with each point represented by (x, y)

XY = [1 1; 2 3; 5 7]; tform = maketform('affine', [2 0 0; 0 3 0; 0 0 1]); Scaling matrix XY1 = tformfwd(XY, tform); Forward transform: XY1 = [2 3; 4 9; 10 21] XY = tforminv(XY1, tform); Inverse transform: XY = [1 1; 2 3; 5 7]

Page 33: Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

33

MATLAB image transform: * Scan each pixel of the output image, and compute the corresponding

location in the input image using T–1{(x, y)}, e.g., rotate 30 degrees x = pi/6; R = [cos(x) sin(x) 0; -sin(x) cos(x) 0; 0 0 1]; Rotation matrix tform = maketform('affine', R); [g xdata ydata] = imtransform(f, tform); figure, imshow(uint8(g), 'XData', xdata, 'YData', ydata), title('Image g'); impixelinfo, axis on, axis([xdata ydata]);

* Example: transform.m

Page 34: Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

34

function transform(fn) im = double(imread(fn)); figure, imshow(im), title('Original'); coord = [-200 600 -200 600]; T = [1 0 0; 0 1 0; 100 200 1]; % Translation matrix t = pi/6; R = [cos(t) sin(t) 0; -sin(t) cos(t) 0; 0 0 1]; % Rotation matrix: 30 degrees tform = maketform('affine', T); [translate xdata ydata] = imtransform(im, tform); figure, imshow(translate, [ ], 'XData', xdata, 'YData', ydata), title('Translate'); impixelinfo, axis on, axis([xdata ydata]); tform = maketform('affine', R); [rotate xdata ydata] = imtransform(im, tform); figure, imshow(rotate, [ ], 'XData', xdata, 'YData', ydata), title('Rotate'); impixelinfo, axis on, axis([xdata ydata]); [rotate xdata ydata] = imtransform(translate, tform, 'udata', xdata, 'vdata', ydata); figure, imshow(rotate, [ ], 'XData', xdata, 'YData', ydata), title('Translate and then rotate'); impixelinfo, axis on, axis([xdata ydata]); tform = maketform('affine', R*T); [r_t xdata ydata] = imtransform(im, tform);

Page 35: Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

35

figure, imshow(r_t, [ ], 'XData', xdata, 'YData', ydata), title('Rotate and translate'); impixelinfo, axis on, axis([xdata ydata]); tform = maketform('affine', T*R); [t_r xdata ydata] = imtransform(im, tform); figure, imshow(t_r, 'XData', xdata, 'YData', ydata), title('Translate and rotate'); impixelinfo, axis on, axis([xdata ydata]);

((ii)) AAnnaallyyzziinngg aanndd eennhhaanncciinngg iimmaaggeess - Pixel values and statistics

Mean value and standard deviation: mean2(im), std2(im) Display the image histogram: imhist(im)

- Image analysis Display the image contour: imcontour(im) Edge detection: edge(im, method, …) * method: 'sobel', 'prewitt', 'roberts', 'log', 'zerocross', 'canny'

Page 36: Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

36

Histogram

Contour

Edge

- Image enhancement Intensity adjustment: im1 = imadjust(im, [0 1], [0.5 0.8])

Adjust the intensity by mapping gray-level range [0 1] of the input image to range [0.5 0.8]

Histogram equalization: im1 = histeq(im) Add noise to an image: im1 = imnoise(im, type) * type: 'gaussian', 'localvar', 'poisson', 'salt & pepper', 'speckle'

- Image processing demos Directory: matlabroot\toolbox\images\imdemos

Page 37: Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

37

((jj)) PPrrooggrraamm eexxaammpplleess - Adaptive median filter

Adaptive median filter works at two levels, A and B (Smax: max allowed window size) Level A: If zmin < zmed < zmax, go to level B

Else increase the window size If window size ≤ Smax, repeat level A Else output zmed

Level B: If zmin < zxy < zmax, output zxy ( do not filter) Else output zmed ( filter by replacing the pixel with zmed)

Advantage over medfilt2: less blurring and distortion

function f = adpmedian(g, Smax) %ADPMEDIAN performs adaptive median filtering. % F = ADPMEDIAN(G, SMAX) performs adaptive median filtering of % image G. The median filter starts at size 3-by-3 and iterates up % to size SMAX-by-SMAX. SMAX must be an odd integer greater than 1.

Page 38: Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

38

% SMAX must be an odd, positive integer greater than 1. if (Smax <= 1) | (Smax/2 == round(Smax/2)) | (Smax ~= round(Smax)) error('SMAX must be an odd interger > 1.') end [M, N] = size(g); % Initial setup. f = zeros(M, N); alreadyProcessed = false(M, N); % Begin filtering for k = 3:2:Smax zmin = ordfilt2(g, 1, ones(k, k), 'symmetric'); zmax = ordfilt2(g, k*k, ones(k, k), 'symmetric'); zmed = medfilt2(g, [k k], 'symmetric'); processUsingLevelB = (zmed > zmin) & (zmax > zmed) & ~alreadyProcessed; zB = (g > zmin) & (zmax > g); outputZxy = processUsingLevelB & zB; outputZmed = processUsingLevelB & ~zB; f(outputZxy) = g(outputZxy); f(outputZmed) = zmed(outputZmed); alreadyProcessed = alreadyProcessed | processUsingLevelB; if all(alreadyProcessed(:))

Page 39: Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

39

break; end end % Output zmed for any remaining unprocessed pixels. Note that this % zmed was computed using a window of size Smax-by-Smax, which is % the final value of k in the loop. f(~alreadyProcessed) = zmed(~alreadyProcessed);

((kk)) CCooddee ooppttiimmiizzaattiioonn - MATLAB is designed for array operations

Whenever possible, using array operations instead of loops will result in significant increase in computation speed

- Preallocating arrays using zeros(size) or ones(size) When size of an array is know, preallocating it reduces memory fragmentation, hence improving speed

- Vectorizing loops

Page 40: Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

40

E.g., f(x) = Asin(x/2π), for x = 0, 1, …, M–1 for loop MATLAB index for x = 1:M f(x) = A * sin((x-1)/(2*pi)); end

x = 0:M-1; f = A * sin(x)/(2*pi));

E.g., f(x, y) = Asin(u0x + v0y), for x = 0, 1, …, M–1, y = 0, 1, …, N–1 for loop MATLAB meshgrid for r = 1:M u0x = u0 * (r-1); for c = 1:N v0y = v0 * (c-1); f(x, y) = A * sin(u0x + v0y) ; end end

r = 0:M-1; c = 0:N-1; [C R] = meshgrid(c, r); f = A * sin(u0*R + v0*C); % ~30 times faster

((ll)) WWeebb aapppplliiccaattiioonnss - Example 1: Windows OS, .NET, Appache, PHP

Install .NET (with c#)

Page 41: Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

41

Compile CallMat.vb program Public Class CallMAT Private Matlab = CreateObject("Matlab.Application") Public RtnValue As System.String Public Sub runMATCommand(ByVal aCommand As System.String) RtnValue = Matlab.Execute(aCommand) End Sub Public Sub quitMATLab() RtnValue = Matlab.Quit() End Sub End Class

PHP collects user input arguments and saves them in the text file input.txt

3 0.5 fig.jpg

* MATLAB M-function program: run.m Open input.txt to read input arguments and create output file

Page 42: Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

42

output.txt function run( ) fp = fopen('input.txt'); msize = fscanf(fp, '%d', 1); % Read one decimal number (mask size) sigma = fscanf(fp, '%g', 1); % Read one real number infn = fscanf(fp, '%s', 1); % Read one character string fclose(fp); im = imread(infn, 'jpg'); h = fspecial('gaussian', msize, sigma); im1 = imfilter(im, h, 'replicate'); imwrite(im1, 'result.jpg'); fp = fopen('output.txt'); fprintf(fp, '%d %g result.jpg', msize, sigma); fclose(fp);

* PHP program: <hthml> <head> </head> <body> // Collect user input arguments and store them in "input.txt" here.

Page 43: Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

43

<? echo(passthru("CallMATLab.exe \"run( );\" ")); ?> // Read "output.txt" and display the image <img src="result.jpg"></p> </body> </html>

- Example 2: Windows OS, .NET, Appache, JSP Install .NET (with c#) Compile CallMat.vb program

Public Class CallMAT Private Matlab = CreateObject("Matlab.Application") Public RtnValue As System.String Public Sub runMATCommand(ByVal aCommand As System.String) RtnValue = Matlab.Execute(aCommand) End Sub Public Sub quitMATLab() RtnValue = Matlab.Quit() End Sub

Page 44: Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

44

End Class

JSP: collects user input parameters and saves them in the text file input.txt

3 0.5 fig.jpg

* MATLAB M-function program: run.m Open input.txt to read input parameters and create output file output.txt

function run( ) fp = fopen('input.txt'); msize = fscanf(fp, '%d', 1); % Read one decimal number (mask size) sigma = fscanf(fp, '%g', 1); % Read one real number infn = fscanf(fp, '%s', 1); % Read one character string fclose(fp); im = imread(infn, 'jpg'); h = fspecial('gaussian', msize, sigma); im1 = imfilter(im, h, 'replicate'); imwrite(im1, 'result.jpg'); fp = fopen('output.txt');

Page 45: Introduction to MATLAB - 國立中興大學web.nchu.edu.tw/pweb/users/ykchan/lesson/6593.pdfMATLAB automatically stores the result in ans. eps Floating-point relative accuracy. This

45

fprintf(fp, '%d %g result.jpg', msize, sigma); fclose(fp);

* JSP program: <hthml> <head> </head> <body> // Collect user input parameters and store them in "input.txt" <? echo(passthru("CallMATLab.exe \"run( );\" ")); ?> // Read "output.txt" and display the image <img src="result.jpg"></p> </body> </html>