Lab Report
Lab Report
2. Write a MATLAB program for (i) showing histogram (ii) contrast stretching
(iii) histogram equalization of a gray level image.
3. Write a MATLAB program for (i) high pass and lowpass filter (ii) average filter
(iii) median, max and min filter of a gray level image.
4. Write a MATLAB program for (i) ideal (ii) Butterworth (iii) Gaussian lowpass
and highpass filter of a gray level image in frequency domain.
5. Write a MATLAB program for (i) Laplacian (ii) homomorphic filter of a gray
level image in frequency domain.
6. Write a MATLAB program for (i) arithmetic and geometric (ii) harmonic
and contraharmonic (iii) midpoint and alpha-trimmed mean filter of a gray
level image.
7. Write a MATLAB program for (i) ideal (ii) Butterworth (iii) Gaussian band
reject and bandpass filter of a gray level image.
11. Write a MATLAB program for (i) Haar Transform (ii) one dimensional
Discrete Wavelet Transform (iii) Discrete Cosine Transform of an image.
12. Write a MATLAB program for edge detection using Sobel, Canny, Prewitt,
Roberts, log, zerocross filter.
13. Write a MATLAB program to implement a LPF (FIR) with cutoff 8KHz and
to denoise audio.
14. Write a MATLAB program to implement Echo of audio signal.
15. Write a MATLAB program to record and save single and double channel audio.
Problem Name: Write a MATLAB program for (i) Negative (ii) Log (iii) Power-law
transformation of a gray level image.
Theory:
Algorithm:
1. Read RGB color image into the MATLAB environment using Matlab inbuilt
function imread()
2. Calculate the levels of the image, for example an 8-bit image has 256 levels
3. Use the formula stated above on every pixel of the image to get corresponding
negative pixel value.
4. Convert each RGB pixel value at location (i, j) to its negative image values and
assign it to the corresponding location (i, j) of another matrix
5. Display the negative image using Matlab in-built imshow() function.
close all;
a = imread('animal.tif');
for i=1:256
for j=1:256
n(i,j)=255-a(i,j);
end
end
subplot(1,2,1);
imshow(a);
title('Original Image');
subplot(1,2,2);
imshow(n);
title('Negative Image');
Output:
Log Image Transformation: The log transformations can be defined by this formula
s = c log(r + 1).
Where s and r are the pixel values of the output and the input image and c is a constant.
The value 1 is added to each of the pixel value of the input image because if there is a pixel
intensity of 0 in the image, then log (0) is equal to infinity. So 1 is added, to make the
minimum value at least 1.
During log transformation, the dark pixels in an image are expanded as compare to the
higher pixel values. The higher pixel values are kind of compressed in log transformation.
This result in following image enhancement.
The value of c in the log transform adjust the kind of enhancement you are looking for.
MATLAB Source Code:
clc
clear all;
close all;
a = imread('cameraman.tif');
c = input(' c = ');
d=im2double(a);
l=d;
for i=1:256
for j=1:256
l(i,j)=c*(log10(1+d(i,j)));
end
end
subplot(1,2,1);
imshow(a);
title('Original Image');
subplot(1,2,2);
imshow(l);
title('Log Transformation');
Correcting gamma.
s=cr^γ
s=cr^(1/2.5)
The same image but with different gamma values has been shown here.
clc
clear all;
close all;
a = imread('cameraman.tif');
c = input(' c = ');
a2 = im2double(a);
for i=1:256
for j=1:256
p(i,j)=c*(power(a2(i,j),gamma));
end
end
subplot(1,2,1);
imshow(a);
title('Original Image');
subplot(1,2,2);
imshow(p);
title('Power-Law Transformation');
Problem Name: Write a MATLAB program for (i) showing histogram (ii) contrast
stretching (iii) histogram equalization of a gray level image.
Theory:
clear all;
close all;
img=imread('peppers.png');
figure(1);
subplot(1,2,1);
imshow(img);
title('Source image')
subplot(1,2,2);
imhist(img);
title('Histogram');
Output:
Example: If the minimum intensity value(r min ) present in the image is 100 then it is
stretched to the possible minimum intensity value 0. Likewise, if the maximum intensity
value(r max) is less than the possible maximum intensity value 255 then it is stretched out
to 255.(0–255 is taken as standard minimum and maximum intensity values for 8-bit
images)
clear all;
close all;
img=imread('peppers.png');
figure(1);
subplot(2,2,1);
imshow(img);
title('Source image')
subplot(2,2,2);
imhist(img);
stretched_image=imadjust(img,[0.3,0.6],[0.0,1.0]);
subplot(2,2,3);
imshow(stretched_image);
subplot(2,2,4);
imhist(stretched_image);
Output:
clear all;
close all;
img=imread('peppers.png');
figure(1);
subplot(2,2,1);
imshow(img);
title('Source image')
subplot(2,2,2);
imhist(img);
subplot(2,2,3);
imshow(hist_equ_image);
subplot(2,2,4);
imhist(hist_equ_image);
Output:
Problem No-03:
Problem Name: Write a MATLAB program for (i) high pass and low pass filter (ii)
average filter (iii) median, max and min filter of a gray level image.
Theory:
clear all;
close all;
RGB=imread('peppers.png');
I = rgb2gray(RGB);
% Highpass filter
subplot(2,2,1);
imshow(RGB)
title('Source image');
subplot(2,2,2);
imshow(high_pass_img);
title('High pass filtered image');
% Lowpass filter
LowKernel = [ 1 1 1; 1 -10 1; 1 1 1 ];
low_pass_img = conv2(LowKernel,I);
subplot(2,2,3)
imshow(RGB);
title('Source image');
subplot(2,2,4);
imshow(low_pass_img);
Output:
Average Filter:
Average (or mean) filtering is a method of 'smoothing' images by reducing the amount of
intensity variation between neighboring pixels. The average filter works by moving
through the image pixel by pixel, replacing each value with the average value of
neighboring pixels, including itself
clear all;
close all;
RGB=imread('peppers.png');
I = rgb2gray(RGB);
[x,y] = size(I);
for i = 2:x-1
for j = 2:y-1
sum = 0;
for ii = i-1:i+1
for jj = j-1:j+1
end
end
I2(i,j) = ceil(sum/9);
end
end
subplot(1,2,1)
imshow(RGB)
title('Source Image');
subplot(1,2,2)
imshow(I2);
Output:
Median, Max and Min filter:
Median Filter: The main problem with local averaging operations is that they tend to
blur sharp discontinuities in intensity values in an image. An alternative approach is to
replace each pixel value with the median of the gray values in the local neighborhood.
Filters using this technique are called median filters.
Median filters are very effective in removing salt and pepper and impulse noise while
retaining image details because they do not depend on values which are significantly
different from typical values in the neighborhood. Median filters work in successive image
windows in a fashion similar to linear filters. However, the process is no longer a weighted
sum. For example, take a 3 x 3 window and compute the median of the pixels in each
window centered around [i, j]
Max Filter: The maximum filter is defined as the maximum of all pixels within a local
region of an image. The maximum filter is typically applied to an image to remove negative
outlier noise.
Min Filter: The minimum filter is defined as the minimum of all pixels within a local
region of an image. The minimum filter is typically applied to an image to remove positive
outlier noise.
clear all;
close all;
% Median Filter
img=imread('cameraman.tif');
[r,c]=size(img);
img=im2double(img);
subplot(231);
imshow(img);
title('Source image');
subplot(232);
imshow(noisy_img);
mf_img=ordfilt2(noisy_img,5,ones(3,3));
subplot(233);
imshow(mf_img);
subplot(234);
imshow(img);
title('Source image');
maxf_img=ordfilt2(noisy_img,9,ones(3,3));
subplot(235);
imshow(maxf_img);
minf_img=ordfilt2(noisy_img,1,ones(3,3));
subplot(236);
imshow(minf_img);
Output:
Problem No-04:
Problem Name: Write a MATLAB program for (i) ideal (ii) Butterworth (iii) Gaussian
lowpass and highpass filter of a gray level image in frequency domain.
Theory:
{ 1 D (u , v ) ≤ D 0
H(u,v) = 0 D ( u , v ) > D 0
Where, D0 is a positive constant. ILPF passes all the frequencies within a circle of
radius D0 from the origin without attenuation and cuts off all the frequencies outside
the circle.
This Do is the transition point between H(u, v) = 1 and H(u, v) = 0, so this is termed
as cutoff frequency.
D(u,v) is the Euclidean Distance from any point (u, v) to the origin of the frequency
plane,
D(u,v) = √ ¿ ¿
clear all;
close all;
input_image = imread('cameraman.tif');
[M, N] = size(input_image);
FT_img = fft2(double(input_image));
u = 0:(M-1);
idx = find(u>M/2);
u(idx) = u(idx)-M;
v = 0:(N-1);
idy = find(v>N/2);
v(idy) = v(idy)-N;
D = sqrt(U.^2+V.^2);
G = H.*FT_img;
output_image = real(ifft2(double(G)));
Output:
Where,
D0 is a positive constant. IHPF passes all the frequencies outside of a circle of radius D0
from the origin without attenuation and cuts off all the frequencies within the circle.
This D0 is the transition point between H(u, v) = 1 and H(u, v) = 0, so this is termed
as cutoff frequency.
D(u,v) is the Euclidean Distance from any point (u, v) to the origin of the frequency
plane, i. e, D(u,v) = √ ¿ ¿
clc;
clear all;
close all;
input_image = imread('cameraman.tif');
[M, N] = size(input_image);
FT_img = fft2(double(input_image));
u = 0:(M-1);
idx = find(u>M/2);
u(idx) = u(idx)-M;
v = 0:(N-1);
idy = find(v>N/2);
v(idy) = v(idy)-N;
D = sqrt(U.^2+V.^2);
G = H.*FT_img;
output_image = real(ifft2(double(G)));
Output:
Butterworth Lowpass Filter: The function expression is as follows (in some books,
the square of the function of Butterworth is equal to the expression on the right, which is
easier to calculate here according to the textbook), where n is called the order of the
Butterworth low-pass filter.
1
[ ]
2n
H(u,v) = D (u , v )
1+
D0
Where,
D0 is a positive constant. BLPF passes all the frequencies less than D0 value without
attenuation and cuts off all the frequencies greater than it.
This D0 is the transition point between H(u, v) = 1 and H(u, v) = 0, so this is termed
as cutoff frequency. But instead of making a sharp cut-off (like, Ideal Lowpass Filter (ILPF)),
it introduces a smooth transition from 1 to 0 to reduce ringing artifacts.
D(u,v) is the Euclidean Distance from any point (u, v) to the origin of the frequency plane,
i.e, D(u,v) = √ ¿ ¿
From the function graph of the filter, we can see that the transition is not as dramatic as the
ideal low-pass filter. It can be seen from c that the higher the order, the more severe the
filter is, the more the ringing phenomenon will be obvious.
clc;
clear all;
close all;
input_image = imread('cameraman.tif');
[M, N] = size(input_image);
FT_img = fft2(double(input_image));
u = 0:(M-1);
v = 0:(N-1);
u(idx) = u(idx) - M;
v(idy) = v(idy) - N;
D = sqrt(U.^2 + V.^2);
H = 1./(1 + (D./D0).^(2*n));
G = H.*FT_img;
output_image = real(ifft2(double(G)));
subplot(1, 2, 1), imshow(input_image),
Output:
Where,
D0 is a positive constant. BHPF passes all the frequencies greater than D0 value without
attenuation and cuts off all the frequencies less than it.
This D0 is the transition point between H(u, v) = 1 and H(u, v) = 0, so this is termed
as cutoff frequency.
clear all;
close all;
input_image = imread('cameraman.tif');
[M, N] = size(input_image);
FT_img = fft2(double(input_image));
u = 0:(M-1);
v = 0:(N-1);
u(idx) = u(idx) - M;
v(idy) = v(idy) - N;
D = sqrt(U.^2 + V.^2);
H = 1./(1 + (D0./D).^(2*n));
G = H.*FT_img;
output_image = real(ifft2(double(G)));
Output:
This is the representation of ideal low pass filter. Now at the exact point of Do, you cannot
tell that the value would be 0 or 1. Due to which the ringing effect appears at that point.
So in order to reduce the effect that appears is ideal low pass and ideal high pass filter, the
following Gaussian low pass filter and Gaussian high pass filter is introduced.
Gaussian Low pass: The concept of filtering and low pass remains the same, but only
the transition becomes different and become smoother.
The function expression is as follows:
clc;
clear all;
close all;
image=imread('cameraman.tif');
[M ,N]=size(image);
n_mid=floor(N/2);
for i = 1:M
for j = 1:N
d = ((i-m_mid)^2+(j-n_mid)^2);
h(i,j) = exp(-d/(2*(d0^2)));
end
end
img_lpf = h.*img_f;
subplot(1,2,1);imshow(image);title('Original image');
Gaussian high pass filter has the same concept as ideal high pass filter, but again the
transition is more smooth as compared to the ideal one.
clc;
clear all;
close all;
image=imread('cameraman.tif');
[M ,N]=size(image);
n_mid=floor(N/2);
for i = 1:M
for j = 1:N
d = ((i-m_mid)^2+(j-n_mid)^2);
h(i,j) = 1 - exp(-d/(2*(d0^2)));
end
end
img_lpf = h.*img_f;
subplot(1,2,1);imshow(image);title('Original image');
Output:
d0 = 10
Problem No-05:
Problem Name: Write a MATLAB program for (i) Laplacian (ii) homomorphic filter of a
gray level image in frequency domain.
Theory:
clear all;
close all;
I=imread('cameraman.tif');
I_D=im2double(I);
[M,N]=size(I_D);
% Center of the image
M0=M/2;
N0=N/2;
J=fft2(I_D);
J_shift=fftshift(J)
A=2;
for x=1:M
for y=1:N
h_hp=1+4*((x-M0)^2+(y-N0)^2)/(M0*N0);
h_bp=(A-1)+h_hp;
J_shift(x,y)=J_shift(x,y)*h_bp;
end
end
J=ifftshift(J_shift);
I_D_rep=ifft2(J);
subplot(1,2,1);
imshow(I);
title('Source Image');
subplot(1,2,2);
imshow(I_D_rep)
Output:
(ii) Homomorphic filter
Homomorphic filtering: Is an image processing method that combines frequency filtering
and spatial grayscale transformation, which is based on the illumination of the image./The
reflectivity model serves as the basis for frequency domain processing, using compressed
luminance ranges and enhanced contrast to improve image quality.
The basic principles of homomorphic filtering are described below.
An image can be seen as consisting of two parts, namely
among them, fi Representing the light intensity that varies with space (IlluminationThe
component, which is characterized by a slow change, is concentrated in the low frequency
part of the image. fr Represents the reflection of the scene reflected to the human eye
(Reflectance) component. Its features include a variety of information on the scene, high-
frequency components.
The homomorphic filtering process is divided into the following5Basic steps:
1. The original image is logarithmic transformed, and the following two additive
components are obtained, namely
clear all;
close all;
% Parameter declaration
rH = 1;
rL = 0.1;
D0 = 0.2;
image = imread('cameraman.tif');
[M, N] = size(image);
% Logarithm
for i = 1:M
for j= 1:N
if mod(i+j, 2) == 0
else
end
end
end
img_py_fft = fft2(img_py);
deta_r = rH - rL;
D = D0^2;
n_mid=floor(N/2);
for i = 1:M
for j =1:N
dis = ((i-m_mid)^2+(j-n_mid)^2);
end
end
% Filtering
img_temp = img_py_fft.*img_tt;
img_temp = abs(real(ifft2(img_temp)));
% Indexed
img_temp = exp(img_temp) - 1;
% Normalization
max_num = max(img_temp(:));
min_num = min(img_temp(:));
img_after = zeros(M,N,'uint8');
for i = 1 : M
for j = 1 : N
end
end
Output:
Problem No-06:
Problem Name: Write a MATLAB program for (i) arithmetic and geometric (ii)
harmonic and contraharmonic (iii) midpoint and alpha-trimmed mean filter of a gray level
image.
Theory:
This operation can be implemented using a convolution mask in which ail coefficients have
value 1/mm. Noise is reduced as a result of blurring.
clear all;
close all;
img=imread('cameraman.tif');
[r,c]=size(img);
img=im2double(img);
subplot(221);
imshow(img);
title('Source image');
noisy_img=imnoise(img,'gaussian');
subplot(222);
imshow(noisy_img);
for i=1:r-2
for j=1:c-2
window = noisy_img(i:i+2,j:j+2);
end
end
subplot(223);
imshow(amf_img);
subplot(224);
imshow(gmf_img);
Output:
(ii) Harmonic and Contraharmonic Filter
Harmonic mean filter
The harmonic mean filtering operation is given by the expression
mn
f(x,y) = ∑ 1
(s , t)∈ S g (s ,t )
The harmonic mean filter works well for salt noise, but fails for pepper noise. It does well
also with other types of noise tike Gaussian noise.
∑ g(s , t)
(Q +1)
(s , t)∈ S
f(x,y) =
∑ g( s,t)
Q
( s ,t ) ∈S
where Q is called the order of the filter. This filter is well suited for reducing or virtually
eliminating the effects of salt-and-pepper noise. For positive values of Q, the filter
eliminates pepper noise. For negative values of Q it eliminates salt noise. It cannot do both
simultaneously. Note that the contraharmonic filter reduces to the arithmetic mean filter if
Q = 0, and to the harmonic mean filter if Q = - 1
clear all;
close all;
img=imread('cameraman.tif');
[r,c]=size(img);
img=im2double(img);
subplot(221);
imshow(img);
title('Source image');
noisy_img=imnoise(img,'gaussian');
subplot(222);
imshow(noisy_img);
Q=1.5;
for i=1:r-2
for j=1:c-2
window = noisy_img(i:i+2,j:j+2);
end
end
subplot(223);
imshow(hmf_img);
subplot(224);
imshow(chmf_img);
Output:
(iii) Midpoint and Alpha-Trimmed Mean Filter
Midpoint Filter
The midpoint filter is typically used to filter images containing short tailed noise such as
Gaussian and uniform type noises. The midpoint filter is defined as : where the coordinate
(x+i, y+j ) is defined over the image A and the coordinate (i, j) is defined over the N x N size
square mask.
The modified alpha mean filter is similar to the method of removing the highest score and
removing the lowest score to evaluate a player's level, that is, sort the data in the filtering
range, remove d data from large to small, and remove d from small to large Data, calculate
the average of the remaining data. Such filters are very good at removing pictures that have
been contaminated by salt and pepper noise along with other types of noise.
clear all;
close all;
% Midpoint Filter ( MF )
img=imread('cameraman.tif');
[r,c]=size(img);
img=im2double(img);
subplot(221);
imshow(img);
title('Source image');
noisy_img=imnoise(img,'Gaussian');
subplot(222);
imshow(noisy_img);
subplot(223);
imshow(midf_img);
d=25; %percent
for i=1:r-2
for j=1:c-2
window = noisy_img(i:i+2,j:j+2);
end
end
subplot(224);
imshow(atmf_img);
Output:
Problem No-07:
Problem Name: Write a MATLAB program for (i) ideal (ii) Butterworth (iii) Gaussian
bandreject and bandpass filter of a gray level image.
Theory:
Band pass and band reject filter transfer functions in the frequency domain can be
constructed by combining lowpass and highpass filter transfer functions. In other words,
the lowpass filter transfer functions are the basis for forming high pass, band reject and
band pass filter functions. A band pass filter transfer function is obtained from a band-
reject function:
The key requirements of a bandpass transfer function are: (1) the values of the function
must be in the range [0,1]; (2) the value of the function must be zero at a distant from the
origin of the function; and (3) we must be able to specify a value for .
Ideal (IBRF)
Gaussian (GBRF)
Butterworth(BBRF)
clc;
clear all;
close all;
% Ideal Bandreject Filter(IBRF)
img=imread('cameraman.tif');
[r,c]=size(img);
imshow(img);
title('Source image');
[u,v]=meshgrid(-floor(c/2):floor((c-1)/2),-floor(r/2):floor((r-1)/2));
%%%Adding Noise
sin_noise= 15*sin( 2*pi*1/10*u + 2*pi*1/10*v);
noisy_img=double(img)+sin_noise;
NOISY_IMG=fftshift(fft2(noisy_img));
figure(2)
subplot(231);
imshow(noisy_img,[]);
title('Sinusoidal noisy image')
subplot(234);
imshow(mat2gray(log(1+abs(NOISY_IMG))));
title('FFT of noisy image');
%%%Creating filter
D=sqrt(u.^2+v.^2);
D0=50;
W=40;
IBRF= ( D<(D0-W/2) | D>(D0+W/2) );
subplot(232);
mesh(IBRF);
title('IBRF');
IBRF_IMG=NOISY_IMG.*IBRF;
ibrf_img=ifft2(IBRF_IMG);
subplot(233);
imshow(mat2gray(abs(ibrf_img)));
title('IBRF filtered image');
% Ideal Bandpass Filter(IBPF)
IBPF= 1 - IBRF ;
subplot(235);
mesh(IBPF);
title('IBPF')
IBPF_IMG=NOISY_IMG.*IBPF;
ibpf_img=ifft2(IBPF_IMG);
subplot(236);
imshow(mat2gray(abs(ibpf_img)));
title('IBPF filtered image');
Input and Output:
(ii) Butterworth band-pass and band-reject filter
%%%Creating filter
D=sqrt(u.^2+v.^2);
D0=50;
n=1;
W=20;
BBRF=1./( 1.+ ( (D.*W) ./ (D.^2-D0.^2) ) .^(2*n) );
subplot(232);mesh(BBRF);title('BBRF')
BBRF_IMG=NOISY_IMG.*BBRF;
bbrf_img=ifft2(BBRF_IMG);
subplot(233);imshow(mat2gray(abs(bbrf_img)));title('BBRF filtered image')
Output:
[u,v]=meshgrid(-floor(c/2):floor((c-1)/2),-floor(r/2):floor((r-1)/2));
%%%Adding Noise
sin_noise= 15*sin( 2*pi*1/10*u + 2*pi*1/10*v);
noisy_img=double(img)+sin_noise;
NOISY_IMG=fftshift(fft2(noisy_img));
figure(2)
subplot(231);imshow(noisy_img,[]);title('Sinusoidal noisy image');
subplot(234);imshow(mat2gray(log(1+abs(NOISY_IMG))));title('FFT of noisy image');
%%%Creating filter
D=sqrt(u.^2+v.^2);
D0=50;
W=20;
GBRF= 1 - exp ( -(1/2).* ( ((D.^2)-(D0.^2)) ./ (D.*W) ).^2 ) ;
subplot(232);mesh(GBRF);title('GBRF');
GBRF_IMG=NOISY_IMG.*GBRF;
gbrf_img=ifft2(GBRF_IMG);
subplot(233);imshow(mat2gray(abs(gbrf_img)));title('GBRF filtered image');
Problem No-08:
Problem Name: Write a MATLAB program for Wiener filter of a gray level
image.
Theory:
The Wiener filter is the MSE-optimal stationary linear filter for images degraded by
additive noise and blurring. Calculation of the Wiener filter requires the assumption that
the signal and noise processes are second-order stationary (in the random process
sense). For this description, only noise processes with zero mean will be considered (this is
without loss of generality).
Wiener filters are usually applied in the frequency domain. Given a degraded image x(n,m),
one takes the Discrete Fourier Transform (DFT) to obtain X(u,v). The original image
spectrum is estimated by taking the product of X(u,v) with the Wiener filter G(u,v):
S(u,v) = G(u,v)X(u,v)
The inverse DFT is then used to obtain the image estimate from its spectrum. The Wiener
filter is defined in terms of these spectra:
H(u,v) Fourier transform of the point spread function(PSF)
Pa(u,v) Power spectrum of the signal process obtained by taking the Fourier transform of
the signal autocorrelation
Pn Power spectrum of the noise process, obtained by taking the Fourier transform of the
noise autocorrelation
The term pn/pa can be interpreted as the reciprocal of the signal-to-noise ratio. Where the
signal is very strong relative to the noise, and the Wiener filter becomes H-1(u,v) - the
inverse filter for the PSF. Where the signal is very weak, pn/pa→∞ and G(u,v)→∞ .
For the case of additive white noise and no blurring, the Wiener filter simplifies to:
Obtaining can be problematic. One can assume that has a parametric shape, for
img=imread('cameraman.tif');
subplot(131)
imshow(img)
title('Source image')
noisy_img=imnoise(img,'gaussian');
subplot(132);
imshow(noisy_img);
wiener_img=wiener2(noisy_img,[5 5]);
subplot(133)
imshow(wiener_img);
Output:
Problem No-09:
Problem Name: Write a MATLAB program for separating RGB and HSI components of a
color image.
Theory:
The RGB Color Model
As you probably know, RGB stands for red, green, blue. The RGB color model is additive:
red, green, and blue light are added together in varying proportions to produce an
extensive range of colors.
It’s important to keep in mind that real-life colors are not actually a mixture of red, green,
and blue. Purple, for example, is purple, not a vector that extends 33 units in the red
direction, 39 units in the green direction, and 127 units in the blue direction. Nonetheless,
the RGB model has been wildly successful and is frequently used in sensor and image-
processing applications.
In my opinion, the RGB model is, overall, quite intuitive. The key to understanding RGB
image processing is recognizing that an RGB image is simply a composite of three
independent grayscale images that correspond to the intensity of red, green, and blue light.
These three images can be processed separately and then recombined into a single image
that human beings will perceive as having color.
Gathering RGB data is also straightforward, again, because RGB imagery boils down to
intensity. A photosensor that measures light intensity becomes an R, G, or B sensor if you
combine it with an optical filter, which means that you can generate RGB data using a unit
consisting of three photosensors and three optical filters. In fact, I used a sensor like this
for a project series that I wrote a couple years ago.
It would be reasonable to assume that color photographs or video imagery would require
three full CCD or CMOS image sensors, but it turns out that a system can generate high-
quality color imagery from one image sensor by using a Bayer filter and then applying
specialized processing algorithms to the resulting data.
It’s true that the RGB model draws upon our familiarity with mixing primary colors to
create other colors, but in terms of actual perception, RGB is very unnatural. People don’t
look at a grapefruit and think about the proportions of red, green, and blue that are hidden
inside the somewhat dull, yellowish-orangish color of the rind or the shinier, reddish flesh.
Though you probably never realized it, you think about color more in terms of hue,
saturation, and intensity.
Hue is the color itself. When you look at something and try to assign a word to the
color that you see, you are identifying the hue. The concept of hue is consistent with
the way in which a particular wavelength of light corresponds to a particular
perceived color.
Saturation refers to the “density” of the hue within the light that is reaching your
eye. If you look at a wall that is more or less white but with a vague hint of peach, the
hue is still peach, but the saturation is very low. In other words, the peach-colored
light reaching your eye is thoroughly diluted by white light. The color of an actual
peach, on the other hand, would have a high saturation value.
rgb_img=imread('peppers.png');
rgb_img=im2double(rgb_img);
figure(1)
subplot(222);imshow(R);title('Red component');
subplot(223);imshow(G);title('Green component');
subplot(224);imshow(B);title('Blue component');
figure(2)
subplot(221);imshow(rgb_img);title('RGB image');
hsi_img=rgb2hsv(rgb_img);
subplot(222);imshow(H);title('Hue component');
subplot(223);imshow(S);title('Saturation component');
subplot(224);imshow(I);title('Intensity component');
Output:
Problem No-10:
Problem Name: Write a MATLAB program for smoothing and sharpening of a color
image.
Theory:
Color Image Smoothing
Gray-scale image smoothing can be viewed as a spatial filtering operation in which the
coefficients of the filtering mask are all 1's. As the mask is slid across the image to be
smoothed, each pixel is replaced by the average of the pixels in the neighborhood defined
by the mask. This concept is easily extended to the processing of full-color images. The
principal difference is that instead of scalar gray-level values we must deal with component
vectors of the form given in Equation.
Let Sxy denote the set of coordinates defining a neighborhood centered at ( x, y ) in a RGB
color image. The average of the RGB component vectors in this neighborhood is
When recognize the components of this vector as the scalar images that would be obtained
by independently smoothing each plane of the starting RGB image using conventional gray-
scale neighborhood processing. Thus, we conclude that smoothing by neighborhood
averaging can be carried out on a per-color-plane basis. This result is the same as when the
averaging is performed using RGB color vectors.
In this section we consider image sharpening using the Laplacian. From vector analysis, we
know that the Laplacian of a vector is defined as a vector whose components are equal to
the Laplacian of the individual scalar components of the input vector. In the RGB color
system, the Laplacian of vector c in Equation is,
which, as in the previous section, tells us that we can compute the Laplacian of a full-color
image by computing the Laplacian of each component image separately .
clear all;
close all;
rgb_img=imread('peppers.png');
rgb_img=im2double(rgb_img);
figure(1)
% Creating filter
avg_filter=fspecial('average',[5 5]);
laplacian_filter=fspecial('laplacian',0.2);
avg_rgb_img=cat(3,avg_R,avg_G,avg_B);
lap_rgb_img=cat(3,lap_R,lap_G,lap_B);
hsi_img=rgb2hsv(rgb_img);
H=hsi_img(:,:,1);
S=hsi_img(:,:,2);
avg_hsi_img=cat(3,H,S,avg_I);
lap_hsi_img=cat(3,H,S,lap_I);
avg_rgb_img_from_hsi=hsv2rgb(avg_hsi_img);
lap_rgb_img_from_hsi=hsv2rgb(lap_hsi_img);
diff_avg_img=avg_rgb_img-avg_rgb_img_from_hsi;
diff_lap_img=lap_rgb_img-lap_rgb_img_from_hsi;
subplot(224);imshow(diff_avg_img);title('Difference');
figure(2)
subplot(224);imshow(diff_lap_img);title('Difference');
Output:
Problem No: 11
Problem Name: Write a MATLAB program for (i) Haar Transform (ii) one dimensional
Discrete Wavelet Transform (iii) Discrete Cosine Transform of an image.
Theory:
(i) Haar Transform:
k = 2p+q-1
For any value of k≥0, p and q are uniquely determined so that 2P is the largest power of 2
contained in k (2P<k) and q-1 is the remainder q-1 = k-2P example, when , the index with
clc;
clear all;
close all;
i=imread('peppers.png');
%functions
transformed_i_level_1=[a1 v1 ; h1 d1];
figure(2);
%leve-2 transformation
Output:
(ii) One dimensional Discrete Wavelet Transform
a discrete wavelet transform(DWT) is any wavelet transform for which the wavelets are
discretely sampled. As with other wavelet transforms, a key advantage it has over Fourier
transforms is temporal resolution: it captures both frequency and location information
(location in time).
clear all;
X=imread('peppers.png');
figure(1);
subplot(1,2,1);
imshow(X);
title('Original Image');
X= double(X);
i=imresize(X,[512 512]);
subplot(1,2,2);
imshow(i);
title('Resize Image');
sX=size(X);
[LL,LH,HL,HH]= dwt2(X,'db1');
figure(2)
clear all;
close all;
img=imread('autumn.tif');
img=rgb2gray(img);
dct_img=dct2(img);
dct_img(abs(dct_img)<10)=0;
idct_img=idct2(dct_img);
Output:
Problem No-12:
Problem Name: Write a MATLAB program for edge detection using Sobel, Canny,
Prewitt, Roberts, log, zero cross filter.
Theory:
Sobel Filter: The Sobel filter is used for edge detection. It works by calculating the gradient
of image intensity at each pixel within the image. It finds the direction of the largest
increase from light to dark and the rate of change in that direction.
Canny Filter: The Canny edge detector is an edge detection operator that uses a multi-
stage algorithm to detect a wide range of edges in images. It was developed by John F.
Canny also produced a computational theory of edge detection explaining why the
technique works.
Prewitt Filter: The Prewitt operator is used in image processing, particularly within edge
detection algorithms. Technically, it is a discrete differentiation operator, computing an
approximation of the gradient of the image intensity function. At each point in the image,
the result of the Prewitt operator is either the corresponding gradient vector or the norm
of this vector. The Prewitt operator is based on convolving the image with a small,
separable, and integer valued filter in horizontal and vertical directions and is therefore
relatively inexpensive in terms of computations like Sobel and Kayyalioperators. On the
other hand, the gradient approximation which it produces is relatively crude, in particular
for high frequency variations in the image.
I=imread('coins.png');
figure(1),
BW1=edge(I, 'sobel');
BW2=edge(I, 'canny');
I=imread('circuit.tif');
BW1=edge(I, 'canny');
BW2=edge(I, 'prewitt');
Output:
Problem No: 13
Problem Name: Write a MATLAB program to implement a LPF (FIR) with cutoff 8KHz
and to denoise audio.
Theory:
FIR filters:
Obtaining Low pass FIR Filter Coefficients: To summarize, two functions are presented that
return a vector of FIR filter coefficients: firceqrip and firgr. Firceqrip is used when the filter
order (equivalently the filter length) is known and fixed. The choice of a filter order of 100
was arbitrary. In general, a larger order results in a better approximation to ideal at the
expense of a more costly implementation. Doubling the order roughly reduces the filter's
transition width in half (assuming all other parameters remain the same).
Source Code
[x, Fs]=audioread(num2str(filename));
%filter implementation
y=filter(df, xn);
Output:
Fst= 8400
sound(x, Fs)
sound(xn, Fs)
sound(y, Fs)
Theory:
In audio signal processing, echo is a reflection of sound that arrives at the listener with a
delay after the direct sound. The delay is directly proportional to the distance of the
reflecting surface from the sound and the listener.
In this case listeners perceive and audible repetition of a signal after some duration of
timel. Listeners perceive distince echoes when the time delay is relatively long. When a
time delay is short listeners do not perceive echoes. Instread a single fused sound is
perceived.
Source Code:
d=2000; %delay
fori=(d+1):1:n
y(i-d, 1)=x(i)+a*xn(i-d);
end
sound(y, Fs), this time we will hear the audio signal with echo
Problem No: 15
Problem Name: Write a MATLAB program to record and save single and double
channel audio.
Theory:
Record and save audio: Record Audio
Record data from an audio input device such as a microphone connected to a system:
•record returns immediate control to the calling function or the command prompt even as
recording proceeds. Specify the length of the recording in seconds, or end the recording
with the stop method. The recording is performed asynchronously.
•record blocking retains control until the recording is complete. Specify the length of the
recording in seconds. The recording is performed synchronously.
3. Create a numeric array corresponding to the signal data using the get audio data method.
Record microphone input: Create an audio recorder object named recObj for recording
audio input.
Source Code:
nob=16; %no of bits per sample, default value is 8bits per sample
%record(recObj)
%pause(5); % no ofseconds
plot(myRecording);
Output:
After running the matlab code, the microphone will start recroding the audio
If we say “This is a test”, then the device will record the audio and save the audio file in the
desiered location.
Problem No-16:
Theory:
Text to speech: In the field of text-to-speech synthesis, or TTS is widely known where the
goal of the machine is to convert ordinary text messages into intelligible and natural
sounding synthetic speech so as to transmit transformation from a machine to a person by
voice.
Ideally, the input to the TTS system is arbitrary input text and the output of the TTS system
is synthetic speech. There are two fundamental processes that all TTS systems must
perform. An analysis of the text must be performed in order to determine the abstract
underlying linguistic description of the speech signal. Then the proper sounds
corresponding to the text input must be synthesized; i.e., a sampled version of the desired
spoken output must be created via the speech synthesizer in a form that can be converted
to an acoustic signal by a D-to-A converter.
Source Code:
NET.addAssembly('System.speech');
mySpeaker=System.Speech.Synthesis.SpeechSynthesizer;
mySpeaker.Rate=3;
mySpeaker.Volume=100;
Output:
After running the matlab code, we will hear a voice saying