0% found this document useful (0 votes)
784 views30 pages

Digital Image Processing Lab

This document provides an overview of basic image processing concepts and techniques in MATLAB. It introduces how images are represented as matrices in MATLAB and describes common image processing functions in the Image Processing Toolbox like loading, viewing, cropping and arithmetic operations on images. It also explains MATLAB programming concepts like M-files, functions, and flow control structures like if-else, for loops, while loops and switch-case that are useful for writing image processing scripts and functions. A set of exercises are provided to practice applying these basic image processing and programming techniques.

Uploaded by

Sami Zama
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
784 views30 pages

Digital Image Processing Lab

This document provides an overview of basic image processing concepts and techniques in MATLAB. It introduces how images are represented as matrices in MATLAB and describes common image processing functions in the Image Processing Toolbox like loading, viewing, cropping and arithmetic operations on images. It also explains MATLAB programming concepts like M-files, functions, and flow control structures like if-else, for loops, while loops and switch-case that are useful for writing image processing scripts and functions. A set of exercises are provided to practice applying these basic image processing and programming techniques.

Uploaded by

Sami Zama
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 30

Practical File

DIGITAL IMAGE PROCESSING LAB

SUBMITTED TOMr. Ashish Jain

SUBMITTED BYStudent Name Roll No.

INDEX
S.No.
1. Date Topic INTRODUCTION TO IMAGE PROCESSING
1.1 Images as Matrices 1.2 Image Processing Toolbox(IMT) Basics 1.3 Arithmetic Operations 2.1 M-Files and Functions 2.2 Flow Control 2.3 Loop Vectorization and Preallocation 3.1 Solarization Effects 3.2 Ripple Effect 3.3 Oil-Painting Effects

Remarks

2.

BASIC IMAGE PROCESSING


1. Thresholding 2. Gaussian Filter 3. Canny Edge Detector

1 Introduction to Image Processing in Matlab


1.1 Images as Matrices
In MATLAB, most images are stored as two-dimensional matrices, in which each element of the matrix corresponds to a single pixel in the image. For example, an image composed of 200 rows and 300 columns of pixels would be stored in MATLAB as an M-by-N matrix of 200-by-300 matrix elements.

Fig.1 : [Left] the usual image coordinates. [Right] the matrix coordinates of Matlab.

However we note that unlike the coordinate convention used in many textbooks,the matrixcoordinates in MATLAB originate at (r,c) = (1,1) instead of (x,y) = (0,0). Furthermore, some images, such as truecolor RGB images, require a three-dimensional matrix, where the first component matrix in the third dimension represents the red pixel intensities,the second component matrix represents the green pixel intensities, and the third component matrix represents the blue pixel intensities.

1.2 Image processing Toolbox (IMT) Basics


1. Load the image f =imread (lena.gif); 2. Convert to type double f = double(f); 3. Convert to grey-scale f = (f(:,:,1)+f(:,:,2)+f(:,:,3))/3; or you can use rgbgray which gives a slightly different result since it converts to a luminance rather than an intensity image, youll learn about this in the lecture on color imaging.
Convert from [0,255] to [0,1]

im_grey = im_grey/255;

4.view an image
use either imshow(f) or imagesc(),

5.set the axis for an image


use imagesc and then axis image;

6.Axis labeling can be turned on and off by


axis on; axis off;

7.crop an image
using imcrop(im_grey);

8.To see the information of image


imfinfo(lena.gif)

9.colormap A colormap is an M by3 matrix of RGB-tuples, where each tuple specifies a color by the red, green and blue component values in the RGB color model. False colormap can be used to enhance the presentation of an image. In this example, we will make use of it to investigate the uniformity of the image background. Estimating and subtracting an image background are two preliminary steps often used for object detection processing.
g = imread(rice.tif); imshow(g) , colormap(JET) , figure, imshow(g) pixval on

Fig.2 : [a] the rice.tif image. [b] the image with the JET colormap.

In the rice.tif image, the background illumination is brighter in the center of the image than at the

bottom. The variation can be clearly visualized by changing the colormap property as illustrated in Fig.2. Meanwhile, the pixval command installs a bar at the bottom of the figure which interactively displays the pixel coordinates and value for which ever pixel the cursor is currently over. 10. add two images:

f = imread(rose.gif); g = imread(rice.gif) figure, imshow(imadd(f,g))

In this example, pixels in y are computed by adding corresponding pixel in f and g: y = f + g Suppose the output image of 8-bit unsigned integer datatype, so the following range requirement applies: y = f + g y = 255 if (f + g) > 255 and y = 0 if (f + g) < 0.

1.3 Arithmetic Operations


Image arithmetic deals with the standard arithmetic operations, such as addition, subtraction, multiplication, and division, on image pixels. Image arithmetic has many uses in the image processing both as a preliminary step in complex operations and by itself. Addition: I(x,y) = min[I1(x,y)+I2(x,y), Imax] Subtraction: I(x,y) = max[I1(x,y)-I2(x,y), Imin] Division: I(x,y) = I1(x,y)/I2(x,y)where I2(x,y) <> 0 Sensibly I2(x,y) may take the form of constant: Addition: I(x,y) = min[I1(x,y) + C, Imax] Subtraction: I(x,y) = max[I1(x,y) - C, Imin] Division: I(x,y) = I1(x,y)/C where C <> 0 The formulation can also be extended to obtain the negative of an image: Complement: I(x,y)= Imax-I1(x,y) Note I(x,y) are in the range of values permitted by its data type. For example if I(x,y) is an 8-bit image, the pixel values are mapped only to the range of 0-255. Overflow values i.e.

I(X,Y) > 255 and I(X,Y) < 0 will be clipped at 255 and 0 respectively IPT offers support for several arithmetic operations. To browse the list of IPT function, type: >> help images

imabsdiff
imadd imcomplement imdivide imlincomb immultiply imsubtract

Compute absolute difference of two images. Add two images, or add constant to image. Complement image. Divide two images, or divide image by constant Compute linear combination of image. Multiply two images, or multiply image by constant. Subtract two images, or subtract constant from image.

Among others, you should notice the following arithmetic functions:

1.4 Exercises
Exercises1.1 Read the rose.tif and rice.tif images into variable f and g. a) Try various false colormaps on the two images. b) Checking pixels values with pixval on the two images with and without the false colormaps. Any changes? c) Using imrotate, rotate f by 45 counter clockwise. Save the result as fllc.tif. d) Using imresize, reduce f by half, then enlarge the result by double, write the result using imwrite as flld.tif. Compare the original image with the result obtained, what happened? e) Compute grayslice (image ,n) where n=2,4,16 and 32 for the two images. Comments? f) Write the two images as jpeg files. Exercise 1.2 Using f and g in Exercise 1.1, compare and comment the following: a) Computes a= f-g and b= g-f using imsubtract. b) Computes c= f+g using imadd, where c is of unit 16. Compare the result with image illustrate in Fig.3[c]. c) Compute d= (f+g)/2 and e= imlincomb(.5,f,.5,g). d) Compute i= imcomplement(f). Exercise 1.3 Using f and g in Exercise 1.1, create a black and white{0,1}mask image of the same size.Crop f and g with the mask.(Hint: using AND operator)

2.1 M-Files and Functions


Programming in MATLAB is facilitated by M-Files (named after its .m file extension). There are two types of M-Files that you can write: script and functions. The former operates like a shell script, while the latter are program routines which act like standard functions in MATLAB that accept input arguments and return output arguments. M-File functions are used to extend the capabilities of MATLAB and IPT to address user specific problems. function y = average1(x) % AVERAGE1 mean of vector elements. % AVERAGE1(X) computes the mean of X vector elements. % Non-vector input results in error. [m,n] = size(x); If ( ~ ( (m = = 1) | (n = = 1)) | (m = = 1 & n = = 1) ) error (Input must be a vector) end y = sum(x) / length(x) ; Save the files as average1.m. To call the average1 function, enter: >> z = 1:99; >> average1 (z) Ans = 50 Each M-File function operates in its own workspace context that is separate from the MATLAB base workspace. Therefore, the variables that you pass to a function must be in the calling context. If a variable is meant to be accessible in more than one workspace context, it should be explicitly defined as a global variable.

2.2 Flow Control


Statement
If for while break continue switch return try, catch

Description
if together with else and else if, executes a group of statements based on specific logical condition. Executes a group of statements a fixed(specified) number of times. Executes a group of statements an indefinite number of times based on a specific logical condition. Terminates the execution of the for or while loop. Passes control to the next iteration of a for or while loop skipping an remaining statement in the body of the loop. Switch, together with case and otherwise, executes different groups of statements, depending on a specified value or string. Causes execution to return to the invoking function. Changes flow control if an error is detected during execution.

To control the flow of operations, MATLAB provides a number of constructs:

if, else if and else


The if statement evaluates a logical expression and executes a group of statement when the expression is true. The optional else if and else constructs provide for the execution of alternate group of statements. An end construct terminates the if group of statements. Example function av = average2(A) % AVERAGE2 Computes the average value of an array. % AV = AVERAGE2(A) Computes the average value of input array, A which must be a 1-D or 2-D array % Check the validity of the input. (Keep in mind that a 1-D array is a special case of a 2-D array.) if ndims (A) > 2 error (The dimensions of the input cannot exceed 2.) end % Computes the average2 av = sum(A(:))/length(A(:));

for
The for statement is a loop construct used to repeat a group of statements for a predetermined number of times. A matching end delineates the statements. Example f = imread(rose.tif); for q = 0:5:100 filename = sprint(series_%3d . jpg, q); imwrite (f, filename, quality, q); end Example function s = subim(f, m, n, rx, cy) % SUBIM Extracts a subimage, s, from a given image, f. % The subimage is of size m-by-n, and the coordinates % of its top, left corner are (rx , cy) S = zeros (m, n); rowhigh = rx+m-1; colhigh = cy+ n-1; xcount= 0; for r = rx : rowhigh xcount = xcount + 1; ycount=0; for c = cy: colhigh ycount = ycount +1;

S(xcount,ycount)=f(r,c); end end

While
The while statement is another loop construct which repeats a group of statement for as long as the expression controlling the loop is true. A matching end delineates the statements.

Line counter.m
fid=fopen(average2.m,r) count = 0; while ~feof(fid) line =fgetl(fid); if isempty(line)|strncmp(line,%,1) continue end count =count + 1 ; end disp(sprintf(%d lines,count));

Switch and case


The switch statement executes groups of statement based on the value of a variable or expression. The keyword case and otherwise delineate the groups. Only the first matching case is executed. There must always be an end to match the switch. Switch input_number case 1 disp(negative one); case 0 disp(zero); case 1 disp(positive one); otherwise disp(other value); end

2.3 Loop Vectorization and preallocation


MATLAB is optimized for array computation,thus MATLAB programs can be writtento run faster if the use of for or while loop is supplanted with matrix operation.An example below illustrates the loop vectorization process: x = .01; for k =1:1001 y(k) = log10(x); x = x + .01; end A vectorized version of the same code is given by: x = .01: .01 : 10; y = log10(x); However, loop vectorization is not always obvious for more complicated algorithms. In the case that loop vectorization cannot be realized, we can make our for loops run faster by preallocating any vector or arrays in which output results are stored. r = zeros (32, 1); for n = 1.32 r(n) = rank(magic(n)); end For example, the code above use the function zeros to preallocate the vector created in the for loop. This makes the for loop execute significantly faster. Without preallocation, MATLAB enlarges the r vector by one element each time through the loop.

Write a mat lab function Lab1.m with a sub-function find-moment. The specifications of these functions follow. Function lab1; This function % - loads an image, % - display the image and its intensity histogram, % - converts the image to binary via a threshold % - calculates the area, centre of mass and orientation of the binary object. % - displays the binary image with its centre of mass % - indicated and a line showing its orientation. % - print out the area ,centre of mass , and orientation function[moments ,orientation] =find_moments(I_bin); % calculates the 0th ,1st , and 2nd moments and orientation of

% % % % % %

the binary image I_bin and returns: moment .M = 0th moment (area) moment .Mx = 1st moment (x-cordinate of centroid ) moment .My = 1st moment (y-cordinate of centroid ) orientation = orientation

3-Creating Image effects


We create a mask image and use it along with a boolean operator to crop the rose image. Suppose a mask of the keyhole shape is chosen, the result image shall somewhat look stylistic. In fact many images editing effect can be created by simple image arithmetic and straightforward matrix manipulations.

3.1 Solarization Effects


Solarization is a photographic effect in which the image appears partly positive and partly negative. A simple solarization effect can be created by taking the complements of pixels in an image whose intensity values are less than 128. I(x,y) = I(x,y) if I(x,y)>128 , I(x,y) = 255-I(x,y) if I(x,y)<=128.

[a]

[b]

3.2 Ripple Effects


Ripple effects which stimulate the reflection of an object on an surface of a pond or an object seen through wavy glasses can be created by pixilated effects obtained by adding and subtracting moduli. >> x=1 : 16 ; >> x + mod(x , 4) Ans = 2 4 6 4 6 8 10 8 10 12 14 12 14 16 18 16

[a]

[b]

3.3 Oil Painting Effects


An oil painting effect can be created by taking the pixel values most frequently occurred in a small pixel neighborhood.

[a]

[b]

2. Basic Image Processing


These are MATLAB programmed demos showing some basic image processing filters : thresholding, Gaussian Filter and Canny Edge detector. MATLAB codes and corresponding results of each filter are given below. TO run, just save them as .m files or functions. All the images in the demos are grey images.

1. Thresholding Demos Algorithm and Matlab Codes 2. Gaussian Filter Demos Algorithm and Matlab Codes 3. Canny Edge Detection Demos Algorithm and Matlab Codes

Thresholding

Image Thresholding
This demo shows how a image looks like after thresholding. The percentage of the thresholding means the threshold level between the maximum and minimum indesity of the initial image. Thresholding is a way to get rid of the effect of noise and to improve the signal-noise ratio. That is, it is a way to keep the significant imformation of the image while get rid of the unimportant part (under the condition that you choose a plausible thresholding level). In the Canny edge detector part, you will see that, before thinning, we first do some thresholding. You are encouraged to do thinning without thresholding and to see what is the advantage of thresholding.

lena.gif

10% threshold

20% threshold

30% threshold

Image Thresholding Matlab Codes


This program show the effect of thresholding. The output are four subfigures shown in the same figure:

Subfigure 1: The initial "lena" Subfigure 2: Threshold level is one alfa Subfigure 3: Threshold level is two alfa Subfigure 4: Threshold level is three alfa

The MATLAB codes: %%%%%%%%%%%%% The main.m file %%%%%%%%%%%%%% clear; % Threshold level parameter alfa: alfa=0.1;% less than 1/3 [x,map]=gifread('lena.gif'); ix=ind2gray(x,map); I_max=max(max(ix)); I_min=min(min(ix)); level1=alfa*(I_max-I_min)+I_min; level2=2*level1; level3=3*level1; thix1=max(ix,level1.*ones(size(ix))); thix2=max(ix,level2.*ones(size(ix))); thix3=max(ix,level3.*ones(size(ix))); figure(1);colormap(gray); subplot(2,2,1);imagesc(ix);title('lena'); subplot(2,2,2);imagesc(thix1);title('threshold one alfa'); subplot(2,2,3);imagesc(thix2);title('threshold two alfa'); subplot(2,2,4);imagesc(thix3);title('threshold three alfa'); %%%%%%%%%%%%% End of the main.m file %%%%%%%%%%%%%%

Gaussain Filter
Gaussian function demos
These demos show the basic effects of the (2D) Gaussian filter: smoothing the image and wiping off the noise. Generally speaking, for a noise-affected image, smoothing it by Gaussian function is the first thing to do before any other further processing, such as edge detection. The effectiveness of the gaussian function is different for different choices of the standard deviation sigma of the Gaussian filter. You can see this from the following demos.

Smoothing nonnoisy image


lena.gif filtered with sigma = 3 filtered with sigma = 1

Noise cancelling
noisy lena filtered with sigma = 3 filtered with sigma =1

(Noise is generated by matlab function 0.3*randn(512))

Gaussian filter study matlab codes


This program show the effect of Gaussian filter. The output are four subfigures shown in the same figure:

Subfigure 1: The initial noise free "lena" Subfigure 2: The noisy "lena" Subfigure 3: Filtered the initial "lena" Subfigure 4: Filtered the noisy "lena" The matlab codes: %%%%%%%%%%%%% The main.m file %%%%%%%%%%%%%%% clear; % Parameters of the Gaussian filter: n1=10;sigma1=3;n2=10;sigma2=3;theta1=0; % The amplitude of the noise: noise=0.1; [w,map]=gifread('lena.gif'); x=ind2gray(w,map); filter1=d2gauss(n1,sigma1,n2,sigma2,theta); x_rand=noise*randn(size(x)); y=x+x_rand; f1=conv2(x,filter1,'same'); rf1=conv2(y,filter1,'same'); figure(1); subplot(2,2,1);imagesc(x); subplot(2,2,2);imagesc(y); subplot(2,2,3);imagesc(f1); subplot(2,2,4);imagesc(rf1); colormap(gray); %%%%%%%%%%%%%% End of the main.m file %%%%%%%%%%%%%%% %%%%%%% The functions used in the main.m file %%%%%%% % Function "d2gauss.m": % This function returns a 2D Gaussian filter with size n1*n2; theta is % the angle that the filter rotated counter clockwise; and sigma1 and sigma2 % are the standard deviation of the gaussian functions. function h = d2gauss(n1,std1,n2,std2,theta) r=[cos(theta) -sin(theta); sin(theta) cos(theta)]; for i = 1 : n2 for j = 1 : n1

u = r * [j-(n1+1)/2 i-(n2+1)/2]'; h(i,j) = gauss(u(1),std1)*gauss(u(2),std2); end end h = h / sqrt(sum(sum(h.*h))); % Function "gauss.m": function y = gauss(x,std) y = exp(-x^2/(2*std^2)) / (std*sqrt(2*pi)); %%%%%%%%%%%%%% end of the functions %%%%%%%%%%%%%%%%

Canny Edge Detector Canny edge detector demos


There are some results of applying Canny edge detector to real image (The black and white image "lena.gif" we used here was obtained by translating from a color lena.tiff using matlab. So it might not be the standard BW "lena".) The thresholding parameter alfa is fix as 0.1. The size of the filters is also fixed as 10*10. These images are all gray images though they might seem a little strange in your browser. To see them more clearly, just click these images and you will find the difference especially from the "result images", that is, the titled "after thinning" ones. The safe way to see the correct display of these images is to grab these images and show them by "xv" or "matlab". While, you are encouraged to use the given matlab codes and get these images in matlab by yourself. Try to change the parameters to get more sense about how these parameters affect the edge detection.

The results of choosing the standard deviation sigma of the edge detectors as 3.
lena.gif vertical edges horizontal edges

norm of the gradient

after thresholding

after thinning

The results of choosing the standard deviation sigma of the edge detectors as 1.
lena.gif vertical edges horizontal edges

norm of the gradient

after thresholding

after thinning

Canny edge detector algorithm matlab codes


This part gives the algorithm of Canny edge detector. The outputs are six subfigures shown in the same figure:

Subfigure 1: The initial "lena" Subfigure 2: Edge detection along X-axis direction Subfigure 3: Edge detection along Y-axis direction Subfigure 4: The Norm of the image gradient Subfigure 5: The Norm of the gradient after thresholding Subfigure 6: The edges detected by thinning

The matlab codes: %%%%%%%%%%%%% The main.m file %%%%%%%%%%%%%%% clear; % The algorithm parameters: % 1. Parameters of edge detecting filters: % X-axis direction filter: Nx1=10;Sigmax1=1;Nx2=10;Sigmax2=1;Theta1=pi/2; % Y-axis direction filter: Ny1=10;Sigmay1=1;Ny2=10;Sigmay2=1;Theta2=0; % 2. The thresholding parameter alfa: alfa=0.1; % Get the initial image lena.gif [x,map]=gifread('lena.gif'); w=ind2gray(x,map); figure(1);colormap(gray); subplot(3,2,1); imagesc(w,200); title('Image: lena.gif'); % X-axis direction edge detection subplot(3,2,2); filterx=d2dgauss(Nx1,Sigmax1,Nx2,Sigmax2,Theta1); Ix= conv2(w,filterx,'same'); imagesc(Ix); title('Ix'); % Y-axis direction edge detection subplot(3,2,3) filtery=d2dgauss(Ny1,Sigmay1,Ny2,Sigmay2,Theta2); Iy=conv2(w,filtery,'same'); imagesc(Iy); title('Iy'); % Norm of the gradient (Combining the X and Y directional

derivatives) subplot(3,2,4); NVI=sqrt(Ix.*Ix+Iy.*Iy); imagesc(NVI); title('Norm of Gradient'); % Thresholding I_max=max(max(NVI)); I_min=min(min(NVI)); level=alfa*(I_max-I_min)+I_min; subplot(3,2,5); Ibw=max(NVI,level.*ones(size(NVI))); imagesc(Ibw); title('After Thresholding'); % Thinning (Using interpolation to find the pixels where the norms of % gradient are local maximum.) subplot(3,2,6); [n,m]=size(Ibw); for i=2:n-1, for j=2:m-1, if Ibw(i,j) > level, X=[-1,0,+1;-1,0,+1;-1,0,+1]; Y=[-1,-1,-1;0,0,0;+1,+1,+1]; Z=[Ibw(i-1,j-1),Ibw(i-1,j),Ibw(i-1,j+1); Ibw(i,j-1),Ibw(i,j),Ibw(i,j+1); Ibw(i+1,j-1),Ibw(i+1,j),Ibw(i+1,j+1)]; XI=[Ix(i,j)/NVI(i,j), -Ix(i,j)/NVI(i,j)]; YI=[Iy(i,j)/NVI(i,j), -Iy(i,j)/NVI(i,j)]; ZI=interp2(X,Y,Z,XI,YI); if Ibw(i,j) >= ZI(1) & Ibw(i,j) >= ZI(2) I_temp(i,j)=I_max; else I_temp(i,j)=I_min; end else I_temp(i,j)=I_min; end end end imagesc(I_temp); title('After Thinning'); colormap(gray); %%%%%%%%%%%%%% End of the main.m file %%%%%%%%%%%%%%%

%%%%%%% The functions used in the main.m file %%%%%%% % Function "d2dgauss.m": % This function returns a 2D edge detector (first order derivative % of 2D Gaussian function) with size n1*n2; theta is the angle that % the detector rotated counter clockwise; and sigma1 and sigma2 are the % standard deviation of the gaussian functions. function h = d2dgauss(n1,sigma1,n2,sigma2,theta) r=[cos(theta) -sin(theta); sin(theta) cos(theta)]; for i = 1 : n2 for j = 1 : n1 u = r * [j-(n1+1)/2 i-(n2+1)/2]'; h(i,j) = gauss(u(1),sigma1)*dgauss(u(2),sigma2); end end h = h / sqrt(sum(sum(abs(h).*abs(h)))); % Function "gauss.m": function y = gauss(x,std) y = exp(-x^2/(2*std^2)) / (std*sqrt(2*pi)); % Function "dgauss.m"(first order derivative of gauss function): function y = dgauss(x,std) y = -x * gauss(x,std) / std^2; %%%%%%%%%%%%%% end of the functions %%%%%%%%%%%%%

Canny Edge Detector Algorithm Matlab Codes


This part gives the algorithm of Canny edge detector.The outputs are six subfigures shown in the same figure: Subfigure 1:The initial lena Subfigure 2:Edge detection along x-axis Subfigure 3:Edge detection along y-axis Subfigure 4:The norm of image gradient Subfigure 5:The norm of gradient after thresholding Subfigure 6:The edge detected by thinning

The matlab codes: %%%%%%%%%% The main .m file %%%%%%%%% Clear; % The algorithm parameters; % 1.Parameter of edge detecting filters; Nx1=10;Sigmax1=1;Nx2=10;SigmaX2=1;Theta1=pi/2; y-axis direction filter; Ny1=10;Sigmay1=1;Ny2=10;SigmaY2=1;Theta2=0; % 2.the thresholding parameter alfa; alfa=0.1; %Get the initial image lena.gif [x,map]=gifread(lena.gif); W=ind2gray(x,map); figure(1);colormap(gray); subplot(3,2,1); imagesc(w,200); title(image:lena.gif); %x-axis direction adge detection Subplot(3,2,2); Filterx=d2dgauss(Nx1,Sigmax1,Nx2,SigmaX2,Theta1); Ix=conv2(w,filterx,same); Imagesc(Ix); Title(Ix); %y-axis direction adge detection Subplot(3,2,3); Filtery=d2dgauss(Nx1,Sigmax1,Ny2,Sigmay2,Theta2); Iy=conv2(w,filtery,same);

Imagesc(Iy); Title(Iy);
%Norm of the gradient (Combining the x and y directional derivatives ) Subplot(3,2,4); NVI=sqrt(Ix.*Ix+Iy.*Iy); Imagesc(NVI);

title ( Norm of Gradient ); % Thresholding I_max=max(max(NVI)) ; I_min=min(min(NVI)) ; Level=alfa*(I_max-I_min) + I_min ; Subplot (3,2,5); Ibw=max(NVI,level.*ones(size(NVI) ) ); imagesc(Ibw); title ( After Thresholding ); % Thinning (Using interpolation to find the pixels where the norms of % gradient are local maximum.) Subplot (3,2,6); [n,m]=size (Ibw); for i = 2 : n-1 , for j = 2 : m-1, if Ibw ( i , j) > level , X = [-1 , 0 ,+1 ; -1 ,0 , +1; -1 , 0 , +1] ; Y =[-1 ,-1 , -1 ; 0 ,0 ,0 ; +1 , +1 , +1] ; Z =[Ibw (i-1, j-1), Ibw ( i-1 , j) , Ibw (i - 1, j + 1) ; Ibw (i , j - 1) , Ibw (i , j), Ibw ( i , j+1) ; Ibw (i+1,j-1) , Ibw (i+1,j) , Ibw( i+1, j+1 ) ] ; XI = [ Ix (i ,j) / NVI (i , j) , -Ix (i, j) / NVI( i , j) ] ; YI= [ Iy (i , j) / NVI (i , j) , - Iy ( i ,j) / NVI ( i , j) ] ; ZI=interp2 (X , Y, Z , XI , YI ) ; if Ibw (i , j) >= ZI (1) & Ibw (i , j) >= ZI (2) I_temp (i , j) = I_max ; else I_temp ( i , j ) = I_ min; end .end end imagesc (I_temp) ; titile ( After Thinning ) ; colormap (gray) ; %%%%%%%%%%%%%%% End of the main.m file %%%%%%%%%%%%%%% % Function d2dgauss.m ; % This function returns a 2d edge detector (first order derivative % of 2d Gaussian function) with size n1*n2 ; theta is the angle that % the detector rotated counter clockwise ; and s (1)igma1 and sigma2 are the % standard deviation of the Gaussian functions. Function h = d2dgauss (n1, sigma1,n2 , sigma2,theta)

r= [cos (theta) sin(theta) ; sin (theta) cos(theta) ; for i= 1 : n2 for j = 1 : n1 u = r * [j- (n1+1)/2 i-(n2+1)/2] ; h (i,j) = gauss ( u (1) , sigma1) * dgauss (u (2) , sigma2 ) ; end end h = h / sqrt (sum (abs (h) . * abs (h) ) ) ) ; % Function gauss.m: Function y = gauss ( s, std ) y =exp (-x ^2/ (2 * std 2) ) / (std * sqrt (2 * pi) ) ) ; % Function dgauss.m (first order derivative of gauss function ) : Function y = dgauss (x , std) y = -x * gauss (x , std) / std^2 ; %%%%%%%%%%%%% end of the functions %%%%%%%%%%%%%

Exercise Solutions
Exercise 1: a) Try various false colormaps on the two images. Sol: f = imread(rose.tif); g = imread(rice.tif); imshow(f), colormap(HSV), figure, imshow(f) imshow(f), colormap(COOL), figure, imshow(f) imshow(f), colormap(HOT), figure, imshow(f) imshow(f), colormap(SUMMER), figure, imshow(f) imshow(f), colormap(GRAY), figure, imshow(f)

imshow(g), colormap(HSV), figure, imshow(g) imshow(g), colormap(COOL), figure, imshow(g) imshow(g), colormap(HOT), figure, imshow(g) imshow(g), colormap(SUMMER), figure, imshow(g) imshow(g), colormap(GRAY), figure, imshow(g)

b) Checking pixel values with pixval on the two images with and without the false colormaps. Sol: f = imread(rose.tif); g = imread(rice.tif); imshow(f), colormap(JET), figure, imshow(f) pixval on imshow(f), colormap(HSV), figure, imshow(f) pixval on imshow(g), colormap(JET), figure, imshow(g) pixval on imshow(g), colormap(HSV), figure, imshow(g) pixval on

c) Using imrotate, rotate f by 45 counter clockwise, Save the result as f11c.tif. Sol: //Create M file f= imread(rose.tif); b = imrotate(f,45,nearest); imshow(b) save faac.tif;

d) Using imresize, reduce f by half, then enlarge the result by double, write the result using imwrite as f11d.tif. Sol: // Create a M file k = imread(rice.gif); b = imresize(k,.5); c = imresize(b,2); imshow(b) imwrite(c,f11d.tif);

e) Compute grayslice(image,n) where n=2,4,16 and 32 for the two images. Sol: f = imread(rose.tif); X = grayslice(f,2); imview(f) imview(X,jet(2))

Y = grayslice(f,4); imview(f) imview(Y,jet(4))

Z = grayslice(f,16); imview(f) imview(Z,jet(16))

U = grayslice(f,32); imview(f) imview(U,jet(32))

g = imread(rice.tif); a = grayslice(g,2); imview(g) imview(a,jet(2))

b = grayslice(g,4);

imview(g) imview(b,jet(4))

c = grayslice(g,16); imview(g) imview(c,jet(16))

d = grayslice(g,32); imview(g) imview(d,jet(32))

f) Write the two images as jpeg files. Sol: f = imread(rose.tif); g = imread(rice,tif); imwrite(f,rose.tif); imwrite(g,rice.tif);

Exercise 2: a) Compute a= f - g and b = g - f using imsubtract Sol: f = imread(rose.tif); g = imread(rice,tif); a = imsubtract(f,g); b = imsubtract(g,f);

b) Compute c = f + g using imadd, where c is of uint16 Sol: Double c; f = imread(rose.tif); g = imread(rice.tif); c = imadd(f,g);

c) Compute d = (f + g)/2 and e = imlincomb(.5,f,.5,g). Sol: f = imread(rose.tif); g = imread(rice.tif); h = imadd(f,g); d = (h(:,:,1)+h((:,:,2)+h((:,:,3))/2; e = imlincomb(.5,f,.5,g);

d) Compute i = imcomplement(f) Sol: f = imread(rose.tif); i = imcomplement(f);

Exercise 3: a) Create a black and white [0,1] mask image of the same size Sol: h = imread(); h=(h(:,:,1)+ h(:,:,2)+ h(:,:,3))/3; imshow(h);

You might also like