Lecture 1: Introduction to Matlab Programming

Similar documents
Brief Introduction to Vision and Images

Matlab for CS6320 Beginners

CS/NEUR125 Brains, Minds, and Machines. Due: Wednesday, February 8

Digital Image processing Lab

EGR 111 Image Processing

Image processing in MATLAB. Linguaggio Programmazione Matlab-Simulink (2017/2018)

MATLAB Image Processing Toolbox

Lab 1. Basic Image Processing Algorithms Fall 2017

Computer Vision & Digital Image Processing

INTRODUCTION TO MATLAB by. Introduction to Matlab

5.1 Image Files and Formats

Introduction to Simulink Assignment Companion Document

MATLAB 6.5 Image Processing Toolbox Tutorial

Plotting. Aaron S. Donahue. Department of Civil and Environmental Engineering and Earth Sciences University of Notre Dame January 28, 2013 CE20140

MATLAB 2-D Plotting. Matlab has many useful plotting options available! We ll review some of them today.

Week 2: Plotting in Matlab APPM 2460

Experiment 1 Introduction to MATLAB and Simulink

DSP First Lab 06: Digital Images: A/D and D/A

L2. Image processing in MATLAB

THE HONG KONG POLYTECHNIC UNIVERSITY Department of Electronic and Information Engineering. EIE2106 Signal and System Analysis Lab 2 Fourier series

Lab P-8: Digital Images: A/D and D/A

Two-dimensional Plots

Computer Programming ECIV 2303 Chapter 5 Two-Dimensional Plots Instructor: Dr. Talal Skaik Islamic University of Gaza Faculty of Engineering

17. Symmetries. Thus, the example above corresponds to the matrix: We shall now look at how permutations relate to trees.

MatLab for biologists

Lecture 3: Linear Filters

CSCD 409 Scientific Programming. Module 6: Plotting (Chpt 5)

SIGNALS AND SYSTEMS: 3C1 LABORATORY 1. 1 Dr. David Corrigan Electronic and Electrical Engineering Dept.

The 21 st Century Wireless Classroom Network for AP Calculus

Play with image files 2-dimensional array matrix

Chapter 5 Advanced Plotting

Plots Publication Format Figures Multiple. 2D Plots. K. Cooper 1. 1 Department of Mathematics. Washington State University.

EELE 5110 Digital Image Processing Lab 02: Image Processing with MATLAB

Princeton ELE 201, Spring 2014 Laboratory No. 2 Shazam

Introduction to R Software Prof. Shalabh Department of Mathematics and Statistics Indian Institute of Technology, Kanpur

Index of Command Functions

6.098/6.882 Computational Photography 1. Problem Set 1. Assigned: Feb 9, 2006 Due: Feb 23, 2006

A PROPOSED ALGORITHM FOR DIGITAL WATERMARKING

Previous Lecture: Today s Lecture: Announcements: 2-d array examples. Working with images

Diploma in Photoshop

Universal Scale 4.0 Instruction Manual

Problem Set 1 (Solutions are due Mon )

AutoCAD 2D. Table of Contents. Lesson 1 Getting Started

ECE411 - Laboratory Exercise #1

Contents. 1 Matlab basics How to start/exit Matlab Changing directory Matlab help... 2

ImagesPlus Basic Interface Operation

Making 2D Plots in Matlab

INTRODUCTION TO IMAGE PROCESSING

EE/GP140-The Earth From Space- Winter 2008 Handout #16 Lab Exercise #3

EEL 4350 Principles of Communication Project 2 Due Tuesday, February 10 at the Beginning of Class

IT154 Midterm Study Guide

ISET Selecting a Color Conversion Matrix

Getting Started With The MATLAB Image Processing Toolbox

ECE 619: Computer Vision Lab 1: Basics of Image Processing (Using Matlab image processing toolbox Issued Thursday 1/10 Due 1/24)

Worksheet 5. Matlab Graphics

MATLAB - Lecture # 5

GE U111 HTT&TL, Lab 1: The Speed of Sound in Air, Acoustic Distance Measurement & Basic Concepts in MATLAB

Installation. Binary images. EE 454 Image Processing Project. In this section you will learn

Problem Set 3. Assigned: March 9, 2006 Due: March 23, (Optional) Multiple-Exposure HDR Images

Previous Lecture: Today s Lecture: Announcements: 2-d array examples. Image processing

Introduction to the Graphing Calculator for the TI-86

UNIVERSITY OF UTAH ELECTRICAL AND COMPUTER ENGINEERING DEPARTMENT

Digital Imaging - Photoshop

Objectives. Materials

Engineering Department Professionalism: Graphing Standard

MATLAB: SIGNAL PROCESSING

Excel Tool: Plots of Data Sets

Color and More. Color basics

EP375 Computational Physics

Introduction. EN Raster Graphics 6-1

BRUSHES AND LAYERS We will learn how to use brushes and illustration tools to make a simple composition. Introduction to using layers.

Plotting in MATLAB. Trevor Spiteri

Learning Log Title: CHAPTER 2: ARITHMETIC STRATEGIES AND AREA. Date: Lesson: Chapter 2: Arithmetic Strategies and Area

Drawing Bode Plots (The Last Bode Plot You Will Ever Make) Charles Nippert

DFT: Discrete Fourier Transform & Linear Signal Processing

Contents. An introduction to MATLAB for new and advanced users

Lesson 15: Graphics. Introducing Computer Graphics. Computer Programming is Fun! Pixels. Coordinates

COMPUTING CURRICULUM TOOLKIT

Midterm is on Thursday!

Calibration. Click Process Images in the top right, then select the color tab on the bottom right and click the Color Threshold icon.

Do You See What I See?

BacklightFly Manual.

Transform. Processed original image. Processed transformed image. Inverse transform. Figure 2.1: Schema for transform processing

Using Curves and Histograms

MATHEMATICAL FUNCTIONS AND GRAPHS

14 - Dimensioning. Dimension Styles & settings. Arrows tab.

Remote Sensing 4113 Lab 08: Filtering and Principal Components Mar. 28, 2018

Chapter 0 Getting Started on the TI-83 or TI-84 Family of Graphing Calculators

(ans: Five rows require a 3-bit code and ten columns a 4-bit code. Hence, each key has a 7 bit address.

VARVE MEASUREMENT AND ANALYSIS PROGRAMS OPERATION INSTRUCTIONS. USING THE COUPLET MEASUREMENT UTILITY (Varve300.itm)

Lesson 6 2D Sketch Panel Tools

Working with Photos. Lesson 7 / Draft 20 Sept 2003

All Creative Suite Design documents are saved in the same way. Click the Save or Save As (if saving for the first time) command on the File menu to

Vector VS Pixels Introduction to Adobe Photoshop

Apple Photos Quick Start Guide

Exercise NMCGJ: Image Processing

Inserting and Creating ImagesChapter1:

Mech 296: Vision for Robotic Applications. Vision for Robotic Applications

Class #16: Experiment Matlab and Data Analysis

Chapter 5 Advanced Plotting and Model Building

Transcription:

What is Matlab? Lecture 1: Introduction to Matlab Programming Math 490 Prof. Todd Wittman The Citadel Matlab stands for. Matlab is a programming language optimized for linear algebra operations. It is very useful for numerical computation and is commonly used by mathematicians and engineers in academia and industry. Basic Arithmetic If we type a calculation, when we press ENTER the result appears as ans. 2+3 ans = 5 Pressing the up arrow repeats the last input. In addition to basic + - * / there are basic mathematical functions exp(2) sin(pi) asin(2) There may be round-off errors. Watch out for the values Inf and NaN. If you see these values, then you probably. Variables To assign a value to a variable, just type it. We don't need to declare variables first: x=2 Matlab is weakly typed, which means the variable type is flexible. x=2 x=2.3 x=2+4i x='hello' To see what variables are available, look in the Workspace window or type: who To delete a variable x: clear x If you type just clear, all variables will be deleted. Vectors We enclose vector values in square brackets. v = [2 3 4 5 6] We can look up a value at a position: v(2) The colon operator takes on a range of values v = 2:6 More generally we set start:step: (default step=1) Ex Make a vector of all multiples of 3 less than 1000. w = : : What is the last entry in w? Apping Vectors We can app one vector onto another by enclosing them in brackets, separated by commas. v = [1:5, 10, 2:2:16] This trick also works for strings. s = [ pokemon, rule! ] This is particularly useful when we want to combine strings and numbers. We can convert a number to a string using the command num2str. (Or go the other way with str2num.) disp(['the value of x is ', num2str(x)]) 1

Matrices To make a 2D matrix, the semi-colon skips to the next row: A = [2 3 4; 5 6 7] We look up values by row,column: A(2,3) = 7; You can look up a submatrix with the colon: A(1:2,2:3) Using just a colon gets all possible values: A(:,2:3) Special matrices rand(10,20) eye(3) zeros(4,5) ones(3,2) As matrices get large, you can suppress output with a semi-colon at the. R = rand(20,20); Matrix Operations Matrix multiplication: A*B A^3 Component-wise operations: A.*B Inverse: inv(a) Transpose: A' Look up matrix size: size(a) Eignenvalues: [v,d] = eig(a); Linear solver Ax=b: x = linsolve(a,b); Vectorize a matrix: A(:) Change matrix size: reshape(a,[r,c]); A.^3 Linear Algebra Pop Quiz Basic Flow Control Suppose we make a matrix: A=[1 2; 3 4]; Write what each command below does. A'= A(:) = A^2 = A.^2 = while i > 0 for i = 1:10 if x >0 elseif x<0 else An Odd Example Basic Plotting The function mod(a,b) tells the remainder after a is divided by b. So a is multiple of b if mod(a,b)=. for i = 1:100 if mod(i,2) == 0 disp([num2str(i), ' is even.']); else disp([num2str(i), ' is odd.']); The plot function takes two vectors as input. The first vector goes on the horizontal axis (x) and the second on the vertical (y). Ex Plot a sine wave on 0,2. x=0:0.1:2*pi; y=sin(x); plot(x,y,'r') axis([0,2*pi,-1,1]) title('a sine wave') You can suprress the axis numbers with: axis off Note the axis command sets the x and y bounds: axis( [ xmin, xmax, ymin, ymax ] ) You can reset the axis and tick marks manually too. You can (and should) add text to the plot: title xlabel ylabel gtext leg 2

Label Label Label I will deduct points if you do not label your plot axes or title your images. Plotting on Common Axis The hold command tell Matlab to plot things on top of each other, rather than erasing the previous picture. hold on forces all subsequent plots to appear on top of the last plot. hold off releases the plot, so any new plots will erase the current picture. 1 0.8 x=0:0.01:2*pi; 0.6 0.4 plot(x,sin(x),'r'); 0.2 0 hold on; -0.2-0.4 plot(x,cos(x),'b'); -0.6-0.8 hold off -1 0 1 2 3 4 5 6 7 Subplots The subplot command divides the figure into windows. subplot(totalnumrows, TotalNumCols, index) The index goes from left to right, top to bottom (raster order). Which box would subplot(2,3,4) get? Subplots x=0:0.1:2*pi; subplot(1,2,1); plot(x,sin(x)); subplot(1,2,2); plot(x,cos(x)); Pro Tip: If the numbers are all single digits, we can omit the commas: subplot(234) x=0:0.1:2*pi; subplot(2,1,1); plot(x,sin(x)); subplot(2,1,2); plot(x,cos(x)); Subplot Example Subplot Example Ex Plot the graphs of sin ( ) on, for N=1 to 10. x = -pi:0.1:pi; for i = subplot(,, ); plot( title( 3

Navigation You can change directories by clicking the little folder icon at the top. Check current position: pwd Print all files in the current folder: ls Saving & Loading Data You can save your current variables to a Matlab save file (.mat file). save my_data x y z You will see the file my_data.mat appear in the current folder. You can quit Matlab, come back a couple days later, and load the variables x,y,z to the workspace. load my_data Reading & Writing Images Load images into a matrix with imread. A = imread('mypic.jpg'); Write a matrix to an image with imwrite. You need to specify the image format. I like to use bitmaps to avoid compression artifacts. imwrite(a, 'mypic.bmp', 'bmp'); Grayscale Images A grayscale image is given by a 2D matrix with the low value being black, the high value being white, and everything in between denoting a shade of gray. Typically, optical images are 8-bit images which take on integer values in the range [0,255]. (0=black, 255=white) The top left corner of the image is position (1,1). Note Matlab records matrix position as (row,col), so it's (y,x) with the y values inverted. A(1,1)=255; A(1,2)=0; A(2,1)=100; A(2,2)=200; Displaying Images imagesc vs. imshow You can display a matrix with the command imagesc. Matlab defaults to an annoying red-blue "jet" colormap. So we need to tell Matlab to use a grayscale display by typing: colormap gray Often we prefer not to display the axis numbers on images: axis off imagesc(a); imagesc(a); imagesc(a); colormap gray; colormap gray; axis off; The imagesc command fills the window with the image, ignoring the aspect ratio. It draws grayscale images from min=black to max=white. If you want to see how the image would appear like in a web browser with proper aspect ratio and in 8-bit format, use the imshow command. A(1,1)=10; A(1,2)=6; A(2,1)=8; A(2,2)=11; A(3,1)=7; A(3,1)=9; 4

imagesc vs. imshow Data Format The difference between imagesc and imshow is most obvious when the length and width of the image are very different. Images typically come in 8-bit uint8 format. But we can't do math on the images in this format. So we cast to double before we do our arithmetic tricks. A = double(a); Then when we're done, we cast back to 8-bit image format. Some Matlab functions require 8-bit images as input, others prefer double images. Image Arithmetic To brighten a grayscale image A by 60%, we multiply all values by 1.6. A = 1.6 * A; But multiplying an integer by 1.6 does not necessarily give an integer in the range [0,255]. To preserve image formats, we need to cast to double and then back to integer 8-bit. A = double(a); A = 1.6 * A; To see the effect of brightening an image, you really should use the imshow command, not imagesc. (Why?) Writing Scripts A Matlab script is a set of commands that you can save as.m file. Select Script from the New dropdown menu. Ex Display a 8x8 chessboard where each square is 10x10 pixels. Writing Functions Chessboard Function We can create user-defined functions that Matlab can call. We call these functions or m-files. The first line is: function [out1, out2] = function_name (in1, in2) Comments start with a % sign. Matlab will ignore these lines, but they are helpful for people who read your code later. Matlab highlights comment lines in green. Ex Write a function that returns the image of a chessboard. function [ A ] = chessboard ( N ) % Return image of NxN chessboard. % Each square on the chessboard is 10x10 pixels. for i=1:n if mod(i,2)==0 color=0; else color=255; for j=1:n A(1+10*(i-1):10*i, 1+10*(j-1):10*j)=color; color = 255-color; 5

Binary Images A binary image is black or white, no shades of gray. A binary image typically has values of just 0 (black) or 1 (white). Binary images are useful for detection tasks, e.g. identify if each pixel belongs to a cat. These types of images are often referred to as a mask. Binary Images We can mask out part of an image by doing component-wise multiplication by a binary image. A = imread('cat.jpg'); A = double(a); D = zeros(size(b)); D(120:160,50:250)=1; subplot(131); imagesc(a); subplot(132); imagesc(d); subplot(133); imagesc(d.*a); Color Images A standard color image has 3 channels indicating the intensity of Red, Green, and Blue light (RGB). A color image is a 3D matrix, with the 3rd dimension representing color. Think of a color image as being a stack of 3 grayscale images. A=imread('ash.png'); size(a) ans = 708 1129 3 Color Images We can access an individual color channel by the 3rd dimension. A = imread('ash.png'); subplot(141); imshow(a); title('original'); subplot(142); imshow(a(:,:,1)); title('red'); subplot(143); imshow(a(:,:,2)); title('green'); subplot(144); imshow(a(:,:,3)); title('blue'); Color Images Each pixel in a color image is a 3D vector. Black = (0,0,0) White = (255,255,255) Red = (255,0,0) Green = (0,255,0) Blue = (0,0,255) The color of a pixel is determined by the mixture of the RGB values. Color Image Example B = Start with a red background. B(1:3,1:5,1)= ; B(1:3,1:5,2)= ; B(1:3,1:5,3)= ; Now make the white pixel. B(1,2,1)= ; B(1,2,2)= ; B(1,2,3)= ; Finally make the purple pixel. B(2,4,1)= ; B(2,4,2)= ; B(2,4,3)= ; 6

Color Image Example 2 Ex Make the flag of Japan. Color Image Example 2 h = ; % Height of flag. w = round(3*h/2); % Width of flag. d = round(3/5 * h); % Diameter of circle A(1:h,1:w,1:3) = ; %Start with white background. for i = 1:h for j = 1:w if A(i,j,2)=0; A(i,j,3)=0; imshow(a); Color Image Example 2 Processing Color Images If you look closely at the circle we produced, you may see the edges are not smooth. This phenomenon of having "blocky" or "staircased" edges is called. How can we remove it? In this course, we mostly deal with how to process grayscale images. Suppose you have a Matlab function that processes a grayscale image. To process a color image, you just need to run your function 3 times. for i = 1:3 New_A(:,:,i) = MY_FUNCTION ( A(:,:,i) ); You can turn a 3-channel color image into 1-channel grayscale image using rgb2gray. Matrix Operations In Matlab, we want to avoid loops and make use of matrix operations to make it run faster. Ex Write a function that returns the average of the color bands. Note: This is a crude way to turn a color image into grayscale. The Matlab command rgb2gray actually does a weighted average. Averaging 3 Bands Bad Answer function [A] = average(b) B = double(b); [m,n,k] = size(b); for i=1:m for j=1:n A(i,j) = (B(i,j,1)+B(i,j,2)+B(i,j,3)) / 3; Better Answer function [A] = average(b) B = double(b); A = (B(:,:,1)+B(:,:,2)+B(:,:,3)) / 3; Best Answer function [A] = average(b) B = double(b); A = mean(b,3); 7