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

Image Processing using Matlab

About Matlab
MatLab : Matrix Laboratory

Numerical Computations with matrices


Every number can be represented as matrix

Why Matlab?
User Friendly (GUI)
Easy to work with
Powerful tools for complex mathematics

2
Desktop Tools
Command Window
type commands

Workspace
view program variables
clear to clear
double click on a variable to see it in the Array Editor

Command History
view past commands
Command Window
Workspace

Command History
Getting Started
Declare variable in matlab using
>> A=9;
>> B=10;
>> A
9
who: current variables in the workspace
>> who
Your variables are:
A B
whos
Name Size Bytes Class
A 1x1 8 double array
B 1x1 8 double array
Matrices
a vector >> x = [1 2 5 1]

x =
1 2 5 1

a matrix >> x = [1 2 3; 5 1 4; 3 2 -1]

x =
1 2 3
5 1 4
3 2 -1

transpose >> y = x
y =
1 5 3
2 1 2
3 4 -1
Colon Operator
>> y=x(2,3)
y = 1 2 3
x= 5 1 4
4 Comment Statement 3 2 -1

>> y=x(3,:) % All elements of third row


y =
3 2 -1

>> y=x(:,2) % All elements of second column


y =
2
1
2
Basic Mathematical Operations
Addition:
1 3 1 4 2 7
A B C
3 1
>> C = A + B
5 2 7 4
Subtraction:
>> D = A B

Multiplication:
>> E = A * B (Matrix multiplication)
>> E = A .* B (Element wise multiplication)

Division:
>> F = A . / B (Element wise division)

8
Generating basic matrices
Matrix with ZEROS
>> z = zeros(r, c);
z=zeros(3,3)
Matrix with ONES
>> o = ones (r, c);
o=ones(3,3)
IDENTITY Matrix
>> I = EYE (r, c);
i=eye(3,3)
Random Numbers
>> R=rand(r, c);

r Rows
c Columns
zeros, ones, eye Matlab functions

9
Operators
>> x = [zeros(1,3) ones(1,2)]
[] concatenation x =
0 0 0 1 1

>> x = [1 3 5 7 9]
x =
1 3 5 7 9

>> y = x(2)
() subscription
y =
3
>> y = x(2:4)
y =
3 5 7
Load and Save Variables
>> A = [1 2 3] % declare A
>> B = [4 5 6] % declare B

>> save mydata.mat % save current variables in workspace

>> clear % clear all variables in workspace

>> load mydata.mat % load mat file containing already


% saved variables

>> who
Your variables are:
A B
Flow Control
if A > B
if statement
'greater'
switch statement
elseif A < B
'less'
else
'equal'
end

for loops for x = 1:10


r(x) = x;
while loops
end
Scripts and Functions
Scripts
which do not accept input arguments or return output arguments.
They operate on data in the workspace.

Functions
which can accept input arguments and return output arguments.
Internal variables are local to the function.
Example - Script
Example - Function
Run .m file
From editor
we can run a script from editor using button

From command prompt


>> x=2:7;
>> [m,s] = stat(x); % function
>> stat; % script
What is the Image Processing Toolbox?
The Image Processing Toolbox extends the basic capabilities of
Matlab by providing a number of specialized I/O, display, and
processing functions for images and image processing.

The basic image functions are


Neighborhood and block operations
Linear filtering and filter design
Transforms
Image analysis and enhancement
Binary image operations
Region of interest operations
Coordinate System
Pixel Coordinates
most convenient method for expressing locations in
an image is to use pixel coordinates.

1,1 1,2
columns
2,1
1 2 3
1 34 32 33 ..
2 17 22 25 ..
rows

3 18 21 24 ..
.
.
Some basic concepts
Reading an image
>> I = imread('pout.tif');

Display an image
>> imshow(I);
>> imtool(I);
>> imagesc(I);
>> image(I);

Writing an image to disk


>> imwrite (I, 'pout2.png,png);

Get contents of an image Format of image to be


written
>> imfinfo(pout.tif);
Data Types
Matlab uses 3 data types to represent an image
8 bit image
Values range from 0 to 255 (Class uint8)

16 bit image
Values range from 0 to 65535 (Class uint16)

Double image
Values range from 0 to 1 (Class double)
Image Formats in MATLAB
MATLAB can import/export several image formats

BMP (Microsoft Windows Bitmap)

GIF (Graphics Interchange Files)

JPEG (Joint Photographic Experts Group)

PNG (Portable Network Graphics)

TIFF (Tagged Image File Format)

MATLAB can also load raw-data or other types of image data


Colormap in Matlab
The colormap is an m-by-3 matrix of class double.

Each row of the colormap matrix specifies the red,


green, and blue (RGB) values for a single color:
color = [R G B]
Image Types in the Toolbox
The Image Processing Toolbox supports four basic types of images:
Intensity images

RGB images

Indexed Images

Binary Images
Intensity Images
An intensity image is a data matrix, whose values
represent intensities within some range.

The matrix can be of


class double, values in the range [0 1],
class uint8, values range is [0 255]
153 152 152 152
155 154 153 153
156 155 154 155
155 154 153 154
Read intensity image in matlab
>> I=imread(camera.bmp','bmp'); % load image

Matrix with image data image filename as a string image format as a string

165 164 162 160 159 157


167 165 163 162 161 158
168 166 164 163 162 160
167 166 164 163 162 160
166 165 163 162 162 160
166 165 163 163 162 161
167 166 164 164 163 162
168 167 166 165 165 164
169 168 167 165 164 162
169 168 167 166 164 162
Display Intensity Image
>>imshow(I);
>>whos I

Name Size Bytes Class

I 512x512 262144 unit8 array


RGB Images
An RGB image, sometimes referred to as a truecolor image,

m-by-n-by-3 data array that defines red, green, and blue color
components for each individual pixel
Read rgb image
>> rgb=imread(pills.bmp);

Consider pixel position rgb(112,86,:)


(112,86,1) 0.1238
(112,86,2) 0.9874
(112,86,3) 0.2543

The color for the pixel at (112,86) is:


0.1238 0.9874 0.2543
Displaying rgb image
>> image(rgb); % imshow(I) : alternate method
Indexed Images
An indexed image consists of two arrays,
Image matrix
Colormap

An indexed image uses direct mapping of pixel values to


colormap values. Colormap
Image Matrix
519 0.59 0.59 0.59
260 517 774 520 0.27 0.27 0.27
261 518 775
262 519 776 521 0.41 0.41 0.41
263 520 777 522 0.53 0.53 0.53
523 0.58 0.58 0.58

mapping
Displaying indexed images
>> I=imread(mandrill.bmp);
>> I2=I(:,:,2); % green values of I
>> image(I2)
>> colorbar % display colourmap

Index

Associated color

Colour Lookup Table


Binary Image
In a binary image, each pixel assumes one of only two
values 0 or 1.

0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
1 1 1 1 1 1
1 1 1 1 1 1
Converting Images
After image has been read it has to be converted from
one form to another

Functions Usage
gray2ind intensity image to index image
im2bw image to binary
im2double image to double precision
im2uint8 image to 8-bit unsigned integers
im2uint16 image to 16-bit unsigned integers
ind2gray indexed image to intensity image
mat2gray matrix to intensity image
rgb2gray RGB image to grayscale
rgb2ind RGB image to indexed image
Example Image Conversion
>> im=imread(capsule.jpg);
>> im1=rgb2gray(im);

50

100

150

200

250

300

350

400

450

500

100 200 300 400 500 600 700 800


>> im2=im2bw(im1);
Image Airthematic
Add two images
>>im1=imread(1.jpg);
>>im2=imread(2.jpg);
>>im3=imadd(im1,im2);

Find the complement image


>> IM2 = imcomplement(IM);

Absolute difference of two images


>> Z = imabsdiff(X,Y);
Image Arithmetic
Some basic image transforms
Cropping an image
>> I = imread('circuit.tif');
>> I2 = imcrop(I,[75 68 130 112]);
>> imshow(I), figure, imshow(I2);
Resizing an image
>> im=imread(capsule.jpg);
>> im1=imresize(im,[100 100],'bicubic');
>> imshow(im1);
Method to resize
Rotating an image
>> im1=imread(camera.jpg);
>> im3=imrotate(im1,10,'bicubic'); % rotate an image

imrotate(A,ANGLE) rotates image A by ANGLE degrees in a


counterclockwise direction around its center point. To rotate the image
clockwise, specify a negative value for ANGLE.
A sample code
Rotation

Complement
Image Enhancement using Histogram
Processing Techniques
44

Histogram of an image represents the relative


frequency of occurrence of various gray levels in
the image

Takes care the global appearance of an image

Basic method for numerous spatial domain


processing techniques

Used effectively for image enhancement


Why Histogram Processing Techniques?
45

4
x 10
4

3.5

2.5

1.5

0.5

0 50 100 150 200 250

It is a baby in the cradle!

Histogram information reveals that image is under-exposed


Why Histogram Processing Techniques?
46

7000

6000

5000

4000

3000

2000

1000

0 50 100 150 200 250

Over-exposed image

Histogram information reveals that image is over-exposed


Histogram Processing Techniques (cont.)
47

Histogram of an Image
Histogram of a digital image with gray levels in the range
[0 L-1], is a discrete function
h(rk) = nk
Where
rk : the kth gray level
nk : the number of pixels in the image having gray level rk
h(rk) : histogram of a digital image with gray levels rk
Histogram Processing Techniques (cont.)
48

Histogram Equalization Example

Before
After Equalization
Histogram Processing Techniques (cont.)
49

Histogram Equalization Example (cont..)

After Equalization
Before
Histogram Processing Techniques (cont.)
50

Histogram Equalization Example (cont..)

After Equalization
Before
Histogram Processing Techniques (cont.)
51

A Sample Example of Histogram Equalization


(cont.) No. of pixels
6
5
4
3
2
4x4 image 1
Gray scale = [0,9] 0 1 2 3 4 5 6 7 8 9 Gray level
histogram
Histogram Processing Techniques (cont.)
52

A Sample Example of Histogram Equalization


(cont.)

n
j 0
j

k nj
s
j 0 n
Histogram Processing Techniques (cont.)
53

A Sample Example of Histogram Equalization


(cont.) No. of pixels
3 6 6 3 6
8 3 8 6 5
4
6 3 6 9
3
3 8 3 8 2
1
Output image
Gray scale = [0,9] 0 1 2 3 4 5 6 7 8 9 Gray level
Histogram equalization
MATLAB functions
54

%Histogram Equalization Using Predefined Function


a= imread('pout.tif');
imshow(a)

%% Histogram plot
imhist(a)

%% Histogram equalization
b=histeq(a);
Low contrast image Histogram plot

Equalized image Equalized histogram plot


Image Filtering
Original image
subimage

Statistic parameters
Mean, Median, Mode,
Min, Max, Etc.

Moving
window

Output image
Order Statistics Filters
Median filter

f ( x, y ) median g ( s, t )
( s ,t )S xy

Max filter

f ( x, y ) max g ( s, t ) Reduce dark noise


( s ,t )S xy (pepper noise)

Min filter

f ( x, y ) min g ( s, t ) Reduce bright noise


(salt noise)
( s ,t )S xy

Midpoint filter

f ( x, y ) 1 max g ( s, t ) min g ( s, t )
2 ( s ,t )S xy ( s ,t )S xy
Median Filter: How it works?
A median filter is good for removing impulse, isolated noise

Pepper noise Salt noise


Median

Sorted
Degraded image Moving array
window
Salt noise Filter output

Pepper noise
Normally, impulse noise has high magnitude
and is isolated. When we sort pixels in the
moving window, noise pixels are usually
at the ends of the array.

Therefore, its rare that the noise pixel will be a median value.
Remove salt and pepper noise from images
59

Using predefined functions


% Read image
I = imread('eight.tif');
figure, imshow(I)
% Add salt and pepper noise
J=imnoise(I,'salt & pepper',0.02);
%Use median filter to filter out the noise
K = medfilt2(J);
% Display the result side-by-side
imshowpair(J,K,'montage)
60

Using userdefined functions


% Read image
I = imread('eight.tif');
figure, imshow(I)
% Add salt and pepper noise
b=imnoise(I,'salt & pepper',0.02);
[m n]=size(b);
for i=2:m-1
for j=2:n-1
N=[b(i,j),b(i,j+1),b(i+1,j+1),b(i+1,j),b(i+1,j-
1),b(i,j-1),b(i-1,j-1),a(i-1,j),b(i-1,j+1)]; % neighbourhood
pixels
v=median(N);
b(i,j)=v;
end
end
figure, imshow(b)
Original image

Noisy image Restored image


Linear Blur Model
Spatial domain

x(m,n) h(m,n) y(m,n)


blurring filter

Gaussian blur motion blur 62


Blurring Effect

Gaussian blur

motion blur

63
From [Gonzalez & Woods]
Problem statement

g x, y f x, y hx, y x, y

Goal: To design a restoration filter to minimize error = F f f
The blurring function is called Point spread function

Variations:
h unknown
Constraints on f
Model for f
64
Image Restoration: Deblurring/Deconvolution

x(m,n) h(m,n) y(m,n) g(m,n) ^


x(m,n)
blurring filter deblurring/
deconvolution
filter

Non-blind deblurring/deconvolution
Given: observation y(m,n) and blurring function h(m,n)
Design: g(m,n), such that the distortion between x(m,n) and ^
x(m,n)
is minimized

Blind deblurring/deconvolution
Given: observation y(m,n)
^
Design: g(m,n), such that the distortion between x(m,n) and x(m,n)
is minimized 65
Image blurring with MATLAB
66

Using predefined functions


% Read image
I = imread(cameraman.tif');
figure, imshow(I)

% Add motion blur to the image


H=fspecial(motion', 20, 45);
MotionBlur = imfilter(I,H,'replicate');
imshow(MotionBlur);
% Deblurring using blind deconvolution
INITPSF = ones(size(H));
[J P] = deconvblind(MotionBlur,INITPSF,30);
figure;
imshow(J)
Original image Blur image
Image Deblurring with Wiener Filter
68

I = im2double(imread('cameraman.tif'));
imshow(I); title('Original Image (courtesy of MIT)');
% Add motion blur to the image
LEN = 21; THETA = 11;
PSF = fspecial('motion', LEN, THETA);
blurred = imfilter(I, PSF, 'conv', 'circular');
figure, imshow(blurred)
% simulate additive noise
noise_mean = 0;
noise_var = 0.0001;
blurred_noisy = imnoise(blurred, 'gaussian', ...
noise_mean, noise_var);
figure, imshow(blurred_noisy);title('Simulate Blur and Noise')
%% deblurring with Wiener filter
estimated_nsr = noise_var / var(I(:));
wnr3 = deconvwnr(blurred_noisy, PSF, estimated_nsr);
figure, imshow(wnr3)
title('Restoration of Blurred, Noisy Image Using Estimated
NSR');
Visualizing the Fourier Spectrum using
MATLAB
70

% Create an image
a=zeros(200);
for i=1:size(a,1)
for j=1:size(a,2)
if (i>=41 && i<=160)&&(j>=81 && j<=120)
a(i,j)=1;
end
end
end
figure; imshow(a);title('original image')
% Calculate the DFT
F=fft2(a);
%There are real and imaginary parts to F. Use the abs
function to compute the magnitude of the components.
S=abs(F);
figure;imshow(S,[])title('Fourier spectrum')
Visualizing the Fourier Spectrum using
MATLAB
71

%The zero-frequency coefficient is displayed in the upper


left hand corner. To display it in the center,
%you can use the function fftshift.
Fc=fftshift(F);
figure; imshow(uint8(abs(Fc))); title('Center spectrum')
%In Fourier transforms, high peaks are so high they hide
details. Reduce contrast with the log function.
S2=log(1+abs(Fc));
figure; imshow(S2,[])
title('Spectrum visually enhanced by a log transformation')
Visualizing the Fourier Spectrum using
MATLAB
72
Image Transformation with MATLAB
73

% Read Image
img=imread(cameraman.tif');
subplot(121);
imshow(img);
title('original image)

% Fourier Tranform
fimg=fftshift(fft2(img));
subplot(122);
imshow(abs(fimg)/10000)
title('transformed image')
Image Transformation with MATLAB
74

%% Discrete Cosine Transform


a=imread('lena512.png');
a=rgb2gray(a);
imshow(a)
[m n]=size(a)
%Converting Original Image into DCT coeff. matrix
b=dct2(a);
figure,imshow(uint8(b))
%selecting DCT coefficients
for i=1:m
for j=1:n
if i<=50 && j<=50
c(i,j)=b(i,j);
else
c(i,j)=0;
end
end
end
Image Transformation with MATLAB
75

% Reconstruct the original image from the selected coeff. of


DCT
d=idct2(c);
figure,imshow(uint8(d))

Original Image DCT coefficients Reconstructed image


Image Processing LAB Assignments
Perform Negative, logarithm, and power law transformation on different test
images.
Perform contrast stretching on a test image with the help of piecewise linear
function (y1, y2, y3) shown below
Image Processing LAB Assignments
Perform Zoom-in and Zoom-out operation for lena test image of size
256256.
Write a MATLAB program to rotate an input image GT.jpg by an angle of
67 degrees about the origin.
Write a MATLAB routine to perform scaling by a factor of 2 for the input
image G.bmp.
Given an image of arbitrary histogram, generate an output image that has a
nearly uniform histogram by histogram equalization.
(a) Compute the probability of occurrence of each of the 256 grey level in the image
tire.tif and display the normalized histogram.
(b) From the normalized histogram, compute the Cumulative Distribution function.
(c) Given a grey level r in the input image, map that level to
yr = floor(255 T(r)).
Image Processing MATLAB LAB
Assignments
Perform bit-plane slicing transformation for an test image.
Write a MATLAB program to perform convolution operation of two images.
Consider an input image Cameraman.tif and add Salt and Pepper Noise of
desired density p using imnoise inbuilt function. Perform median filtering on
the noisy image of varying mask size (3 3, 5 5, 7 7 and 9 9) and
observe the filtering performance.
Write a MATLAB program to perform Salt and Pepper noise reduction using
adaptive median filter.
Perform image reconstruction using KL-transform.
Write a MATLAB program to implement Gaussian low-pass filter on
DGT.jpg for a cut off threshold of 50.
Write a MATLAB routine to convert onion.png image from RGB to HSI
color model.
Write a MATLAB program to convert peppers.png image from HSI to RGB
color model.
Image Processing MATLAB LAB
Assignments
Image compression using DCT.
(a) Load an image (say I)
(b) Divide I into 88 blocks and compute DCT for each block.
(c) Retain 25% of highest coefficient, with respect to magnitude, in
each block and set other coefficients to zero.
(d) Find inverse DCT of each block and display the reconstructed
image.
(e) Compute the reconstruction error.
Image compression using DCT with elimination of low frequency
components.
(a) Load an image (say I)
(b) Divide I into 8 8 blocks and compute DCT for each block.
(c) Set the low frequency DCT components in each block to zero.
(d) Compute the inverse DCT for each of the blocks and display the
image.
(e) Compute the reconstruction error.
Image Processing MATLAB LAB
Assignments
Load the images mandrill and clown. Make these unequal sized images
equal. Take their Fourier transform. Swap the phase spectra of the Fourier
transform of the images with each other while keeping their magnitude
spectra unchanged and take the inverse Fourier transforms. Display the
resulting images. Observe the changes.
Image Processing Projects

1. Image Segmentation with Grey Level Thresholding.


(a) Read the Jacket image and find number of regions in it (say n).
(b) Plot its histogram and determine the threshold values such that the
image will be segmented into n regions.
(c) Display the resulting segmented image.
(d) Repeat the above steps for other images like Landsat, Building, and
Cameraman.
Image Processing Projects

2. Image Segmentation with K Means Clustering Algorithm.


Let an image be segmented into K clusters. Perform the following steps:
(a) Randomly select K pixels and let their intensities be initial K means for
the K clusters.
(b) With the help of minimum Euclidean distance metric assign the
remaining pixels to its nearest cluster.
(c) Update the mean of each cluster.
(d) Repeat the steps (b) and (c) until there is no change in the K cluster
means.
(e) Display the segmented image.
Image Processing Projects

3. Salt and pepper noise filtering using weighted median and centre
weighted median filter. Find the weight vector using real coded GA to
maximize the quality of the image in terms of PSNR.
Image Processing Projects
4. Compare the quality of the image using PSNR and SSIM for compression of
a bitmap image to jpg and jpg2000.

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