Lets Learn together... Happy Reading

" Two roads diverged in a wood, and I,
I took the one less traveled by,
And that has made all the difference "-Robert Frost

Recent Posts

Sobel Edge Detection - Part 2

In Edge Detection- fundamentals, we have seen how the first and second order derivatives are used in finding the edge strength. Now lets see another version of sobel edge detection.

Basic Steps followed in Sobel Edge Detection:

1.       Obtain the gradient of the image.
2.       Find the magnitude
3.       Threshold the gradient image.


SOBEL EDGE DETECTION USING ‘edge’ FUNCTION:

%Input Image
A=imread('coins.png');

%Image obtained using MATLAB function 'edge'
[E,th]=edge(A,'sobel','nothinning');
figure,imshow(E);title('Image obtained using MATLAB function')




Edge Detection without using the 'edge' function: 

MATLAB CODE:

%Input Image
A=imread('coins.png');

%Preallocate the matrices with zeros
I=zeros(size(A));


%Filter Masks
F1=[-1 0 1;-2 0 2; -1 0 1];
F2=[-1 -2 -1;0 0 0; 1 2 1];

A=double(A);


for i=1:size(A,1)-2
    for j=1:size(A,2)-2
        %Gradient operations
        Gx=sum(sum(F1.*A(i:i+2,j:j+2)));
        Gy=sum(sum(F2.*A(i:i+2,j:j+2)));
               
        %Magnitude of vector
         I(i+1,j+1)=sqrt(Gx.^2+Gy.^2);
       
    end
end


I=uint8(I);
figure,imshow(I);title('Filtered Image');



%Define a threshold value
Thresh=210;
B=max(I,Thresh);
B(B==round(Thresh))=0;

B=im2bw(B);
figure,imshow(B);title('Edge detected Image');



EXPLANATION:

1.       Read the image
2.       Convert the image to double
3.       Use the mask F1 for x direction and F2 for y direction and obtain the gradient of the image.
4.       Find the magnitude of the vector.
5.       Since we need 3x3 image pixels, the border pixels are not considered, and so starting from the pixel (2, 2) the edge detection process starts.
       %Magnitude of vector
    I(i+1,j+1)=sqrt(Gx.^2+Gy.^2);
    When i=1 and j =1, then Image I pixel position will be I(2,2).Thus we are not considering the borders.
Example:

    In the for loop 2 is subtracted.
"
for i=1:size(A,1)-2
    for j=1:size(A,2)-2 "
     The filter mask is 3x3, so the last position to be processed in our example is I(3,3).And normally it will be I(size(A,1)-2,size(A,2)-2). Thus the borders are left.

Example :
               


6.       Threshold the image
7.       Display the logical image


Advantage:

1. Sobel masks perform better noise suppression.

2. Image smoothing


Disadvantage:

1.       Diagonal direction points are not preserved always.

like button Like "IMAGE PROCESSING" page

Image Sharpening using second order derivative –(Laplacian)


Prerequisite: Read EdgeDetection- fundamentals

The derivative operator Laplacian for an Image is defined as



For X-direction,

For Y-direction,


By substituting, Equations in Fig.B and Fig.C in Fig.A, we obtain the following equation







The equation  represented in terms of Mask:
0
1
0
1
-4
1
0
1
0

When the diagonals also considered then the equation becomes,



The Mask representation of the above equation,
1
1
1
1
-8
1
1
1
1

Now let’s discuss further how image sharpening is done using Laplacian.

Equation:
Where f(x,y)  is the input image
              g(x,y) is the sharpened image and
               c= -1 for the above mentioned filter masks.(fig.D and fig.E)

MATLAB CODE:

%Input Image
A=imread('coins.png');
figure,imshow(A);



%Preallocate the matrices with zeros
I1=A;
I=zeros(size(A));
I2=zeros(size(A));

%Filter Masks
F1=[0 1 0;1 -4 1; 0 1 0];
F2=[1 1 1;1 -8 1; 1 1 1];

%Padarray with zeros
A=padarray(A,[1,1]);
A=double(A);

%Implementation of the equation in Fig.D
for i=1:size(A,1)-2
    for j=1:size(A,2)-2
       
        I(i,j)=sum(sum(F1.*A(i:i+2,j:j+2)));
       
    end
end

I=uint8(I);
figure,imshow(I);title('Filtered Image');









The Laplacian derivative equation has produced grayish edge lines and other areas are made dark(background)

%Sharpenend Image
%Refer Equation in Fig.F
B=I1-I;
figure,imshow(B);title('Sharpened Image');




The Filter Image is combined with the Original input image thus the background is preserved and the sharpened image is obtained .



For a Filter Mask that includes Diagonal,


1
1
1
1
-8
1
1
1
1

Filtered Image:


Sharpened Image:



like button Like "IMAGE PROCESSING" page

EDGE DETECTION – FUNDAMENTALS


The derivatives of a digital function are defined in terms of differences.
The above statement made me to analyze about derivatives and how it is used for edge detection.  The first time when I came across the edge detection operation [Example: edge(Image,’sobel’)], I wondered how it worked. 
Consider a single dimensional array,
A =
5
4
3
2
2
2
2
8
8
8
6
6
5
4
0

MATLAB CODE:

x=1:15;
y=[5 4 3 2 2 2 2 8 8 8 6 6 5 4 0];

figure,
plot(x,y,'-o','LineWidth',3,'MarkerEdgeColor','k','Color','y');
title('Input Array');




First-order Derivative for one dimensional function f(x):




MATLAB  CODE:

x1=1:14;
y1=diff(y,1);
figure,
plot(x1,y1,'-o','LineWidth',3,'MarkerEdgeColor','k','Color','r');


-1
-1
-1
0
0
0
6
0
0
-2
0
-1
-1
-4
































NOTE: The contiguous values are zero. Since the values are nonzero for non-contiguous values, the result will be thick edges.
The first-order derivative produces thicker edges.

Second-order Derivative for one dimensional function f(x):

















MATLAB CODE:

x2=1:13;
y2=diff(y,2);
figure,
plot(x2,y2,'-o','LineWidth',3,'MarkerEdgeColor','k','Color','g');


0
0
1
0
0
6
-6
0
-2
2
-1
0
-3































The Second-order derivative gives finer result compared to first-order derivative. It gives fine detailed thin lines and isolated points.  Let’s see how the second-order derivative used for Image sharpening (Laplacian) in my upcoming post.
like button Like "IMAGE PROCESSING" page

Sobel edge detection

         The gradient of the image is calculated for each pixel position in the image.






























The procedure and the MATLAB  code for sobel edge detection without using MATLAB built-in function:


































MATLAB CODE:


A=imread('peppers.png');
B=rgb2gray(A);

C=double(B);


for i=1:size(C,1)-2
    for j=1:size(C,2)-2
        %Sobel mask for x-direction:
        Gx=((2*C(i+2,j+1)+C(i+2,j)+C(i+2,j+2))-(2*C(i,j+1)+C(i,j)+C(i,j+2)));
        %Sobel mask for y-direction:
        Gy=((2*C(i+1,j+2)+C(i,j+2)+C(i+2,j+2))-(2*C(i+1,j)+C(i,j)+C(i+2,j)));
     
        %The gradient of the image
        %B(i,j)=abs(Gx)+abs(Gy);
        B(i,j)=sqrt(Gx.^2+Gy.^2);
     
    end
end
figure,imshow(B); title('Sobel gradient');
Sobel Gradient

%Define a threshold value
Thresh=100;
B=max(B,Thresh);
B(B==round(Thresh))=0;

B=uint8(B);
figure,imshow(~B);title('Edge detected Image');












Edge detected Image



Edge detected Image(Threshold value:35)
The edge detected image can be obtained from the sobel gradient by
using a threshold value.


  • If the sobel gradient values are lesser than the threshold value then replace it with the threshold value.
    if f < threshold value then
    f = threshold value.

























To avoid complex computation, the gradient can also be computed using the formula:




The Image obtained from computing X-direction derivative:













The Image obtained from computing Y-direction derivative:




      Check  Sobel Edge Detection - Part 2








like button Like "IMAGE PROCESSING" page

Darker Edges


Captured Image

Last week my friend was in need of her signature in digital format. Fortunately, it was not for any official purpose. So we captured the signature using the camera and used it.

The image that we acquired using the camera was not that much good. So we processed the image and then included in the document.

After this thing happened, I thought of trying the image with MATLAB.
First I adjusted the image intensity using the imadjust function . 
The syntax for the imadjust for rgb image is
imadjust(RGB,[Low_R Low_G Low_B; High_R High G High B],[]);
The Low values should always be lower than High values.
The range of these values between 0 to 1.
After Imadjust

Then I detected the edge of the image. Then to enlarge the image parts I dilated it. Use an appropriate structure element. Here I used 'disk'.
After that, using labeling method, I labeled all the connected components. Based on the size of the components the components where finally used and components whose size are less are ignored.
Edge detected Image

MATLAB CODE:



function my_edge
global filename A I ;
scz=get(0,'ScreenSize');
figure('Position',[round(scz(1,3)/4) round(scz(1,4)/8) 700 500],'MenuBar','None','NumberTitle','off','Name','Pencil sketch Application','Resize','off');
axes('Position',[0 0 .7 1],'xtick',[],'ytick',[]);
Low=uicontrol('Style','slider','Position',[500,280 200 20],'Max',0.99 ,'Min',0,'Value',0.0,'SliderStep',[0.05,0.1],'Callback',@draw);
High=uicontrol('Style','slider','Position',[500,370 200 20],'Max',1,'Min',0.1,'Value',.5,'SliderStep',[0.05,0.1],'Callback',@draw);
uicontrol('Style','pushbutton','String','Done','Position',[500 200 40 20],'Callback',@pushme);
directory=dir('*.jpg');
files={directory.name}';
uicontrol('style','text','Position',[500,310 100 20]','String','Low:');
uicontrol('style','text','Position',[500,395 100 20]','String','High :');
uicontrol('style','text','Position',[500,455 100 20]','String','Filename:');
uicontrol('Style','popupmenu','position',[500 420 160 30],'Value',1,'String',files,'Callback',@displayfile);
    function displayfile(obj,eve)
        ptr=get(obj,'value');
        filename=char(files(ptr));
        A=imread(filename);
        A=imresize(A,0.4);
        subplot('Position',[0.05 0.1 .6 .9]);imshow(A);
    end
    function draw(obj,eve)
        H=get(High,'Value');
        L=get(Low,'Value');
      uicontrol('Style','edit','position',[500 250 50 20],'String',L);
      uicontrol('Style','edit','position',[500 340 50 20],'String',H);
        if( L < H )
            %The intensity values for each R,G,B planes are adjusted.
            I=imadjust(A,[L L L; H H H],[]);
        end
           subplot('Position',[0.05 0.1 .6 .9]);imshow(I);
       end
                                                                                                         
                                                                                        
                                                                                         
                                                                                   
                                                                                    
    function pushme(obj,eve)
        myedges(I);
    end
    function myedges(A)
      
A1=rgb2gray(A);
B=(edge(A(:,:,1))|edge(A(:,:,2))|edge(A(:,:,3)));

Edge detected




SE=strel('disk',3);
C=~(imdilate(B,SE));
target=(ones([size(A1,1) size(A1,2)] ));
[BW,label]=bwlabel(~C,8);
for l=1:max(max(label))
[row, col] = find(BW==l);
if(size(row,1)>30)
for i=1:size(row,1)
    x=row(i,1);
    y=col(i,1);
    target(x,y)=C(x,y);
end
end
end


subplot('Position',[0 0.5 .8 .45]);imshow(A);title('Original Image');
subplot('Position',[0 0   .8 .45]);imshow(target);title('Final Image');
    end
end


Another example:

After Imadjust and edge detection (structuring element:disk Radius=1)


like button Like "IMAGE PROCESSING" page
Next Post Home
Related Posts Plugin for WordPress, Blogger...
Twitter Bird Gadget Google ping Hypersmash.com