Sei sulla pagina 1di 35

Matlab in Signal Processing: Introduction

Prof. Mohamed Waleed Fakhr


mfakhr@eng.uob.bh

Electrical and Electronics Engineering Dept. University of Bahrain November 2006

13/11/2006

Outline
1. One-dimensional signal processing (generation and analysis of 1-dimensional signals, sptool, fdatool, dsplib-simulink blockset, filtering) 2. Image processing (generation, read-write, and conversion of images, image transform). All Matlab programs in this tutorial are available on the department site.

13/11/2006

Part I
One-dimensional Signals

13/11/2006

One-dimensional Signals
This introduction sheds some light on Matlab methods to generate signals in time-domain (e.g., sine, tri, etc.), as well as dealing with information signals like speech. Frequency-domain analysis of such signals is described, as how to get the magnitude and phase of the spectrum. The power spectral density and autocorrelation function are also shown. Examples of doing Filtering using Matlab are shown, with the use of two powerful GUI tools FDAtool and sptool which help design and analyze filters, and apply the filters on signals.

13/11/2006

Important Notes
We deal with sampled discrete-time signals. For a sampling frequency Fs Hz, the discrete time increment is 1/Fs. 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. For the discrete spectrum, it spans the range (0 Fs) Hz. The usable part is (0 Fs/2) with (N/2+1) samples. The increment between discrete spectrum samples is 1/T Hz (Thus the total range is N*1/T = Fs. Also, we specify a digital filter characteristics in the same usable range (0 Fs/2).

13/11/2006

1-Simple Signals in time and frequency domains


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

13/11/2006

example1.m
clear; %here we want to generate a sinewave with duration 0.1sec, sampling %frequency 8000 Hz (sample per sec), and fundamental frequency 200Hz. %In this case, del_t=1/8000, and the duration is 800 samples Fs=8000; for i=1:800 x1(i)=sin(2*pi*(i-1)/8000 * 200); end for i=1:800 tt(i)=(i-1)/8000; %This is the time increments end for i=1:800 ff(i)=(i-1)/0.1; end

%This is the frequency increments

13/11/2006

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 uu=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 Imag)

13/11/2006

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


T=0.1; %Signal duration in seconds t=0:1/8000:T; %This is the time increments d = 0 : 1/50 : T; %Repetition every 1/50 for duration of T width=0.02; y1 = pulstran(t,d,'tripuls',width); %t is the time, %d gives the repetition (in this case the period of % 0.02 sec) %and thus we have 5 cycles in the duration (0-0.1) sec. %width=0.02 is the width of the tri pulse (Tau). figure(4); plot(t,y1); ff=0:1/T:8000; %The frequency increments umag=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));
13/11/2006 9

A single pulse (Tri or Rect or Gaussian) %Now we generate a Rectangular pulse (rect) %Use the same t=0:1/8000:T %width=0.02; (In this case the rect is defined betwee % -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));
13/11/2006 10

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

13/11/2006

11

example2.m
clear; %here we want to generate 2 sinewaves with duration 1sec, sampling frequency %8000 Hz (sample per sec), and fundamental frequencies 2 and 2.5 KHz. %In this case, del_t=1/8000, and the duration is 8000 samples Fs=8000; T=1; %Duration in seconds t=0:1/Fs:1; %The time samples (8000 points) for i=1:8000 x1(i)=sin(2*pi*(i-1)/Fs * 2000); end for i=1:8000 x2(i)=sin(2*pi*(i-1)/Fs * 2500); end xx=x1+x2; %we have added the 2 sinewaves

13/11/2006

12

%Generate a random WGN with zero mean, and st.dev=1 for i=1:8000 rr(i)= 1.0*randn; end std(rr) %Add the three signals y1=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 openning the "plottools" %along with the plot. pause(3); sound(xx,8000); pause(3); sound(y1,8000);

%We hear the sound of the two sine waves %We hear the noise-corrupted sound

13/11/2006

13

%The PSD for the pure sine waves without the noise %versus the PSD after the noise is added. %PSD has many functions in Matlab; some are non-parametric (periodogram and %pwelch), and some are parametric (pburg, peig, pcov, etc.) Here we work %with pwelch 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 sinewaves and for the WGN.

13/11/2006

14

%Now we add a 50Hz sinewave 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); pause(3); sound(z1,8000);

%We hear the sound of the two sine waves %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 %so that, using filtering techniques, we try to get back the nice %sinewaves.

13/11/2006

15

Simulink: Using DSP blocks


The signal processing Simulink-based signal processing block set is called by dsplib, or just by opening Simulink from Matlab. The same previous example is shown in Simulink (see exsim1.mdl)
Periodogram DSP Freq Periodogram1 Sine Wave Row Sum Matrix Sum Time Vector Scope Random Source Periodogram Freq Periodogram DSP Vector Scope1 Vector Scope3

Sine Wave1 Freq Vector Scope2 Periodogram

13/11/2006
Periodogram2

16

Simulink steps
1. 2. 3. 4. 5.

Write dsplib File: New model file, save as myfile Grab blocks from the open library (dsplib) and connect them together to get the required functionality You can do library browser to see other blocks in the whole Simulink. To the left the dsplib, to the right, myfile with some blocks connected.
FFT f(u) F(v) Signal Operations
DSP FDATool

Signal Processing Sources z +1 2z -1

Signal Processing Sinks

Filtering

Transforms

Time

Ax= b

Sine Wave

Digital Filter Design

Vector Scope

Estimation

Statistics

Math Functions

Quantizers

Signal Management

Platform Specific I/O

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

Info

Demos

13/11/2006

17

example3.m: Notch filter


%This program shows the notch filtering to suppress the 50Hz interference clear; Fs=8000; load z1; %z1 is the signal with 2 sine waves at 2 and 2.5 KHz, with additive WGN and %with a 50Hz interference. %We want to design a Notch filter to remove the 50Hz interference. %There is a direct way to do that in Matlab using "iirnotch" % % IIRNOTCH Second-order IIR notch digital filter design. % % [NUM,DEN] = IIRNOTCH(Wo,BW) designs a second-order notch digital filter % % with the notch at frequency Wo and a bandwidth of BW at the -3 dB level. % % Wo must statisfy 0.0 < Wo < 1.0, with 1.0 corresponding to pi % % radians/sample. %% % % The bandwidth BW is related to the Q-factor of a filter by BW = Wo/Q.

13/11/2006

18

% Our Fs/2 is 4000. We want our notch W0 % 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 :)) %bn is the vector of the numerator 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 50Hz. z11=filter(bn,an,z1);

13/11/2006

19

figure(1); %The spectrum before the filtering pwelch(z1,[ ],[ ],[ ],Fs); figure(2); %The spectrum after the filtering pwelch(z11,[ ],[ ],[ ],Fs); %Now we have the signal z11 which is still corrupted by the WGN. save z11;

13/11/2006

20

sptool: A GUI alternative: Steps


1. 2. 3.

4. 5.

sptool is a GUI Matlab tool which handles signals and filters. It is called simply sptool. We have a clear session in clear.spt. sptool File: open session: clear.spt File: import (we can import signal, filter, spectrum), either from the workspace (if it was generated in this session and is still saved in the workspace), or from the disk (file.mat) To design a filter: Filters: New (opens a window for design). Then apply the filter to the signal, get the new signal, get the specta for the old and new signals.

13/11/2006

21

Notch Filter in Sptool


The Notch filter is imported to the sptool: file sptool1.spt Lets open it and apply the notch filter. We have to import the signal z1, and enter its sampling frequency. We also import the notch filter we have designed (Although we could have designed the filter using GUI tools as we shall see soon). The filter is applied to z1 and we get z11. We see the spectra for both: spect1 and spect2.

13/11/2006

22

Example (sptool: sptool2.spt): Band-pass filter


We use the sptool directly to design the filter in this case. We design a BPF with (Fs1=1600Hz, Fs2=2900Hz) (Fp1=1800Hz, Fp2=2700Hz) Pass-band maximum ripple is 2dB, Stop-band minimum attenuation is 30dB Simply we call sptool, and open session sptool2.spt. The designed filter is shown below.

13/11/2006

23

Working with speech signals: example4


clear; %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 sinewave for i=1:dur_samples x2(i)=5*sin(2*pi*(i-1)/8000 * 1000); end speech1=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');; 13/11/2006 24

Removing the interference from the speech signal: A BSF using sptool
Sptool: sptool3.spt We design a band-stop filter between (950-1050)Hz to get rid of the 1000Hz interference. We hear the signal before and after the filtering We see the spectrum before and after the filtering

13/11/2006

25

FDATool: Powerful filter design and implementation: bsf1.fda


1.

2. 3. 4. 5.

Suppose we want to put the designed BSF in hardware; (DSP board, HDL code for ASIC), For the already designed filter, get the numerator and denominator polynomial coefficients by: bb1=filt1.tf.num; and aa1=filt1.tf.den; Open fdatool, import filter, put the bb1 and aa1 as variables. The filter opens for processing In the File-options, we can export to simulink model, or generate an m-file. In the Targets: we can generate: C-code for the filter coefficients, HDL code, XILINX coefficients, and Code-Composer studio file: for DSP boards (however, they are restricted to FIR filters for the time being).

13/11/2006

26

Part II
Image Processing

13/11/2006

27

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

13/11/2006

28

clear; %synthesized Example hh1(1:16,1:16)=uint8(40); hh1(17:32,17:32)=uint8(200); %Now let's write this image once with gray and once with color map1=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: xh1=imread('testout1.jpg'); xh2=imread('testout2.jpg'); figure(1); subplot(1,2,1), imshow(xh1); subplot(1,2,2), imshow(xh2);
13/11/2006 29

example1.m

%Now we can convert the image array values from integers to double, %and add some random noise. h1=im2double(hh1); for i=1:32 for j=1:32 h1(i,j)=h1(i,j)+rand/6; end end figure(2); imshow(h1), colormap('gray'); figure(3); imshow(h1), colormap('cool');
13/11/2006 30

example2.m
%Here we practice reading and writing images. Converting file formats, and converting color to gray clear; x=imread('ayman.bmp'); %convert the file to "jpg" and to 'tif' formats %(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 applications gray is sufficient) y= rgb2gray(x);
13/11/2006 31

y=im2double(y); %from unsigned integer (0-255) to %double (0-1) %This is neccessary for image transforms. figure(1); subplot(2,1,1), imshow(x); subplot(2,1,2), imshow(y); %Discrete Cosine transform "dct2" is the most important transform for %images, it is used in JPEG compression. ydct=dct2(y); figure, imshow(ydct);

13/11/2006

32

example3.m
%Here we read a signature image, do edge detection and crop the %region of interest in the signature clear; ss1=imread('sig.jpg'); ss2= rgb2gray(ss1); ss3=im2double(ss2); %Edge detection using Canny method edg1=edge(ss3,'canny'); %Now we get the boundaries of the edge then crop the image to %fit the signature x1=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);

13/11/2006

33

uu=imcrop(ss3, [xx1 oo1 xx2 oo2]); %Then we resize the cropped image to be same size %as before tt=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);

13/11/2006

34

Image and Video Processing Blockset


The Video and Image Processing Blockset is a tool used for the rapid design, prototyping, graphical simulation, and efficient code generation of video processing algorithms. The Video and Image Processing Blockset blocks can import streaming video into the Simulink environment and perform two-dimensional filtering, geometric and frequency transforms, block processing, motion estimation, edge detection and other signal processing algorithms. You can also use the blockset in conjunction with Real-Time Workshop to automatically generate embeddable C code for realtime execution. The Video and Image Processing Blockset blocks support floatingpoint, integer, and fixed-point data types. To use any data type other than double-precision and single-precision floating point, you must install Simulink Fixed Point. For more information about this product, see the Simulink Fixed Point documentation.

13/11/2006

35

Potrebbero piacerti anche