Digital Image Analysis and Processing CPE

Similar documents
Introduction to Engineering gii

Dr. Iyad Jafar. Adapted from the publisher slides

PROGRAMMING WITH MATLAB DR. AHMET AKBULUT

Introduction to MATLAB for Engineers, Third Edition

Introduction to MATLAB

This appendix provides a quick start introduction to MATLAB. You should be

Introduction to MATLAB 7 for Engineers

Introduction to Matlab. By: Dr. Maher O. EL-Ghossain

Chapter 1 Introduction to MATLAB

Introduction to MATLAB

OUTLINES. Variable names in MATLAB. Matrices, Vectors and Scalar. Entering a vector Colon operator ( : ) Mathematical operations on vectors.

Introduction to MATLAB 7 for Engineers

2.0 MATLAB Fundamentals

ECE Lesson Plan - Class 1 Fall, 2001

Introduction to MATLAB

Introduction to MatLab. Introduction to MatLab K. Craig 1

MATLAB Basics EE107: COMMUNICATION SYSTEMS HUSSAIN ELKOTBY

Outline. CSE 1570 Interacting with MATLAB. Starting MATLAB. Outline. MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An.

1 Overview of the standard Matlab syntax

Outline. CSE 1570 Interacting with MATLAB. Starting MATLAB. Outline (Cont d) MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An

To start using Matlab, you only need be concerned with the command window for now.

Finding, Starting and Using Matlab

Dr. Iyad Jafar. Adapted from the publisher slides

Dr Richard Greenaway

Outline. CSE 1570 Interacting with MATLAB. Outline. Starting MATLAB. MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An.

PART 1 PROGRAMMING WITH MATHLAB

Constraint-based Metabolic Reconstructions & Analysis H. Scott Hinton. Matlab Tutorial. Lesson: Matlab Tutorial

Introduction to MATLAB

SECTION 1: INTRODUCTION. ENGR 112 Introduction to Engineering Computing

Introduction to MATLAB

MATLAB QUICK START TUTORIAL

Desktop Command window

MATLAB Tutorial. Digital Signal Processing. Course Details. Topics. MATLAB Environment. Introduction. Digital Signal Processing (DSP)

Introduction to MATLAB

Matlab is a tool to make our life easier. Keep that in mind. The best way to learn Matlab is through examples, at the computer.

EGR 111 Introduction to MATLAB

Starting Matlab. MATLAB Laboratory 09/09/10 Lecture. Command Window. Drives/Directories. Go to.

AN INTRODUCTION TO MATLAB

Introduction to MATLAB

Lecturer: Keyvan Dehmamy

MATLAB Programming for Numerical Computation Dr. Niket Kaisare Department Of Chemical Engineering Indian Institute of Technology, Madras

Laboratory 1 Octave Tutorial

MATLAB Tutorial EE351M DSP. Created: Thursday Jan 25, 2007 Rayyan Jaber. Modified by: Kitaek Bae. Outline

Introduction to MATLAB

Ordinary Differential Equation Solver Language (ODESL) Reference Manual

Introduction to Matlab

EP375 Computational Physics

An Introduction to MATLAB

Chapter 2. MATLAB Basis

Introduction to MATLAB

MATLAB COURSE FALL 2004 SESSION 1 GETTING STARTED. Christian Daude 1

1 Introduction to Matlab

Introduction to MATLAB. Simon O Keefe Non-Standard Computation Group

Chapter 3 Functions and Files

AMS 27L LAB #1 Winter 2009

Experiment 1: Introduction to MATLAB I. Introduction. 1.1 Objectives and Expectations: 1.2 What is MATLAB?

Introduction to MATLAB. Computational Probability and Statistics CIS 2033 Section 003

PowerPoints organized by Dr. Michael R. Gustafson II, Duke University

STAT/MATH 395 A - PROBABILITY II UW Winter Quarter Matlab Tutorial

Numerical Analysis First Term Dr. Selcuk CANKURT

Dr Richard Greenaway

Introduction to. The Help System. Variable and Memory Management. Matrices Generation. Interactive Calculations. Vectors and Matrices

MATLAB Basics. Configure a MATLAB Package 6/7/2017. Stanley Liang, PhD York University. Get a MATLAB Student License on Matworks

Variables are used to store data (numbers, letters, etc) in MATLAB. There are a few rules that must be followed when creating variables in MATLAB:

Digital Image Processing

MATLAB Tutorial. Mohammad Motamed 1. August 28, generates a 3 3 matrix.

ELEC4042 Signal Processing 2 MATLAB Review (prepared by A/Prof Ambikairajah)

MATLAB Project: Getting Started with MATLAB

McTutorial: A MATLAB Tutorial

Chapter 2. MATLAB Fundamentals

NatSciLab - Numerical Software Introduction to MATLAB

MATLAB Project: Getting Started with MATLAB

This is a basic tutorial for the MATLAB program which is a high-performance language for technical computing for platforms:

What is MATLAB? What is MATLAB? Programming Environment MATLAB PROGRAMMING. Stands for MATrix LABoratory. A programming environment

VARIABLES Storing numbers:

Introduction to Matlab

ANSI C Programming Simple Programs

MatLab Just a beginning

MATLAB Fundamentals. Berlin Chen Department of Computer Science & Information Engineering National Taiwan Normal University

Welcome to EGR 106 Foundations of Engineering II

1 Introduction to MATLAB

1 Introduction to MATLAB

Introduction to Matlab. Summer School CEA-EDF-INRIA 2011 of Numerical Analysis

Matlab Programming Introduction 1 2

Getting started with MATLAB

User-defined Functions

CITS2401 Computer Analysis & Visualisation

Lecture 2: Variables, Vectors and Matrices in MATLAB

Introduction to MATLAB

Introduction to MATLAB. Dr./ Ahmed Nagib Elmekawy Mechanical Engineering department, Alexandria university, Egypt Spring 2017.

An Introduction to MATLAB and the Control Systems toolbox Aravind Parchuri, Darren Hon and Albert Honein

Lab of COMP 406. MATLAB: Quick Start. Lab tutor : Gene Yu Zhao Mailbox: or Lab 1: 11th Sep, 2013

Starting with a great calculator... Variables. Comments. Topic 5: Introduction to Programming in Matlab CSSE, UWA

Edward Neuman Department of Mathematics Southern Illinois University at Carbondale

the Enter or Return key. To perform a simple computations type a command and next press the

ME 121 MATLAB Lesson 01 Introduction to MATLAB

Introduction to MATLAB Programming

Mathematical Operations with Arrays and Matrices

Part V Appendices c Copyright, Todd Young and Martin Mohlenkamp, Department of Mathematics, Ohio University, 2017

Introduction to MATLAB

Transcription:

Digital Image Analysis and Processing CPE 0907544 Matlab Tutorial Dr. Iyad Jafar

Outline Matlab Environment Matlab as Calculator Common Mathematical Functions Defining Vectors and Arrays Addressing Vectors and Arrays Array vs Matrix Operations Script Files & Functions Programming in Matlab Basic Image Functions 2

Matlab Computer programming language and software environment to manage data interactively Originally developed in 1970s for applications involving matrices, linear algebra and numerical analysis Maintained and sold by the MathWorks, Inc. Functionality: manage variables, import/export data, calculations, generate plots, and more Toolboxes such as image processing, control, financial analysis, and more 3

Matlab Environment Menus Toolbar Current Directory Workspace Command History Command Window 4

Variables in MATLAB MATLAB does not require any type declarations or dimension statements. changes its contents and, if necessary, allocates new storage. For example, num_students = 25 creates a 1-by-1 matrix named num_students and stores the value 25 in its single element. To view any variable, simply enter the variable name. Variable names consist of a letter, followed by any number of letters, digits, or underscores. Matlab is case-sensitive! 5

Matlab as Calculator 6 >> 8/10 ans= 0.8000 >> 5*ans ans= 4 >> r=8/10 r = 0.8000 >> r r = 0.8000 >> s=20*r s = 16 NOTES ans is a built-in special variable to store the result of the last computation. Can be reused by typing ans variables defined by the assignment operator = are stored in memory and can be used again using their names

Scalar Arithmetic Operations Symbol Operation MATLAB Form ^ exponentiation: a b a^b * multiplication: ab a*b / right division: a/b a/b \ left division: b/a a\b + addition: a + b a + b - subtraction: a b a -b 7

Order of Precedence of Arithmetic Operators 1. Parentheses, evaluated starting with the innermost pair. 2. Exponentiation 3. Multiplication and division 4. Addition and subtraction Note: if precedence is equal, evaluation is performed from left to right. 8

Special Variables and Constants Command Description ans i,j inf NaN Temporary variable containing the most recent answer. The imaginary unit 1. Infinity. Indicates an undefined numerical result. pi The number π. 9

Some Commonly Used Mathematical Functions Function MATLAB syntax 10 e x x ln x log 10 x cos x sin x tan x cos 1 x sin 1 x tan 1 x exp(x) sqrt(x) log(x) log10(x) cos(x) sin(x) tan(x) acos(x) asin(x) atan(x) NOTE Trigonometric functions in MATLAB use radian measure

Some Commonly Used Mathematical Functions 11 >> x = [5,7,15] ; >> y = sqrt(x) ; y = 2.2361 2.6358 3.8730 >> ceil(y) ans = 3,3,4 >> fix(y) ans = 2,2,3 >> floor(y) ans = 2,2,3 >> round(y) ans = 2,3,4 >> sign(y) Ans = 1 1 1

Numeric Data Types in Matlab Supported types Integers Signed Unsigned Both available in 8, 16, 32, and 64 bits Floating point Single precision Double precision 12 By default, MATLAB stores all numeric values as double-precision floating point

Converting Data Types Functions that can be used for data conversion and generating arrays of specified type int8, uint8 int16, uint16 int32, uint32 int64, uint64 float double Example >> x = 1.34 ; >> class(x) ans = double >> uint8(x) ans = 1 >> class(ans) ans = uint8 13

Arrays and Vectors MATLAB has the capability of handling collections of numbers (other data types) called arrays. Array manipulation in MATLAB is much simpler when compared to other programming languages (C = A + B is done without looping) This makes MATLAB the choice for many engineering application that require processing of data sets. 14

Creating Vectors in MATLAB 15 1. To create a row vector, separate the elements by commas or spaces. For example, >> p = [3,7,9] p = 3 7 9 2. You can create a column vector by using the transpose notation ('). >> p = [3,7,9]' p = 3 7 9 3. You can also create a column vector by separating the elements by semicolons. For example >> g = [3;7;9]

Creating Vectors in MATLAB 4. You can create larger vectors by appending one vector to another. For example, to create the row vector u whose first three columns contain the values of r = [2,4,20]and whose fourth, fifth, and sixth columns contain the values of w = [9,- 6,3], you type u = [r,w]. The result is the vector u = [2,4,20,9,- 6,3]. 16 NOTE In order to append vectors they should be either row vectors or column vectors. Otherwise, transposition is required before appending. Example >> u = [1,3,4] ; >> r = [6;8;9] ; >> z = [u,r ] z = [1,3,4,6,8,9]

Creating Vectors in MATLAB 17 5. The colon operator (:) easily generates a large vector of regularly spaced elements. Syntax: x = [m:q:n] to create a vector x of values with a spacing q. The first value is m. The last value is n if m n is an integer multiple of q. If not, the last value is less than n. Number of elements = ((n-m)/q )+ 1 Example: typing x = [0:2:8]creates the vector x = [0,2,4,6,8], whereas typing x = [0:2:7]creates the vector x = [0,2,4,6]. Default increment: If the increment q is omitted, it is presumed to be 1. Thus typing y = [-3:2]produces the vector y = [-3,-2,-1,0,1,2].

Creating Matrices in MATLAB 1.For small matrices, type the elements such that Elements in the same row are separated by commas or spaces Rows are separated by semicolons Example >>A = [2,4,10;16,3,7]; Creates the matrix 18

Creating Matrices in MATLAB 19

Addressing Array and Vector Elements Row =1, column = 1 To access a single element use Matrix A(row,col) Vectors v(element position) or Row vectors v (1,col) Column vectors v(row,1) Row =2, column = 3 20

Addressing Array and Vector Elements To access a group of elements, rows, columns, or subarrays of arrays use the colon symbol Examples 21

Some Array Functions Function Description 22

Element-by-Element Operations scalar-array operations Addition B = A + 4 Subtraction B = A 4 Multiplication B = A * 4 Division B = A / 4 The operation is repeated for each element in the array separately. Example 23

Element-by-Element Array-array operations Operations The mathematical operation is repeated between corresponding elements in the arrays Arrays should be of equal dimensions Example 24 Note Subtraction is performed in similar way

Element-by-Element Array-array operations Operations For multiplication (division) use.* (./) to multiply (divide) corresponding elements of the two arrays Example 25 Note Division is performed in similar way

Element-by-Element Operations 26

Element-by-Element Array-array operations Operations For exponentiation, use.^ to raise each element in the array to specified base Example 27

Matrix Operations We have discussed addition and subtraction earlier Multiplication 28

Matrix Operations 29 Matrix division is more challenging topic than matrix multiplication. Matrix division uses both right and left division operators, / and \, for various applications One application is solving linear algebraic equations 6x+ 12y+ 4z= 70 7x 2y+ 3z= 5 2x+ 8y 9z= 64 >> A = [6,12,4;7,-2,3;2,8,-9]; >> B = [70;5;64]; >> Solution = A\B Solution = 3 5-2 The solution is x= 3, y= 5,and z= 2.

Matrix Operations Solving the previous set of linear equations can be done by matrix inversion. >> A = [6,12,4;7,-2,3;2,8,-9]; >> B = [70;5;64]; >> solution = inv(a) * B solution = 3.0000 5.0000-2.0000 30

Special Matrices Identity matrix I eye(n), eye(m,n), eye(m,n) All-ones matrix ones(n), ones(m,n), ones (size(a)) All-zeros matrix zeros(n), zeros(m,n), zeros(size(a)) 31

32 Script Files Up to this point, we have used MATLAB in the interactive mode (commands are entered in the Command window). The interactive mode is desirable when we have few commands. For larger problems we usually use a Script file. Basically, the script file contains the same MATLAB commands that we type on the command prompt (we don t have to retype everything if we want to execute/change the commands again.

Script Files - Creation Use the MATLAB editor/debugger to create your script file. Available from File>New>M-file or by clicking the new M-file shortcut. Enter your commands as desired Use ; to suppress the result of commands % to insert comments; inline or full-line comments Script files are saved in MATLAB with.m extension. Run your script file by typing filename.m on the command prompt or click on the run shortcut in the editor. 33

Script Files - Example Problem: The speed v of a falling object dropped with no initial velocity is given as a function of time t by v= gt. Plot v as a function of t for 0 t tf, where tf is the final time entered by the user. 34

Script Files - Example % Comments section % Program falling speed.m: % Plots speed of a falling object. % Created on March 1, 2004 by W. Palm % % Input Variable: % tf= final time (in seconds) % % Output Variables: % t = array of times at which speed is % computed (in seconds) % v = array of speeds (meters/second) 35

Script Files - Example 36 % Parameter Value: g = 9.81; % Acceleration in SI units % Input section: tf = input( Enter final time in seconds: ); % Calculation section: dt= tf/500; % Create an array of 501 time values. t = [0:dt:tf]; % Compute speed values. v = g*t; % Output section: Plot(t,v),xlabel( t(s) ),ylabel( vm/s) )

Notes on Script File Names 1. The name of a script file must begin with a letter, and may include digits and the underscore character, up to 31 characters. 2. Do not give a script file the same name as a variable. 3. Do not give a script file the same name as a MATLAB command or function. You can check to see if a command, function or file name already exists by using the exist command. 37

Some Input/output Commands 38 Command disp(a) disp( text ) x = input( text ) x = input( text, s ) Description Displays the contents, but not the name, of the array A. Displays the text string enclosed within quotes. Displays the text in quotes, waits for user input from the keyboard, and stores the value in x. Displays the text in quotes, waits for user input from the keyboard, and stores the input as a string in

39 User-defined Functions Another type of m-files. It is simply a script file that implements some operation that is not available in MATLAB. It uses MATLAB commands and accepts user arguments. To define your function, begin the script file with function [output variables] = name(input variables) Note: that the output variables are enclosed in square brackets. the input variables must be enclosed with parentheses. The function name should be the same as the file name in which it is saved (with the.m extension).

40 User-defined Functions Example function z = fun(x,y) u = 3*x; z = u + 6*y.^2; Example Call this function with its output argument: >> z = fun(3,7) z = 303 The function uses x = 3 and y = 7 to compute z. Note the use of a semicolon at the end of the lines to prevents the values of u and z from being displayed. the use of the array exponentiation operator (.^). This enables the function to accept y as an array.

Example of Function Definition Lines 1. One input, one output: function names in red letters function [area_square] = square(side) square.m 2. Brackets are optional for one input, one output: function area_square = square(side) square.m 3. Three inputs, one output: function [volume_box] = box(height,width,length) box.m 4. One input, two outputs: function [area_circle,circumf] = circle(radius) circle.m 5. No named output: function sqplot(side) sqplot.m 41

Relational Operators Six operators that are used for comparison of variables (scalars or arrays) or expressions They have equal precedence (evaluated from left to right) 42

43 Logical Operators

44 Logical Operators

The Find Function find(x) computes an array containing the indices of the nonzero elements of the numeric array x. Example >> x = [-2, 0, 4]; >> y = find(x) Y = 1 3 The resulting array y = [1, 3] indicates that the first and third elements of x are nonzero. [u,v,w] = find(a) Computes the arrays u and v containing the row and column indices of the nonzero elements of the array A and computes the array w containing the values of the nonzero elements. The array w may be omitted. 45

The find Function When the find function is used with arrays, the return value is the linear indices of the nonzero elements. With linear indices, we can refer to array elements with a single value A(k), where k is the element location if the columns of the array are appended to each other. Example 2 1 0 A = 5 6 7 1 2 3 A(2) is equivalent to A(2,1) which is 5 A(5) is equivalent to A(2,2) which is 6 46

The Find Function With logical operators The expression inside the function is evaluated first, then the search for nonzero elements is performed Consider the session >> x = [5, -3, 0, 0, 8]; y = [2, 4, 0, 5, 7]; >> z = find(x&y) z = 1 2 5 Note that the find function returns the indices, and not the values. To extract the values, use array indexing y = x(z) 47

Conditional Statements The if statement s basic form is if logical expression end statements Every if statement must have an accompanying end statement. The end statement marks the end of the statements that are to be executed if the logical expression is true. 48

Conditional Statements The else statement The basic structure for the use of the else statement is if logical expression statements group 1 else statement group 2 end 49

For Loops. Loops Used to repeat a set of statements for specific number of times. 50 The loop variable k is initially assigned the value 5, and x is calculated from x = k^2. Each successive pass through the loop increments k by 10 and calculates x until k exceeds 35. Thus k takes on the values 5, 15, 25, and 35, and x takes on the values 25, 225, 625, and 1225. The program then continues to execute any statements following the end statement.

Note the following rules when using for loops with the loop variable expression k = m:s:n 51 The step value s may be negative. Example: k = 10:-2:4 produces k = 10, 8, 6, 4. If s is omitted, the step value defaults to 1. If s is positive, the loop will not be executed if m is greater than n. If s is negative, the loop will not be executed if m is less than n. If m equals n, the loop will be executed only once. If the step value s is not an integer, round-off errors can cause the loop to execute a different number of passes than intended.

52 Loops The While Statement The while loop is used when the looping process terminates because a specified condition is satisfied, and thus the number of passes is not known in advance. The structure of a while loop while logical expression statements end For the while loop to function properly, the following two conditions must occur: 1.The loop variable must have a value before the while statement is executed. 2. The loop variable must be changed somehow by the statements.

Loops While loop A simple example of a while loop is x = 5; while x < 25 disp(x) x = 2*x -1; end The results displayed by the disp statement are 5, 9, and 17. 53

The Switch Structure The switch structure provides an alternative to using the if, elseif, and else commands. Anything programmed using switch can also be programmed using if structures. However, for some applications the switch structure is more readable than code using the if structure. 54

The Switch Statement 55 switch input expression case value1 statement group 1 case value2 statement group 2... otherwise statement group n end

Some Image Processing imread(path) Functions Reads an image from specified path imshow(imagearray) Shows an image defined by the array imagearray on a figure window Im2double(imgArray) 56 Converts the image type to double. Range of values [0,1] imwrite(imagearray,filename,fmt) Write/saves an image specified by array imagearray into the file specified by filename with the format fmt mean2(imagearray) Computes the average of an image specified in imagearray std2(imagearray) Computes the standard deviation of an image specified in imagearray

Some Image Processing Functions - Example 57 close all % close all figure windows clear all % clears all variables clc % clears the command window % read an image x = imread('images\boat.gif') ; % show original image figure imshow(x) title('original Image') % compute the negative of the image y = 255 - x ; % show negative image figure imshow(y) title('image Negative ) % set all pixels with intensity greater than 150 to 255 ind = find(x > 150); z = x ; z(ind) = 255 ; % show thresholded image figure imshow(z) title('thresholded Image') % save the processed images imwrite(y, negativeimage.gif','gif') imwrite(z, thresholdedimage.jpg, jpg )

Some Image Processing Functions - Example 58