Top Banner
13/11/2006 13/11/2006 1 1 Matlab in Signal Matlab in Signal Processing: Introduction Processing: Introduction Prof. Mohamed Prof. Mohamed Waleed Waleed Fakhr Fakhr [email protected] [email protected] Electrical and Electronics Engineering Dept. Electrical and Electronics Engineering Dept. University of Bahrain University of Bahrain November 2006 November 2006
35

Matlab in signal processing

Apr 16, 2015

Download

Documents

mail2poongs

Matlab in signal processing prof waleed
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 in signal processing

13/11/200613/11/2006 11

Matlab in Signal Matlab in Signal Processing: IntroductionProcessing: Introduction

Prof. Mohamed Prof. Mohamed WaleedWaleed [email protected]@eng.uob.bh

Electrical and Electronics Engineering Dept.Electrical and Electronics Engineering Dept.University of BahrainUniversity of Bahrain

November 2006November 2006

Page 2: Matlab in signal processing

13/11/200613/11/2006 22

OutlineOutline1. One1. One--dimensional signal processingdimensional signal processing(generation and analysis of 1(generation and analysis of 1--dimensional signals, dimensional signals, sptoolsptool, ,

fdatoolfdatool, , dsplibdsplib--simulinksimulink blocksetblockset, filtering), filtering)2. Image processing2. Image processing(generation, read(generation, read--write, and conversion of images, image write, and conversion of images, image

transform).transform).

All Matlab programs in this tutorial are available on the All Matlab programs in this tutorial are available on the department site.department site.

Page 3: Matlab in signal processing

13/11/200613/11/2006 33

Part IPart IOneOne--dimensional Signalsdimensional Signals

Page 4: Matlab in signal processing

13/11/200613/11/2006 44

OneOne--dimensional Signalsdimensional Signals

This introduction sheds some light on Matlab methods to generateThis introduction sheds some light on Matlab methods to generatesignals in timesignals in time--domain (e.g., sine, tri, etc.), as well as dealing with domain (e.g., sine, tri, etc.), as well as dealing with information signals like speech. information signals like speech. FrequencyFrequency--domain analysis of such signals is described, as how to domain analysis of such signals is described, as how to get the magnitude and phase of the spectrum.get the magnitude and phase of the spectrum.The power spectral density and autocorrelation function are alsoThe power spectral density and autocorrelation function are alsoshown.shown.Examples of doing Filtering using Matlab are shown, with the useExamples of doing Filtering using Matlab are shown, with the use of of two powerful GUI tools two powerful GUI tools ““FDAtoolFDAtool”” and and ““sptoolsptool”” which help design which help design and analyze filters, and apply the filters on signals.and analyze filters, and apply the filters on signals.

Page 5: Matlab in signal processing

13/11/200613/11/2006 55

Important Notes Important Notes

We deal with sampled discreteWe deal with sampled discrete--time signals. time signals. For a sampling frequency Fs Hz, the discrete time increment is 1For a sampling frequency Fs Hz, the discrete time increment is 1/Fs. /Fs. For a signal duration of T seconds, the number of samples is For a signal duration of T seconds, the number of samples is N = T*Fs, thus for a 1 second signal we get Fs samples.N = T*Fs, thus for a 1 second signal we get Fs samples.For the discrete spectrum, it spans the range (0 For the discrete spectrum, it spans the range (0 –– Fs) Hz. The Fs) Hz. The usable part is (0 usable part is (0 –– Fs/2) with (N/2+1) samples. The increment Fs/2) with (N/2+1) samples. The increment between discrete spectrum samples is 1/T Hz (Thus the total rangbetween discrete spectrum samples is 1/T Hz (Thus the total range e is N*1/T = Fs. is N*1/T = Fs. Also, we specify a digital filter characteristics in the same usAlso, we specify a digital filter characteristics in the same usable able range (0 range (0 –– Fs/2). Fs/2).

Page 6: Matlab in signal processing

13/11/200613/11/2006 66

11--Simple Signals in time and frequency Simple Signals in time and frequency domainsdomains

In this preliminary example, we show how to generate signals (siIn this preliminary example, we show how to generate signals (sine, tri, ne, tri, rectrect) ) in time domain and how to get their spectrum by the discrete Fouin time domain and how to get their spectrum by the discrete Fourier rier transform (using the FFT).transform (using the FFT).

Page 7: Matlab in signal processing

13/11/200613/11/2006 77

example1.mexample1.mclear;

%here we want to generate a %here we want to generate a sinewavesinewave with duration 0.1sec, samplingwith duration 0.1sec, sampling%frequency 8000 Hz (sample per sec), and fundamental frequency 2%frequency 8000 Hz (sample per sec), and fundamental frequency 200Hz.00Hz.%In this case, %In this case, del_tdel_t=1/8000, and the duration is 800 samples=1/8000, and the duration is 800 samplesFs=8000;for i=1:800

x1(i)=sin(2*pi*(i-1)/8000 * 200);endfor i=1:800

tt(i)=(i-1)/8000; %This is the time increments%This is the time incrementsend

for i=1:800ff(i)=(i-1)/0.1; %This is the frequency increments%This is the frequency increments

end

Page 8: Matlab in signal processing

13/11/200613/11/2006 88

figure(1);subplot(2,1,1), stem(tt(1:200),x1(1:200), ‘.’ );subplot(2,1,2), plot(tt(1:200),x1(1:200));

%Now we get the FFT for the signal x1%Now we get the FFT for the signal x1uu=fft(x1);

figure(2);subplot(2,1,1), plot(ff,real(uu));subplot(2,1,2), plot(ff,imag(uu));%Shows the Fourier transform of the sine wave (only %Shows the Fourier transform of the sine wave (only ImagImag))

Page 9: Matlab in signal processing

13/11/200613/11/2006 99

Generating train of pulses (Tri or Generating train of pulses (Tri or RectRect or anything!)or anything!)

T=0.1; %Signal duration in seconds%Signal duration in secondst=0:1/8000:T; %This is the time increments%This is the time incrementsd = 0 : 1/50 : T; %Repetition every 1/50 for duration of T%Repetition every 1/50 for duration of Twidth=0.02;y1 = pulstran(t,d,'tripuls',width); %t is the time, %t is the time, %d gives the repetition (in this case the period of %d gives the repetition (in this case the period of % 0.02 sec)% 0.02 sec)%and thus we have 5 cycles in the duration (0%and thus we have 5 cycles in the duration (0--0.1) sec.0.1) sec.%width=0.02 is the width of the tri pulse (%width=0.02 is the width of the tri pulse (TauTau).).figure(4);plot(t,y1);ff=0:1/T:8000; %The frequency increments%The frequency incrementsumag=abs(fft(y1)); uphase=angle(fft(y1));figure(5);subplot(2,1,1), plot(ff(1:50),umag(1:50));subplot(2,1,2), plot(ff(1:50),uphase(1:50));

Page 10: Matlab in signal processing

13/11/200613/11/2006 1010

A single pulse (Tri or A single pulse (Tri or RectRect or Gaussian)or Gaussian)%Now we generate a Rectangular pulse (%Now we generate a Rectangular pulse (rectrect))%Use the same t=0:1/8000:T%Use the same t=0:1/8000:T%width=0.02; (In this case the %width=0.02; (In this case the rectrect is defined is defined betweebetwee% % --tau/2 and tau/2)tau/2 and tau/2)

y2=rectpuls(t,width);figure(6);plot(t,y2);

umag2=abs(fft(y2));uphase2=angle(fft(y2));figure(7);subplot(2,1,1), plot(ff(1:50),umag2(1:50));subplot(2,1,2), plot(ff(1:50),uphase2(1:50));

Page 11: Matlab in signal processing

13/11/200613/11/2006 1111

22-- Signal AnalysisSignal Analysis

Example 2: In this example we generate a signal with 2 sineExample 2: In this example we generate a signal with 2 sine--waves waves of 2KHz and 2.5KHz frequencies and duration 0.1sec. Then we add of 2KHz and 2.5KHz frequencies and duration 0.1sec. Then we add WGN to resemble additive noise. WGN to resemble additive noise. We then add a 50Hz interference signal to resemble the power We then add a 50Hz interference signal to resemble the power supply interfering signal.supply interfering signal.We assume sampling frequency is 8000Hz. We assume sampling frequency is 8000Hz. The first part is to generate the signals. Then, we would like tThe first part is to generate the signals. Then, we would like to see o see the the power spectral densitypower spectral density and and autocorrelation functionautocorrelation function of the of the signals using different methods.signals using different methods.

Page 12: Matlab in signal processing

13/11/200613/11/2006 1212

example2.mexample2.mclear;

%here we want to generate 2 %here we want to generate 2 sinewavessinewaves with duration 1sec, sampling frequencywith duration 1sec, sampling frequency%8000 Hz (sample per sec), and fundamental frequencies 2 and 2.5%8000 Hz (sample per sec), and fundamental frequencies 2 and 2.5 KHz.KHz.%In this case, %In this case, del_tdel_t=1/8000, and the duration is 8000 samples=1/8000, and the duration is 8000 samples

Fs=8000;T=1; %Duration in seconds%Duration in secondst=0:1/Fs:1; %The time samples (8000 points)%The time samples (8000 points)

for i=1:8000x1(i)=sin(2*pi*(i-1)/Fs * 2000);

endfor i=1:8000

x2(i)=sin(2*pi*(i-1)/Fs * 2500);end

xx=x1+x2; %we have added the 2 %we have added the 2 sinewavessinewaves

Page 13: Matlab in signal processing

13/11/200613/11/2006 1313

%Generate a random WGN with zero mean, and %Generate a random WGN with zero mean, and st.devst.dev=1=1for i=1:8000for i=1:8000

rr(i)= 1.0*randn;end

std(rr)

%Add the three signals%Add the three signalsy1=xx+rr;

figure(1);subplot(2,1,1), plot(xx), title('The two sine waves without noise'), plottools('on');subplot(2,1,2), plot(y1), title('The two sine waves with noise'), plottools('on');%A nice tool for playing with the plotting is %A nice tool for playing with the plotting is openningopenning the "the "plottoolsplottools""%along with the plot.%along with the plot.

pause(3);sound(xx,8000); %We hear the sound of the two sine waves%We hear the sound of the two sine wavespause(3);sound(y1,8000); %We hear the noise%We hear the noise--corrupted soundcorrupted sound

Page 14: Matlab in signal processing

13/11/200613/11/2006 1414

%The PSD for the pure sine waves without the noise %The PSD for the pure sine waves without the noise %versus the PSD after the noise is added.%versus the PSD after the noise is added.%PSD has many functions in Matlab; some are non%PSD has many functions in Matlab; some are non--parametric parametric

((periodogramperiodogram andand%%pwelchpwelch), and some are parametric (), and some are parametric (pburgpburg, , peigpeig, , pcovpcov, etc.) Here , etc.) Here

we workwe work%with %with pwelchpwelch and you can do help on the rest.and you can do help on the rest.

figure(2);subplot(2,1,1), pwelch(xx,[ ],[ ],[ ],Fs), plottools('on');subplot(2,1,2), pwelch(y1,[ ],[ ],[ ],Fs), plottools('on');

figure(3);subplot(2,1,1), plot(xcorr(xx)), plottools('on');subplot(2,1,2), plot(xcorr(rr)), plottools('on');%This is the Autocorrelation for the %This is the Autocorrelation for the sinewavessinewaves and for the WGN.and for the WGN.

Page 15: Matlab in signal processing

13/11/200613/11/2006 1515

%Now we add a 50Hz %Now we add a 50Hz sinewavesinewave with a high amplitude:with a high amplitude:for i=1:8000

x3(i)=3.0*sin(2*pi*(i-1)/8000 * 50);end

z1=y1+x3;

pause(3);sound(xx,8000); %We hear the sound of the two sine waves%We hear the sound of the two sine wavespause(3);sound(z1,8000); %We hear the distorted sound%We hear the distorted sound

figure(4);subplot(2,1,1), pwelch(xx,[ ],[ ],[ ],Fs), plottools('on');subplot(2,1,2), pwelch(z1,[ ],[ ],[ ],Fs), plottools('on');save z1; %here we save the corrupted signal in the disk%here we save the corrupted signal in the disk%so that, using filtering techniques, we try to get back the nic%so that, using filtering techniques, we try to get back the nicee%%sinewavessinewaves..

Page 16: Matlab in signal processing

13/11/200613/11/2006 1616

SimulinkSimulink: Using DSP blocks: Using DSP blocks

The signal processing The signal processing SimulinkSimulink--based signal processing block set is called based signal processing block set is called by by dsplibdsplib, or just by opening , or just by opening SimulinkSimulink from Matlab.from Matlab. The same previous The same previous example is shown in example is shown in SimulinkSimulink (see (see exsim1.mdlexsim1.mdl) )

Freq

VectorScope3

Freq

VectorScope2

Freq

VectorScope1

Time

VectorScope

DSP

Sine Wave1

DSP

Sine Wave

RandomSource

Periodogram

Periodogram2

Periodogram

Periodogram1

Periodogram

Periodogram

RowSum

MatrixSum

Page 17: Matlab in signal processing

13/11/200613/11/2006 1717

SimulinkSimulink stepssteps1.1. Write Write ““dsplibdsplib””2.2. File: New model file, save as File: New model file, save as ““myfilemyfile””3.3. Grab blocks from the open library (Grab blocks from the open library (dsplibdsplib) and connect them together to ) and connect them together to

get the required functionalityget the required functionality4.4. You can do You can do ““library browserlibrary browser”” to see other blocks in the whole to see other blocks in the whole SimulinkSimulink..5.5. To the left the To the left the dsplibdsplib, to the right, , to the right, myfilemyfile with some blocks connected.with some blocks connected.

Signal Processing Blockset 6.1Copyright 1995-2004The MathWorks, Inc.

FFTf(u) F(v)

Transforms

Statistics

SignalProcessing

Sources

SignalProcessing

Sinks

SignalOperations

SignalManagement

Quantizers

PlatformSpecific I/O

A x = b

MathFunctions

Info

Filtering

z +12z -1

Estimation

Demos

Time

VectorScope

DSP

Sine Wave

FDATool

DigitalFilter Design

Page 18: Matlab in signal processing

13/11/200613/11/2006 1818

example3.m: Notch filterexample3.m: Notch filter%This program shows the notch filtering to suppress the 50Hz interferenceclear;Fs=8000;load z1;

%z1 is the signal with 2 sine waves at 2 and 2.5 KHz, with addit%z1 is the signal with 2 sine waves at 2 and 2.5 KHz, with additive WGN andive WGN and%with a 50Hz interference.%with a 50Hz interference.

%We want to design a Notch filter to remove the 50Hz interferenc%We want to design a Notch filter to remove the 50Hz interference.e.%There is a direct way to do that in Matlab using "%There is a direct way to do that in Matlab using "iirnotchiirnotch""

% % IIRNOTCH Second% % IIRNOTCH Second--order IIR notch digital filter design.order IIR notch digital filter design.% % [NUM,DEN] = % % [NUM,DEN] = IIRNOTCH(Wo,BWIIRNOTCH(Wo,BW) designs a second) designs a second--order notch digital filterorder notch digital filter% % with the notch at frequency % % with the notch at frequency WoWo and a bandwidth of BW at the and a bandwidth of BW at the --3 dB level.3 dB level.% % % % WoWo must must statisfystatisfy 0.0 < 0.0 < WoWo < 1.0, with 1.0 corresponding to pi < 1.0, with 1.0 corresponding to pi % % radians/sample.% % radians/sample.% % % % % % The bandwidth BW is related to the Q% % The bandwidth BW is related to the Q--factor of a filter by BW = factor of a filter by BW = WoWo/Q./Q.

Page 19: Matlab in signal processing

13/11/200613/11/2006 1919

% Our Fs/2 is 4000. We want our notch W0 % Our Fs/2 is 4000. We want our notch W0 % at 50Hz which is 50/4000 in normalized Matlab which is 0.0125% at 50Hz which is 50/4000 in normalized Matlab which is 0.0125

%Practical situations we take Q=1, thus BW=Wo/Q and BW=0.0125/1

[bn,an]=iirnotch(0.0125,0.0125/1); %The filter is now designed :))%The filter is now designed :))

%%bnbn is the vector of the numerator coefficients for the filteris the vector of the numerator coefficients for the filter%an is the vector of the denominator coefficients for the filter%an is the vector of the denominator coefficients for the filter

%Now we pass the z1 signal through the filter to suppress the %Now we pass the z1 signal through the filter to suppress the 50Hz.50Hz.

z11=filter(bn,an,z1);

Page 20: Matlab in signal processing

13/11/200613/11/2006 2020

figure(1); %The spectrum before the filtering%The spectrum before the filteringpwelch(z1,[ ],[ ],[ ],Fs);figure(2); %The spectrum after the filtering%The spectrum after the filteringpwelch(z11,[ ],[ ],[ ],Fs);

%Now we have the signal z11 which is still corrupted by the WGN.%Now we have the signal z11 which is still corrupted by the WGN.save z11;

Page 21: Matlab in signal processing

13/11/200613/11/2006 2121

sptoolsptool: A GUI alternative: : A GUI alternative: StepsSteps““sptoolsptool”” is a GUI Matlab tool which handles signals and filters. It is is a GUI Matlab tool which handles signals and filters. It is called simply called simply ““sptoolsptool””. We have a clear session in . We have a clear session in ““clear.sptclear.spt””. .

1.1. sptoolsptool2.2. File: open session: File: open session: clear.sptclear.spt3.3. File: import (we can import signal, filter, spectrum), either frFile: import (we can import signal, filter, spectrum), either from the om the

workspaceworkspace (if it was generated in this session and is still saved in (if it was generated in this session and is still saved in the workspace), or from the the workspace), or from the disk disk ((file.matfile.mat))

4.4. To design a filter: Filters: New (opens a window for design).To design a filter: Filters: New (opens a window for design).5.5. Then apply the filter to the signal, get the new signal, get theThen apply the filter to the signal, get the new signal, get the

spectaspecta for the old and new signals.for the old and new signals.

Page 22: Matlab in signal processing

13/11/200613/11/2006 2222

Notch Filter in Notch Filter in SptoolSptoolThe Notch filter is imported to the The Notch filter is imported to the sptoolsptool: file : file sptool1.sptsptool1.sptLetLet’’s open it and apply the notch filter.s open it and apply the notch filter.We have to import the signal We have to import the signal ““z1z1””, and enter its sampling frequency., and enter its sampling frequency.We also import the notch filter we have designed (Although we coWe also import the notch filter we have designed (Although we could uld have designed the filter using GUI tools as we shall see soon).have designed the filter using GUI tools as we shall see soon).The filter is applied to z1 and we get z11.The filter is applied to z1 and we get z11.We see the spectra for both: spect1 and spect2.We see the spectra for both: spect1 and spect2.

Page 23: Matlab in signal processing

13/11/200613/11/2006 2323

Example (Example (sptoolsptool: sptool2.spt: sptool2.spt): Band): Band--pass filterpass filterWe use the We use the ““sptoolsptool”” directly to design the filter in this case. directly to design the filter in this case. We design a BPF with (Fs1=1600Hz, Fs2=2900Hz)We design a BPF with (Fs1=1600Hz, Fs2=2900Hz)(Fp1=1800Hz, Fp2=2700Hz)(Fp1=1800Hz, Fp2=2700Hz)PassPass--band maximum ripple is 2dB, Stopband maximum ripple is 2dB, Stop--band minimum attenuation is 30dBband minimum attenuation is 30dBSimply we call Simply we call sptoolsptool, and open session , and open session ““sptool2.sptsptool2.spt””..The designed filter is shown below.The designed filter is shown below.

Page 24: Matlab in signal processing

13/11/200613/11/2006 2424

Working with speech signals: example4Working with speech signals: example4clear;%Here we have a speech signal as the information source%Here we have a speech signal as the information source[xsignal,Fs,Nbits]=wavread('s3.wav'); x1=xsignal;dur_samples=length(x1);dur_seconds=dur_samples*1/8000;delta_f=1/dur_seconds;%Now we add a 1000Hz %Now we add a 1000Hz sinewavesinewavefor i=1:dur_samplesx2(i)=5*sin(2*pi*(i-1)/8000 * 1000);endspeech1=x1+x2';save speech1;pause(3);sound(x1);pause(3)sound(speech1,8000);figure(1);subplot(2,1,1), pwelch(x1,[ ],[ ],[ ],Fs), plottools('on');subplot(2,1,2), pwelch(speech1,[ ],[ ],[ ],Fs), plottools('on');;

Page 25: Matlab in signal processing

13/11/200613/11/2006 2525

Removing the interference from the speech signal:Removing the interference from the speech signal:A BSF using A BSF using sptoolsptool

SptoolSptool: sptool3.spt: sptool3.sptWe design a bandWe design a band--stop filter between (950stop filter between (950--1050)Hz to get rid of the 1000Hz 1050)Hz to get rid of the 1000Hz interference.interference.We hear the signal before and after the filteringWe hear the signal before and after the filteringWe see the spectrum before and after the filteringWe see the spectrum before and after the filtering

Page 26: Matlab in signal processing

13/11/200613/11/2006 2626

FDAToolFDATool: Powerful filter design and : Powerful filter design and implementation: implementation: bsf1.fdabsf1.fda

Suppose we want to put the designed BSF in hardware; (DSP Suppose we want to put the designed BSF in hardware; (DSP board, HDL code for ASIC), board, HDL code for ASIC),

1.1. For the already designed filter, get the numerator and For the already designed filter, get the numerator and denominator polynomial coefficients by: denominator polynomial coefficients by: bb1=filt1.tf.num;bb1=filt1.tf.num;and and aa1=filt1.tf.den; aa1=filt1.tf.den;

2.2. Open Open fdatoolfdatool, import filter, put the bb1 and aa1 as variables., import filter, put the bb1 and aa1 as variables.3.3. The filter opens for processing The filter opens for processing ☺☺4.4. In the FileIn the File--options, we can export to options, we can export to simulinksimulink model, or generate model, or generate

an man m--file.file.5.5. In the Targets: we can generate: CIn the Targets: we can generate: C--code for the filter coefficients, code for the filter coefficients,

““HDLHDL”” code, code, ““XILINX coefficientsXILINX coefficients””, and , and ““CodeCode--Composer studio Composer studio file: for DSP boardsfile: for DSP boards”” (however, they are restricted to FIR filters for (however, they are restricted to FIR filters for the time being).the time being).

Page 27: Matlab in signal processing

13/11/200613/11/2006 2727

Part IIPart IIImage ProcessingImage Processing

Page 28: Matlab in signal processing

13/11/200613/11/2006 2828

PreliminariesPreliminariesImages are 2Images are 2--dimensional arrays of pixels (e.g., 32dimensional arrays of pixels (e.g., 32--byby--32).32).If the image is a color image, then it is basically a threeIf the image is a color image, then it is basically a three--layer image (R, G, B). In each layer image (R, G, B). In each one, each pixel may take a discrete intensity value for example one, each pixel may take a discrete intensity value for example between (0between (0--255).255).If the image is gray, then it is one layer, and each pixel may tIf the image is gray, then it is one layer, and each pixel may take a discrete intensity ake a discrete intensity value for example between (0value for example between (0--255).255).If the image is binary, then each pixel takes 0 or 1 values (blaIf the image is binary, then each pixel takes 0 or 1 values (black and white).ck and white).

Here is an example of a 32Here is an example of a 32--byby--32 image in gray and then in color.32 image in gray and then in color.

Page 29: Matlab in signal processing

13/11/200613/11/2006 2929

example1.mexample1.mclear;%synthesized Example%synthesized Examplehh1(1:16,1:16)=uint8(40);hh1(17:32,17:32)=uint8(200);%Now let's write this image once with %Now let's write this image once with graygray and once and once

with with colorcolormap1=colormap('gray');map2=colormap('cool');imwrite(hh1,map1,'testout1.jpg','jpg');imwrite(hh1,map2,'testout2.jpg','jpg');%Now let's read the images and show them:%Now let's read the images and show them:

xh1=imread('testout1.jpg');xh2=imread('testout2.jpg');figure(1);subplot(1,2,1), imshow(xh1);subplot(1,2,2), imshow(xh2);

Page 30: Matlab in signal processing

13/11/200613/11/2006 3030

%Now we can convert the image array values from %Now we can convert the image array values from integers to double,integers to double,

%and add some random noise.%and add some random noise.h1=im2double(hh1);for i=1:32

for j=1:32h1(i,j)=h1(i,j)+rand/6;

endendfigure(2);imshow(h1), colormap('gray');figure(3);imshow(h1), colormap('cool');

Page 31: Matlab in signal processing

13/11/200613/11/2006 3131

example2.mexample2.m%Here we practice reading and writing images. %Here we practice reading and writing images. Converting file formats, and converting color to grayConverting file formats, and converting color to gray

clear;x=imread('ayman.bmp');%convert the file to "jpg" and to '%convert the file to "jpg" and to 'tiftif' formats' formats%(Many other formats are supported).%(Many other formats are supported).imwrite(x,'ayman.jpg','jpg');imwrite(x,'ayman.tif','Tif');info=imfinfo('ayman.jpg');%Transform the image into gray (for many %Transform the image into gray (for many

applications gray is sufficient)applications gray is sufficient)y= rgb2gray(x);

Page 32: Matlab in signal processing

13/11/200613/11/2006 3232

y=im2double(y); %from unsigned integer (0%from unsigned integer (0--255) to 255) to %double (0%double (0--1)1)

%This is %This is neccessaryneccessary for image transforms.for image transforms.figure(1);subplot(2,1,1), imshow(x);subplot(2,1,2), imshow(y);%Discrete Cosine transform "dct2" is the most %Discrete Cosine transform "dct2" is the most

important transform forimportant transform for%images, it is used in JPEG compression.%images, it is used in JPEG compression.ydctydct=dct2(y);=dct2(y);figure, imshow(ydct);

Page 33: Matlab in signal processing

13/11/200613/11/2006 3333

example3.mexample3.m%Here we read a signature image, do edge detection and crop the %Here we read a signature image, do edge detection and crop the

%region of interest in the signature%region of interest in the signatureclear;ss1=imread('sig.jpg');ss2= rgb2gray(ss1);

ss3=im2double(ss2);%Edge detection using Canny method%Edge detection using Canny method

edg1=edge(ss3,'canny');%Now we get the boundaries of the edge then crop the image to %Now we get the boundaries of the edge then crop the image to

%fit the signature%fit the signaturex1=sum(edg1);y1=sum(edg1');z1=find(x1); q1=minmax(z1);z2=find(y1); q2=minmax(z2);xx1=q1(1); xx2=q1(2)-q1(1);oo1=q2(1); oo2=q2(2)-q2(1);

Page 34: Matlab in signal processing

13/11/200613/11/2006 3434

uu=imcrop(ss3, [xx1 oo1 xx2 oo2]);%Then we resize the cropped image to be same size %Then we resize the cropped image to be same size %as before%as beforett=size(ss3);kk=imresize(uu,[tt(1) tt(2)]);

figure(1);subplot(1,3,1), imshow(ss3);subplot(1,3,2), imshow(uu);subplot(1,3,3), imshow(kk);

Page 35: Matlab in signal processing

13/11/200613/11/2006 3535

Image and Video Processing Image and Video Processing BlocksetBlockset

The Video and Image Processing The Video and Image Processing BlocksetBlockset is a tool used for the is a tool used for the rapid design, prototyping, graphical simulation, and efficient crapid design, prototyping, graphical simulation, and efficient code ode generation of video processing algorithms. The Video and Image generation of video processing algorithms. The Video and Image Processing Processing BlocksetBlockset blocks can import streaming video into the blocks can import streaming video into the SimulinkSimulink environment and perform twoenvironment and perform two--dimensional filtering, dimensional filtering, geometric and frequency transforms, block processing, motion geometric and frequency transforms, block processing, motion estimation, edge detection and other signal processing algorithmestimation, edge detection and other signal processing algorithms. s. You can also use the You can also use the blocksetblockset in conjunction with Realin conjunction with Real--Time Time WorkshopWorkshop®® to automatically generate embeddable C code for realto automatically generate embeddable C code for real--time execution.time execution.

The Video and Image Processing The Video and Image Processing BlocksetBlockset blocks support floatingblocks support floating--point, integer, and fixedpoint, integer, and fixed--point data types. To use any data type other point data types. To use any data type other than doublethan double--precision and singleprecision and single--precision floating point, you must precision floating point, you must install install SimulinkSimulink Fixed Point. For more information about this product, Fixed Point. For more information about this product, see the see the SimulinkSimulink Fixed Point documentation.Fixed Point documentation.