Вы находитесь на странице: 1из 33

Experiment: 1

To Calculate Circular Convolution


Aim: To compute the circular convolution of two discrete sequences.
Theory: Two real N-periodic sequences x[n] and h[n] and their circular or periodic
convolution sequence y(n) is also an N- periodic and given by,
N 1

y[n] x[m](( h(m n)) , n 0


m 0

to

N 1

Circular convolution is something different from ordinary linear convolution operation, as


this involves the index ((n-m))N, which stands for a modulo-N operation. Basically both
type of convolution involve same six steps. But the difference between the two types of
convolution is that in circular convolution the folding and shifting (rotating) operations are
performed in a circular fashion by computing the index of one of the sequences with
modulo-N operation. Either one of the two sequences may be folded and rotated without
changing the result of circular convolution.
If x [n] contain L no of samples and h [n] has M no of samples and that L > M, then perform
circular convolution between the two using N = max (L, M), by adding (L-M) no of zero
samples to the sequence h [n], so that both sequences are periodic with number.
Two sequences x (n) and h (n), the circular convolution, y[n] of these two sequences can be
found by using the following steps.
1. Graph N samples of h (n) as equally spaced points around an outer circle in counterclockwise
direction.
2. Start at the same point as h (n) graph N samples of x (n) as equally spaced points around an
inner circle in clock wise direction.
3. Multiply corresponding samples on the two circles and sum the products to produce output.
4. Rotate the inner circle one sample at a time in counter clock wise direction and go to step 3 to
obtain the next value of output.
5. Repeat step No.4 until the inner circle first sample lines up with first sample of the exterior
circle once again.
In Lab Exercise:
Ques1. Find circular convolution of the following signals
x[n]={1,2,1,2}, h[n]={4,3,2,1}

Ques2. Find linear convolution of the following signals using circular convolution
x[n] ={1,2,4}, h[n]={2,5}
Post lab Exercise:
Ques1. Find circular convolution of the following signals
x[n]={1,2,0,1}, h[n]={2,2,1,1}
Ques2. Find circular convolution of the following signals
x[n]={1,-1,1,1}, h[n]={1,2,3,4}
Ques3. Find circular convolution of the following signals
x[n]={1,3,4,5}, h[n]={2,1,4,1}
Ques4. Find linear convolution of the following signals using circular convolution
x[n]={5,3}, h[n]={2,4,6}

Experiment: 2
To Compute Discrete Fourier Transform (DFT)
Aim: To compute the DFT of discrete sequences.
Theory: The N-point discrete Fourier transform (DFT) of a finite-length sequence x[n], defined
for 0 n N 1, is given by

where,
The N-point DFT, X[k] of a length-N sequence x[n], n = 0, 1, . . . , N1, is simply the frequency
samples of its DTFT X( ) evaluated at N uniformly spaced frequency points, = k = 2k/N,
k = 0, 1, . . . , N 1, that is,

The discrete Fourier transform (DFT), X[k] of a finite-length sequence x[n] can be easily
computed in MATLAB using the function FFT. There are two versions of this function. FFT (x)
computes the DFT X[k] of the sequence x[n] where the length of X[k] is the same as that of
x[n]. FFT(x,L) computes the L-point DFT of a sequence x[n] of length N where L N. If L >
N, x[n] is zero-padded with LN trailing zero-valued samples before the DFT is computed. The
inverse discrete Fourier transform (IDFT) x[n] of a DFT sequence X[k] can likewise be
computed using the function IFFT, which also has two versions.
In Lab Exercise:
Ques1. Write a MATLAB program to compute and plot the L-point DFT X[k] of a sequence
X [n] of length N with L N and then to compute and plot the L-point IDFT of X[k]. Run the
program for sequences of different lengths N and for different values of the DFT length L.
Comment on your results.
Ques2. Write a MATLAB program to compute the N-point DFT of two length-N real sequences
using a single N-point DFT and compare the result by computing directly the two N-point
DFTs.
Ques3. Write a MATLAB program to compute the 2N-point DFT of a length-2N real sequence
using a single N-point DFT and compare the result by computing directly the 2N-point DFT.

Post Lab Exercise:


Ques1. Two important concepts used in the application of the DFT are the circular-shift of a
sequence and the circular convolution of two sequences of the same length. Verify these
properties.

Experiment: 3
Digital Filter Design
Aim: To design FIR digital filters.
Theory: The process of deriving the transfer function G(z) whose frequency response G( )
approximates the given frequency response specifications is called digital filter design. After
G(z) has been obtained, it is then realized in the form of a suitable filter structure. In this lab
exercise you will learn how to design an FIR digital filter to meet a specified magnitude or gain
response.
The filter specifications are usually specified in terms of its magnitude response. For example,
the magnitude |G( )| of a lowpass filter G(z) is usually specified as
In the passband defined by 0 p, we require
1 p |G( )| 1 + p, for || p,
or in other words, the magnitude approximates unity within an error of p. In the stopband,
defined by s || , we require
|G( )| s, for s || ,
implying that the magnitude approximate zero within an error of s. The frequencies p and s
are, respectively, called the passband edge frequency and the stopband edge frequency. The
maximum limits of the tolerances in the passband and stopband, p and s, are called ripples.

Fig. 3.1: Normalized magnitude response specifications for a digital lowpass filter.

If the passband edge frequency Fp and the stopband edge frequency Fs are specified in Hz along
with the sampling rate FT of the digital filter, then the normalized angular edge frequencies in
radians are given by

The most straight-forward method of FIR filter design is based on windowing the ideal infinitelength impulse response hD[n] obtained by an inverse discrete-time Fourier transform of the
ideal frequency response HD( ) by an appropriate finite-length window Function, w[n]. The
impulse response coefficients of the final design are then given by
h[n] = D[n] w[n].
The ideal lowpass filter with zero-phase frequency response

The corresponding impulse response coefficients hLP [n] are given by

This is seen to be doubly infinite, not absolutely summable, and therefore unrealizable. By
setting all impulse response coefficients outside the range M n M equal to zero, we arrive
at a finite-length noncausal approximation of length N = 2M + 1 that, when shifted to the right,
yields the coefficients of a causal FIR lowpass filter:

It should be noted that the above expression also holds for N even in which case M is a
fraction, i.e. an integer plus a half.
The impulse response coefficients [n] of the ideal highpass filter are given by

The impulse response coefficients hBP [n] of an ideal bandpass filter with cutoffs at c1 and c2
are given by

and those of an ideal bandstop filter with cutoffs at c1 and c2 are given by

All of the above design methods are for single passband or single stopband filters with two
magnitude levels. However, it is quite straightforward to generalize the method to the design of
multilevel FIR filters and obtain the expression for the impulse response coefficients. The zerophase frequency response of an ideal L-band digital filter hML(z) is given by
hML(ej) = Ak, for k1 k, k= 1, 2, . . . , L, where 0 = 0and L = . Its impulse response
is given by

with Al+1 = 0.
The causal FIR filters obtained by simply truncating the impulse response coefficients of the
ideal filters exhibit an oscillatory behavior in their respective magnitude responses that is more
commonly referred to as the Gibbs phenomenon. The Gibbs phenomenon can be reduced
either by using a window that tapers smoothly to zero at each end or by providing a smooth
transition from the passband to the stopband. Use of a tapered window causes the height of the
side lobes to diminish with a corresponding increase in the main lobe width, resulting in a
wider transition at the discontinuity. In all window-based lowpass filter designs, the cutoff
frequency c is half of the sum of the passband and stopband edge frequencies.
Some commonly used tapered windows of length 2M +1 with fixed ripples are:

The Dolph-Chebyshev window of length 2M +1 is an adjustable window defined by

The most widely used adjustable window is the Kaiser window given by:

where is an adjustable parameter and I0(u) is the modified zeroth-order Bessel function, which
can be expressed in a power series form:

It can be seen that I0(u) is positive for all real values of u. In practice, it is sufficient to keep only
the first 20 terms in the summation to arrive at a reasonably accurate value of I0(u). The
8

parameter controls the minimum stop band attenuation s = 20 log10s of the windowed
filter response. Formulae for estimating and the filter length N = 2M+1, for specified s and
transition bandwidth f = Fp Fs, are given by

The Kaiser window provides no independent control over the passband ripple p. However, in
practice, pis approximately equal to s.
MATLAB Functions
Blackman,butter,buttord,chebwin,cheb1ord,cheb2ord,cheby1,cheby2,ellip,ellipord,fir1,fir
2 firpm,firpmord ,freqz ,hanning ,hamming,Kaiser
The functions fir1 and fir2 can be employed to design linear-phase windowed FIR digital filters
in MATLAB.
The function fir1 can be used to design conventional lowpass, highpass, bandpass, and bandstop
linear-phase FIR filters. The command b = fir1(N,Wn) returns in vector b the impulse response
coefficients, arranged in ascending powers of z1, of a lowpass or a bandpass filter of order N
for an assumed sampling frequency of 2 Hz.
For lowpass design, the normalized cutoff frequency is specified by a scalar Wn, a number
between 0 and 1. For bandpass design, Wn is a two-element vector [Wn1, Wn2] containing the
specified passband edges where0 < Wn1< Wn2< 1. The command b = fir1(N,Wn,high) with N
an even integer, is used for designing a highpass filter. The command b = fir1(N,Wn,stop)
with Wn a two-element vector, is employed for designing a bandstop FIR filter. If none is
specified, the Hamming window is employed as a default. The command b = fir1(N, Wn, taper)
makes use of the specified window coefficients of length N+1 in the vector taper. However, the
window coefficients must be generated a priori using an appropriate MATLAB function such as
blackman, hamming, hanning, chebwin, or kaiser. The commands to use are of the following
forms:
taper = blackman(N) or taper = hamming(N) or taper = hanning(N) or taper = chebwin(N)
or taper = kaiser(N, beta)
The function fir2 can be used to design linear-phase FIR filters with arbitrarily shaped
magnitude responses. In its basic form, the command is b = fir2(N, fpts, mval) which returns in
9

the vector b of length N+1 the impulse response coefficients, arranged in ascending powers of
z1. fpts is the vector of specified frequency points, arranged in an increasing order, in the
range 0 to 1 with the first frequency point being 0 and the last frequency point being 1. As
before, the sampling frequency is assumed to be 2 Hz. mval is a vector of specified magnitude
values at the specified frequency points and therefore must also be of the same length as fpts.
The Hamming window is used as a default. To make use of other windows, the command to use
is b = fir2(N, fpts, mval,taper) where the vector taper contains the specified window
coefficients.
In Lab Exercise
Ques1. Using the function kaiserord, estimate the order of a linear-phase lowpass FIR filter
with the following specifications: passband edge = 2 kHz, stopband edge = 2.5 kHz,
Passband ripple p = 0.005, stopband ripple s = 0.005, and sampling rate of 10 kHz. What are
the purposes of the commands ceil and nargin in the function kaiord?
Ques2. Repeat Question Ques1 for the following cases: (a) sampling rate of 20 kHz, (b) p =
0.002 and s = 0.002, and (c) stopband edge = 2.3 kHz. Compare the filter length obtained in
each case with that obtained in Ques1. Comment on the effect of the sampling rate, ripples, and
the transition bandwidth on the filter order.
Ques3. Using the function fir1, design a linear-phase FIR lowpass filter meeting the
specifications given in Ques1 and plot its gain and phase responses. Use the order estimated
using Kaisers formula in Ques1. Show the filter coefficients in a tabular form. Does your
design meet the specifications? If it does not, adjust the filter order until the design meets the
specifications. What is the order of the filter meeting the specifications?
Ques4. Repeat Ques3 using each of the following windows: Hanning, Blackman, and Dolph
Chebyshev windows.
Ques5. Using fir2 design an FIR filter of order 95 with three different constant magnitude
levels: 0.4 in the frequency range 0 to 0.25, 1.0 in the frequency range 0.3 to 0.45, and 0.8 in the
frequency range 0.5 to 1.0. Plot the magnitude response of the filter designed. Does your design
meet the specifications?
Post Lab Exercise
Ques1. Design an FIR lowpass filter using a Kaiser window. The filter specifications are: p =
0.3, s 0.4, and As = 50dB. Note that the function kaiser requires the values of the parameter
and the order N which must be calculated first using given equations, respectively. Does your
design meet the specifications?
Ques2. Repeat Ques1 using the functions kaiserord and fir1.
10

Experiment: 4
IIR Filter Design
Aim: Write a program for IIR digital filter design (Impulse invariant and Bilinear
transformation) for a given specifications.

Theory:
IIR Filter Types
1) Butterworth filter

Provides the best Taylor series approximation to the ideal low pass filter response at analog
frequencies = 0 and = ; for any order n, the magnitude squared response has 2n 1 zero
derivatives (that is, it is maximally flat) at these locations. Response is monotonic overall,
decreasing smoothly from = 0 to = .
2) Chebyshev Type I filter

It minimizes the absolute difference between the ideal and the actual frequency response over the
entire pass band by using an equal ripple in the pass band. Stop band response is maximally flat.
The transition from pass band to stop band is more rapid than for the Butterworth filter.
3) Chebyshev Type II filter

It minimizes the absolute difference between the ideal and the actual frequency response over the
entire stop band by using an equal ripple in the stop band. Pass band response is maximally flat.
The stop band does not approach zero as quickly as the type I filter. The absence of ripple in the
pass band, however, is often an important advantage.
4) Elliptic filter

Equiripple in both the pass band and stop band. Generally meets filter requirements with the
lowest order of any supported filter type. Given a filter order n, pass band ripple, and stop band
ripple, elliptic filters minimize transition width.
For designing Butterworth filter, the commands are [num, den] = butter(N, W n)For designing a
Type 1 Chebyshev digital filter, the commands are [num, den] = cheby1(N, Rp, Wn)
For designing a Type 2 Chebyshev digital filter, the commands are [num,den] = cheby2(N,Rs,Wn)
For designing Butterworth filter, the commands are [num, den] = ellipse (N, Rp, Rs, Wn)
Each function delivers a low pass filter by default. To design a band pass, W n must be defined as a
vector of 2 elements. The elements hold the corner frequencies of the band pass filter. The filter
order N and the scaling factor for the frequency bounds Wn can be determined as follows:
[N, Wn] = buttord(Wp, Ws, Rp, Rs) [N, Wn] = cheblord(Wp, Ws, Rp, Rs) [N, Wn] = ellipord(Wp, Ws,
Rp , Rs
11

Where, the input parameters are the normalized passband edge frequency Wp, the normalized
stopband edge frequency Ws, the passband ripple Rp in dB, and the minimum stopband
attenuation Rs in dB. Both Wp and Ws must be a number between 0 and 1 with the sampling
frequency assumed to be 2 Hz. The output data are the lowest order N meeting the specifications
and the normalized cutoff frequency Wn. If Rp = 3 dB, then Wn = Wp. Buttord can also be used to
estimate the order of a highpass, a bandpass, and a bandstop Butterworth filter. For a highpass
filter design, Wp > Ws. For bandpass and bandstop filter designs, Wp and Ws are two-element
vectors specifying both edge frequencies, with the lower edge frequency being the first element of
the vector. In the latter cases, Wn is also a two-element vector.
Digital IIR Filter design
The design of an IIR filter is rather straightforward when using the bilinear transformation
technique. An analog filter is converted to a digital one via the bilinear transformation we obtain
the relation

As the bilinear transformation preserves the type of filter (LP, BP etc.) we only need to make sure
that the cut-off frequencies gets mapped to the correct place. The design technique is summarized
here: Start b identifying the discrete time frequencies describing the cut-off frequencies. Use
normalized frequencies in radians where,
= represents half the sampling frequency ( = 2f / fs).
Calculate the corresponding analog frequencies using = 2 tan (2).Design an analog filter
Ha(s) based on the specifications. Use the bilinear transformation to obtain the final digital (Zdomain) filter.

In Lab Exercise:
Ques1. Using MATLAB determine the lowest order of a digital IIR high pass filter of all four
types. The specifications are as follows: sampling rate of 3,500 Hz, pass band edge
frequency of 1,050 Hz, stop band edge frequency of 600 Hz, pass band ripple of 1 dB, and a
minimum stop band attenuation of 50 dB. Plot the frequency response of the above IIR filter for
bilinear and impulse invariant transforms. Comment on your results.

12

Post Lab Exercise:


Ques1. Using MATLAB determine the lowest order of a digital IIR bandstop filter of all four
types. The specifications are as follows: sampling rate of 12 kHz, passband edge frequencies at 2.1
kHz and 4.5 kHz, stopband edge frequencies at 2.7 kHz and 3.9 kHz, passband ripple of 0.6 dB,
and a minimum stopband attenuation of 45 dB. Plot the frequency response of the above IIR filter
for bilinear and impulse invariant transforms. Comment on your results

13

Experiment: 5
Digital Image Processing
Aim: Introduction to Digital Image Processing in MATLAB.

Theory: Some commands and programs


Reading Image File:
We can use following command to read image file:
myImage=imread(File name with path)
If name of the image file is test.bmp and if it is in /home/chv folder above commands can be written
as:
myImage=imread(/home/chv/test.bmp)
The image filename can be given as a full file path or as a file path relative to the current directory.
The current directory can be changed from the main interface window or by cd (change directory
command). The supported file formats include bmp, gif, jpg, jpx and png. After giving above
command image data is available in myImage variable. You can use any variable name.
Displaying image
After reading image data using above function, we can display images using imshow function. This
function simply takes the array storing the image values as its only parameter.
Syntax:
imshow(<variable name>)
Example:
imshow(myImage);
Knowing size of image in pixels Size of the image in pixels can be found out by following
command:
[Rows, Cols] = size(myImage)
Image resizing
Image resizing can be done by following command
imresize(Image,{Parameters});

14

For example: Consider that we read the image in variable myImage using imread function than we
can resize the image stored in this variable by following command
imresize(myImage,[256,256],nearest);
This command will convert image of any size into image of 256x256 using nearest neighbor
technique.
Converting Color image into Grayscale image:
Color image can be converted into Grayscale image by Matlab function rgb2gray. Example:
myGrayImage=rgb2gray(myImage)
Converting Color image into Binary Image:
Color image can be converted into Binary image using function im2bw:
Example:
myBWImage=im2bw(myImage) where myImage is 2D image data
Intensity profile along line given by two points on image
Drawing of intensity profile along single line on given image (Scan one line along the image
draw intensity values (1-D signal)) can be done by function improfile()

and

Example:
improfile(myImage,[0,150],[200,150]);
If given image is chess-board pattern, profile graph would be squarewave.
Separate color image into three separate R, G, B planes
If we read given color image using imread() function, we get 3-D matrix. To separate out R, G and B
planes, we can read each plane separately as follows:
Example:
myImage=imread(RGBBar.bmp);
RED=myImage(:,:,1);
GREEN=myImage(:,:,2);
BLUE=myImage(:,:,3);

15

Combine three separate R, G, B planes to create color image If we have three R, G and B planes
separately and if we want to create color image from it, we can use concatenate function:
Example:
newImage = cat(3,RED,BLUE,GREEN)
Flow control: If statements are simply used to make decisions
Syntax:
if<condition> then
<do some work>
else<do some other work>
end
If we wish to perform thresholding of an image we could use following statements:
if ImageData(r, c) > threshold then
ThresholdedImage(r, c) = 255;
else
ThresholdedImage(r, c) = 0;
end
Loops in
There is for loop and while loop in MATLAB.
While loop
While loop repeat a piece of work as long as a condition holds true. The while loop uses the
following syntax:
while<condition>
<perform some work repeatedly>
End

16

For loop is very popular for image processing because it is particularly useful for iterating through the
members of a matrix.
Syntax:
for index = <start>:<finish>
<Perform some work>
end
Example
Following code iterates through each pixel of image, does summation of pixel values, finds average
pixel value which represents average brightness of the scene.
myImage=imread(/home/chv/test.bmp)
[Rows, Cols] = size(myImage)
total = 0;
for rowIndex = 1:Rows
for colIndex = 1:Cols
total = total + ImageData(rowIndex, colIndex);
end
average=total/(Rows*Cols)
Saving two dimensional matrix in Image file
We read image, image data is available in two dimensional matrices. We process the matrix. After
processing,we need to save the processed data in form of image. To save image data in image file,
following command is used.
imwrite(ImageData, ' Testout.bmp', 'bmp');
This command writes ImageData in file Testout.bmp. It also supports gif, jpg and png file
formats. Image enhancement can be done in two domains: [1] Spatial Domain and [2] Transform
domain.
In spatial domain Image processing, there are two ways:
Point processing (Single pixel is processed at a time)

17

Neighborhood processing (Mask processing) Convolution of 3x3 or 5x5 or other size of mask with
image
In point processing, Grey level transformation can be given by following equation
g(x,y)=T(f(x,y))

s=T(r)

Where, f(x,y) is original image, g(x,y) is transformed image


s = gray level of transformed image
r = gray level of original image
Threshold operation:
In threshold operation, Pixel value greater than threshold value is made white and pixel value less than
threshold value is made black. If we consider image having gray levels r and if grey levels in output
image is s than,
s = 0 if r m
s = 255 if r > m Where m = threshold
Negative Image:
Negative Image can be obtained by subtracting each pixel value from 255.
Contrast Stretching:
Contrast Stretching means Darkening level below threshold value m and whitening level above
threshold value m. This technique will enhance contrast of given image. Thresholding is example of
extreme contrast stretching.
Practically contrast stretching is done by piecewise linear approximation of graph shown in left by
following equations:

s = x.r

0 r<a

s = y.r

a r<b

s = z.r

b r < 255

18

Where x,y and z are different slopes.


Arithmetic operations like image addition, subtraction, multiplication and division is possible. If there
is two images I1 and I2 then addition of image can be given by:
I(x,y) = I1(x,y) + I2(x,y)
Where I(x,y) is resultant image due to addition of two images. x and y are coordinates of image. Image
addition is pixel to pixel. Value of pixel should not cross maximum allow value that is 255 for 8 bit
grey scale image. When it exceeds value 255, it should be clipped to 255.
To increase overall brightness of the image, we can add some constant value depending on brightness
required. We will add value 50 to the image and compare brightness of original and modified image.
To decrease brightness of image, we can subtract constant value. In example program, value 100 is
subtracted for every pixel. Care should be taken that pixel value should not less than 0 (minus value).
Subtract operation can be used to obtain complement (negative) image in which every pixel is
subtracted from maximum value i.e. 255 for 8 bit greyscale image. Multiplication operation can be
used to mask the image for obtaining region of interest. Black and white
mask (binary image)
containing 1s and 0s is multiplied with image to get resultant image. To obtain binary image function
im2bw() can be used. Multiplication operation can also be used to increase brightness of the image
Division
operation results into floating point numbers. So data type required is floating point
numbers. It can be converted into integer data type while storing the image. Division can be used to
decrease the brightness of the image. It can also use to detect change in image.
Calculate mean value:
Mean value can be calculated by MATLAB function mean().
Post Lab Exercise:
1) Create image of size 512x512 black square using monochrome, 256 gray-level using paint or any
other relevant software and save it file name black.bmp Read and display image using
MATLAB commands.
2) Execute following program for the image created in exercise [1] and observe the result. Write
comments on the result:
imgData=imread('black.bmp');
[Rows,Cols]=size(imgData);
imshow(imgData);
for i=1:Rows
for j=1:Cols
19

if(i >Rows/4 && i<3*Rows/4)


if(j>Cols/4 && j<3*Cols/4)
imgData(i,j)=0;
end
end
end
end
figure;imshow(imgData);
3) Read color image pout.bmp given in working directory, convert it into Grey-scale image, find
size of the image, Resize it to 256x256.
4) In contrast stretching program take threshold values 50 and 100, Use slope 3 for gray levels
between 0 to 50, slope 2 for gray levels between 50 to 100 and slope 1 for rest gray levels. Modify
and write program again. Execute it for some image. Write your own matlab function add
brightness() and use

20

Experiment: 6
Introduction to Histogram of an Image and its Histogram Equalization.
Aim: Introduction to histogram, histogram calculation and equalization in MATLAB.
Theory:
Histogram
A histogram is a representation of tabulated frequencies, shown as adjacent rectangles, erected over
discrete intervals (bins), with an area proportional to the frequency of the observations in the interval.
The height of a rectangle is also equal to the frequency density of the interval, i.e., the frequency
divided by the width of the interval. The total area of the histogram is equal to the number of data. A
histogram may also be normalized displaying relative frequencies. It then shows the proportion of
cases that fall into each of several categories, with the total area equaling 1. The categories are usually
specified as consecutive, non-overlapping intervals of a variable. The categories (intervals) must be
adjacent, and often are chosen to be of the same size. The rectangles of a histogram are drawn so that
they touch each other to indicate that the original variable is continuous.
Simply, histogram is bar-graph used to profile the occurrence of each gray level in the image
An image histogram is a type of histogram that acts as a graphical representation of the tonal
distribution in a digital image. It plots the number of pixels for each tonal value. By looking at the
histogram for a specific image a viewer will be able to judge the entire tonal distribution at a glance.

Mathematically it is represented as h(rk)=nk Where rk is kth grey level and nk is number of pixel
having that grey level
Histogram can tell us whether image was scanned properly or not. It gives us idea about tonal
distribution in the image.
Histogram equalization can be applied to improve appearance of the image. Histogram also tells
us about objects in the image. Object in an image have similar gray levels so histogram helps us
to select threshold value for object detection.
Histogram can be used for image segmentation.

21

Fig 6.1.: Image histograms


In the field of computer vision, image histograms can be useful tools for thresholding. Because
the information contained in the graph is a representation of pixel distribution as a function of
tonal variation, image histograms can be analyzed for peaks and/or valleys which can then be
used to determine a threshold value. This threshold value can then be used for edge detection,
image segmentation, and co-occurrence matrices.
Histogram Equalization
This method usually increases the global contrast of many images, especially when the usable data of
the image is represented by close contrast values. Through this adjustment, the intensities can be better
distributed on the histogram. This allows for areas of lower local contrast to gain a higher contrast.
Histogram equalization accomplishes this by effectively spreading out the most frequent intensity
values.

Fig 6.2: Histogram equalization


Consider a discrete grey scale image {x} and let ni be the number of occurrences of gray level i. The
probability of an occurrence of a pixel of level i in the image is

22

L being the total number of gray levels in the image (typically 256), n being the total number of pixels
in the image, and px(i) being in fact the image's histogram for pixel value i, normalized to [0,1].

Let us also define the cumulative distribution function corresponding to px as

which is also the image's accumulated normalized histogram.

The general histogram equalization formula is:

where cdfminis the minimum non-zero value of the cumulative distribution function , M N gives the
image's number of pixels and L is the number of grey levels used (in most cases, , 256).
Standard MATLAB function for histogram and histogram equalization:
imhist function - It computes histogram of given image and plot
Example:
myimage=imread(tier.jpg)
imhist(myimage);
histeq function - It computes histogram and equalize it.
Example:
myimage = imread(rice.bmp);
newimage= histeq(myimage);

In Lab Exercise:
1. Write a program for histogram calculation. Verify your results using Matlab built-n functions.
2. Write a program for equalization. Verify your results using Matlab built-n functions.
23

Post Lab Exercise:


1. Take your own photograph in dark area. Improve its appearance using histogram equalization
technique. (Copy and paste your original image, its histogram, equalized image and its histogram)

24

Experiment: 7
Aim: Introduction to image filtering in spatial and in frequency domains
Theory:
In the early days of image processing the use of Discrete Fourier Transform
(DFT) was very restricted because of its high computational complexity. With the introduction of
the FFT algorithm the complexity of DFT was reduced and DFT became
an extremely
important practical tool of image processing.
In this lab we'll study the properties of DFT and two practical applications:
1. Computation of convolution by two methods direct method (in spatial domain) and indirect
method (in frequency domain).
2. Computation of edge enhancement by unsharp masking.
In Lab Exercise:
1. Prove the following properties of the Continuous 2-D Fourier Transform:
a. Linearity property,
b. Scaling property,
c. Rotation property,
2. Explain the purpose of Matlabs command fftshift.
3. The magnitude of spectrum usually has a large dynamic range. How do you display the
magnitude of spectrum in Matlab?
4. Study the Matlab functions fspecial and imfilter. Explain the purpose of the unsharp filter
of fspecial. Explain the role of the parameter .
Exercise: Select a gray-scale image of your choice to be used as a test case for the experiments.
Description of the experiment
Part 1 - DFT Properties
Use the supplied program dft_demo.m.
1. Observe the following properties and demonstrations:
a. Matlabs fftshift command.
25

b. Linearity.
c. Scaling.
d. Rotation.
e. Exchange between magnitude and phase.
2. Test these properties and demonstrations (except for linearity) with the image of your choice.
(Use the Matlab function imresize).
Part 2 Convolution
1. Observe the implementation of convolution in two ways (in spatial domain and in
frequency domain).
2. Test the implementation of convolution in two ways with the image of your choice.
3. Implement convolution with averaging filter using Matlabs commands
fspecial (average,...) and imfilter(...).
Part 3 Unsharp masking
1. Test the unsharp masking algorithm with the image of your choice.
2. Implement unsharp masking using Matlabs commands fspecial (unsharp,...) and
imfilter(...). Test the effect of various values of the parameter
Post Lab Exercise:
1. Write your own program to implement frequency domain filtering using DFT.
2. Write your own program to implement spatial domain mean filter.

26

EXPERIMENT: 8
Aim: Short-time energy measurements of speech signal using rectangular/Hamming
windows.
Theory: Short-Time energy of speech signal
Short-Time Energy in vicinity
[] = {(). ()}2
W(n) =1 0 n N-1
=0 otherwise
Window jumps/slides across sequence of squared values, selecting interval for processing.
What happens to En as sequence jumps by 2, 4, 8,..., N samples (En is a low pass
function so it can be decimated without loss of information)
Effects of decimation depend on N; if N is small, then En is a lot more variable than if N
is large (window bandwidth changes with N)

Short-Time Energy:

= =[()( )]2(Sum or square of the portion of


signal)
--concentrates measurement at sample n, using weighting w(n-m)

= =[()( )]2= = =[()( )]2


() = 2 (n)

2 ()

x(n)
(

h(n)

)2

Fig 8.1: Block level description for Short-time energy measurements

27

Experiment: 9
Aim: Short-time average zero-crossing rate calculation of speech signal
rectangular/Hamming windows.
Theory: Short-Time Average ZC Rate
Crossing => successive samples have different algebraic signs

zero

Fig 9.1: Zero-crossing of signal

Zero crossing rates is a simple measure of the frequency content of a signalespecially


true for narrowband signals (e.g., sinusoids)
Sinusoid at frequency F0with sampling rate FS has FS/F0samples per cycle with two
zero crossings per cycle,
Giving an average zero crossing rate of

Z=2Fo/Fs crossing/samples

Assuming the sample rate is Fs=10000Hz


Z1=2/100 crossings/sample or Z100

Fo= 1000 Hz sinusoid has Fs/Fo

Z1 2 /10 crossing /sample, or Z100 2/10*100=20 crossings/10msecinterval

Fo= 5000 Hz sinusoid has Fs/Fo

Z1 2 /2 crossing /sample ,or Z100 2/10*100=20crossings/10msecinterval

28

using

ZC Rate Definitions:

Zn = |[()] [( 1)]|( )
=0

[()] = {

1, () 0
1, () < 0

-simple window, rectangular window:

1
= {2 , 0 1
0,

Fig. 9.2: Zero crossing for Voiced and Unvoiced speech

For voiced speech, energy is mainly above 3 kHz

29

for unvoiced speech, energy is mainly above 3kHz


mean ZC rate for unvoiced speech is 49 per 10 msec interval
mean ZC rate for voiced speech is 14 per 10 msec interval

30

Experiment: 10
Aim: Silence/Voiced/Unvoiced selection of speech signal.
Theory: Prior to analysis, the speech signal is highpass filtered to remove any dc, low
frequency hum, or noise components which might be presented. The transfer function of high
pass filter is given below.

Then the following parameters are computed for each block of speech samples:
1. Short-Time energy of speech signal on logarithmic scale

Where is a small positive constant added to prevent the computing of log of zero.
Generally, Es for voiced data is much higher than the energy of silence. The energy
of unvoiced data is usually lower than for voiced sounds but higher than for silence.

2. Zero-crossing count Nz, the number of zero crossing in

the blocked in the signal


spectrum. Voiced speech is produced as a result of excitation of the vocal tract by
the periodic flow of air at the glottis and usually shows allow zero crossing count.
Unvoiced speech is produced due to excitation of the vocal tract by the noise-likes
our cleat a point of constriction in the interior of the vocal tract and shows a high
zero crossing count. The zero crossing count of silence is expected to be lower than
for unvoiced speech, but quite comparable to that for voiced speech.

3. Normalized autocorrelation coefficient at unit sample delay, C1 which is defined


as

This parameter is the correlation between adjacent speech samples. Due to the
concentration of low frequency energy of voiced sounds, adjacent samples of
voiced speech wave form are highly correlated and thus this parameter is close
to1.
On the other hand, the correlation is close to zero for unvoiced speech.

4. First

linear predictor coefficient (LPC) of a 12-pole linear predictive coding


analysis using the covariance method. It can be shown that this parameter is the
negative of the Fourier component of the log spectrum at unit sample delay. Since
31

the spectra of the three classes voiced, unvoiced and silence differ considerably, so
does the first LPC coefficient.

5. Normalized prediction error, Ep, expressed in dB, which is defined as

The five parameters discussed above are correlated with each other. The decision
algorithm discussed in the next section will make use of it to differentiating between the
classes voiced, unvoiced and silence.
Decision Algorithm: To make this decision, a classical of minimum probability of error
decision is used in which it is assumed that the joint probability density function of the
possible values of the measurements for the ith class is a multi dimensional Gaussian
distribution with known mean mi and covariance matrix Wi. i=1,2,3 corresponds to class
1 (silence),class 2 (unvoiced),and class 3 (voiced), respectively.
For the decision rule, the distribution of the measurement does not need to be
necessarily exactly normal. In the case o fun modal distributions, it is sufficient that the
distribution be normal in the center of its range, which is often true for physical
measurements.
Let x be an L dimensional column vector (in our case L=5) representing the
measurements, that is the kth component is the kth measurement. The L-dimensional
Gaussian density function for x with mean vector Mi and covariance matrix Wi is given
by

The decision which minimizes the probability error states that the measurement vector x should be
assigned to class iif

Where pi is the a priori probability that x belongs to the ith class. This decision rule, by
throwing away some insignificant parts and manipulations, can be further simplified: the
quantity distance di^ defined as

32

is computed and the index i is chosen such that di^ is minimized.


Estimation of the Means and the Covariance
In order to use the above decision algorithm, a training set of data is required to obtain the mean
vector and the covariance matrix for each class. This training set is created by manually
segmenting natural speech into regions of silence, unvoiced speech and voiced speech. The
measurements mentioned above are made on each block of data. Let xi denotes the measurement
vector for the nth block for class ( i=1, 2, 3 ) and Ni denotes the number of the blocks manually
classified as class i in the training set, then

33

Вам также может понравиться