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

Image Erosion without using MATLAB function 'imerode'

In MATLAB, ‘imerode’ is a function used to make the objects thin. MATLAB code without using 'imerode' function and explanation is provided here. The input image is binary.



MATLAB CODE:



A=[1 0 1 1 1; 1 0 1 0 0; 1 1 1 0 0;0 0 1 1 1];
%Structuring element
B=[1 1 0];
%Pad array with ones on both sides
C=padarray(A,[0 1],1);
%Intialize the matrix D of size A with zeros
D=false(size(A));
for i=1:size(C,1)
    for j=1:size(C,2)-2
        In=C(i,j:j+2);
        %Find the position of ones in the structuring element
        In1=find(B==1);
        %Check whether the elements in the window have the value one in the
        %same positions of the structuring element
        if(In(In1)==1)
        D(i,j)=1;
        end
    end
end
display(D);


Explanation:
1.     Consider a matrix A and a structuring element B.
2.     Initialize a matrix D of size A with zeros.
3.     Construct a window of size B with the elements of matrix A.
4.     Check whether the ones in the structuring element B overlap the ones in the window.
5.     If it overlaps, then update D with one else zero.





Example 2:


A=imread('circles.png');
figure,imshow(A);
Original Image









%Structuring element
B=getnhood(strel('disk',11));

m=floor(size(B,1)/2);
n=floor(size(B,2)/2);
%Pad array on all the sides
C=padarray(A,[m n],1);
%Intialize a matrix with size of matrix A
D=false(size(A));
for i=1:size(C,1)-(2*m)
    for j=1:size(C,2)-(2*n)
       
        Temp=C(i:i+(2*m),j:j+(2*n));
       
        D(i,j)=min(min(Temp-B));
      
    end
end
figure,imshow(~D);


After Erosion
  

like button Like "IMAGE PROCESSING" page

Image Dilation without using 'imdilate' function


           In MATLAB, ‘imdilate’is the function that dilates the image using a structuring element. Let’s learn how this function works using some examples and codes.


MATLAB CODE:


Example 1:

A=[1 0 0 0 1; 1 0 1 0 0; 1 1 1 0 0;0 0 1 1 1];
%Structuring element
B=[1 0 0; 0 1 0; 0 0 1];
%Pad zeros on all the sides
C=padarray(A,[1 1]);
%Intialize a matrix of matrix size A with zeros
D=false(size(A));
for i=1:size(C,1)-2
    for j=1:size(C,2)-2
        %Perform logical AND operation
        D(i,j)=sum(sum(B&C(i:i+2,j:j+2)));
    end
end

display(D);

Example 2:
A=imread('text.png');
Original Image



A=im2bw(A);
%Structuring element
B2=getnhood(strel('line',7,90));
m=floor(size(B2,1)/2);
n=floor(size(B2,2)/2);
%Pad array on all the sides
C=padarray(A,[m n]);
D=false(size(A));
for i=1:size(C,1)-(2*m)
    for j=1:size(C,2)-(2*n)
        Temp=C(i:i+(2*m),j:j+(2*n));
        D(i,j)=max(max(Temp&B2));
    end
end

figure,imshow(D);

Dilated Image



Example 3:(Method 2)

A=imread('text.png');
A=im2bw(A);
%Structuring element
B=[1 1 1 1 1 1 1;];
C=padarray(A,[0 3]);
D=false(size(A));
for i=1:size(C,1)
    for j=1:size(C,2)-6
        D(i,j)=sum(B&C(i,j:j+6));
    end
end
figure,imshow(D);



Dilated image



























like button Like "IMAGE PROCESSING" page

Find Area, Perimeter, Centroid, Equivdiameter, Roundness and Bounding Box without Using MATLAB Function ‘regionprops’


In MATLAB, the function ‘regionprops’ is used to measure the image properties. Here are some basic properties computed without using the function.
          Read an image and find the connected components using ‘bwlabel’ function.
Using the Labeled matrix as an input, the properties can be measured.

Example:
A=[1 0 0 1
      1 1 1 1
      0 0 1 1]

To find Area:
·        The total number of ‘ON’ pixels in the image.

The number of ones in the matrix is 8.
              
To find Centroid:
·        Find the row and column having pixel value one. Eg.[row,column]=find(label==1)
Row=[ 1     2     2     2     3     1     2     3]
Column=[ 1     1     2     3     3     4     4     4]

·        Find the mean of the row and column having pixel value one.
Mean of Row=2 and mean of column= 2.75



To find the Bounding Box:
·        We need 4 points, starting position(x,y) , length and breadth.
·        Minimum value of row and column minus 0.5 gives starting position(x,y) respectively
·        Minimum value of  row=1-0.5=0.5
·        Minimum value of column=1-0.5=0.5
·        Maximum value of column – minimum value of column+1 gives breadth of the box
·        Maximum value of column=4
·        Max value-min value of column=3+1
·        Maximum value of row- minimum value of row +1gives length of the box
·        maximum value of row=3
·        Max value – Min value=2+1
·        Bounding Box value for the given example:0.5000    0.5000    4.0000    3.0000
·        For more details on how to draw a rectangle check here: https://www.imageeprocessing.com/2011/06/how-to-draw-in-matlab.html



To find the Perimeter
·        Find the boundary of the labeled component
Boundary pixels:
     1     1
     2     2
     2     3
     1     4
     2     4
     3     4
     3     3
     2     2
     2     1
     1     1
·        Find the distance between the each adjoining pair of pixels around the border of the region.
·        Use the distance formula:
                                             
·        For instance, calculate the distance between the two points (1,1) and (2,2). distance=sqrt((2-1).^2+(2-1).^2)=1.41
·        Similarly, the distance is computed for all the pixel positions.
·        The perimeter for the given example is 10.2426

To find the Roundness:
·        Roundness of  an object can be determined using the formula: 
     Roundness=(4*Area*pi)/(Perimeter.^2) 
        If the Roundness is greater than 0.90 then, the object is circular in shape.
     Result= (4*8*3.14)/10.2426.^2=0.9582
           



To find the Equivdiameter
·        Formula: sqrt(4*Area/pi).
     Equivdiameter for the given example:3.1915
   

MATLAB CODE:

%Measure Basic Image Properties without using 'regionprops' function
%Measure Area, Perimeter, Centroid , Equvidiameter, Roundness and Bounding Box
clc
%Read Original Image
I=imread('coins.png');
%Convert to Binary
B=im2bw(I);
                                                 
%Fill the holes
C=imfill(B,'holes');
                                                    
 %Label the image
[Label,Total]=bwlabel(C,8);
%Object Number
num=4;
[row, col] = find(Label==num);

                                         
                                        
                                   
                               





%To find Bounding Box
sx=min(col)-0.5;
sy=min(row)-0.5;
breadth=max(col)-min(col)+1;
len=max(row)-min(row)+1;
BBox=[sx sy breadth len];
display(BBox);
figure,imshow(I);
hold on;
x=zeros([1 5]);
y=zeros([1 5]);
x(:)=BBox(1);
y(:)=BBox(2);
x(2:3)=BBox(1)+BBox(3);
y(3:4)=BBox(2)+BBox(4);
plot(x,y);

                              

%Find Area
Obj_area=numel(row);
display(Obj_area);
%Find Centroid
X=mean(col);
Y=mean(row);
Centroid=[X Y];
display(Centroid);
plot(X,Y,'ro','color','r');
hold off;
                                  

%Find Perimeter
BW=bwboundaries(Label==num);
c=cell2mat(BW(1));
Perimeter=0;
for i=1:size(c,1)-1
Perimeter=Perimeter+sqrt((c(i,1)-c(i+1,1)).^2+(c(i,2)-c(i+1,2)).^2);
end
display(Perimeter);
                                

%Find Equivdiameter
EquivD=sqrt(4*(Obj_area)/pi);
display(EquivD);


%Find Roundness
Roundness=(4*Obj_area*pi)/Perimeter.^2;
display(Roundness);
                          


%Calculation with 'regionprops'(For verification Purpose);
%Sdata=regionprops(Label,'all');
%Sdata(num).BoundingBox
%Sdata(num).Area
%Sdata(num).Centroid
%Sdata(num).Perimeter
%Sdata(num).EquivDiameter
                                           


like button Like "IMAGE PROCESSING" page

Extraction of Connected components without using BWLABEL function


             Many of the visitors to this blog mailed me to post a MATLAB code for extracting the connected components.  In MATLAB, a function called BWLABEL is available to label the connected components.  
Based on the following iterative expression, the connected components are extracted.
where k=1,2,3…

Using the above expression, connected components are extracted without using the function BWLABEL
LABELLING:

MATLAB CODE:


I=imread('label3.jpg');





I=im2bw(I);

%Structuring element
B=strel('square',3);
A=I;
%Find a non-zero element's position.
p=find(A==1);
p=p(1);
Label=zeros([size(A,1) size(A,2)]);
N=0;

while(~isempty(p))
    N=N+1;%Label for each component
    p=p(1);
X=false([size(A,1) size(A,2)]);
X(p)=1;

Y=A&imdilate(X,B);
while(~isequal(X,Y))
    X=Y;
    Y=A&imdilate(X,B);
end

Pos=find(Y==1);

A(Pos)=0;
%Label the components
Label(Pos)=N;

p=find(A==1);

end
imtool(Label);












EXPLANATION:
  1. Read an image (A) and convert it into binary image.
  2. Define a structuring element (B).
  3. Initialize the Label matrix with zeros.
  4. Find a non-zero element position in the input matrix A.
  5. Initialize a matrix X with zeros and place 1 in the non-zero element position found in the previous step.
  6. Perform dilation using the structuring element B on matrix X. i.e. imdilate(X,B);
  7. Perform intersection with the matrix A. Y= A&imdilate(X, B).
  8. Check whether Y==X. If no, then X=Y and perform steps 6 and 7 again else stop the iteration.
  9. Find the non-zero elements position in the Y. In matrix Label place a number N in those positions. N is for labeling the connected components.
  10. Similarly, place zero in those positions in the input matrix A.
  11. Again find a non-zero element position in the matrix A. If found, goto step 5 else stop the iteration.
  12. Using the labels the connected components can be extracted.


EXTRACTION:

MATLAB CODE:






%Extracting the components
Im=zeros([size(A,1) size(A,2)]);
ele=find(Label==1);
Im(ele)=1;
figure,imshow(Im);title('Label:1');






To obtain the first component, find the positions with value=1 in the Label Matrix. Similarly, other components can be extracted.




%Extracting the characters 'I M A G E'
ele=find(Label==2|Label==3|Label==6|Label==7|Label==9);
Im1=zeros([size(A,1) size(A,2)]);
Im1(ele)=1;
figure,imshow(Im1);title('Specific components');






From the Label matrix, I extracted the characters I, M, A, G and E alone by specifying the label numbers 2,3,6,7 and 9.


%Total number of Letters



Total=sprintf('Total Number of Letters:%d',N);
display(Total);




 The total number of components extracted in the above example Image:

Total =

Total Number of letters:14




%Differentiate each component with a specific color
RGBIm=zeros([size(Label,1) size(Label,2) 3]);
R=zeros([size(Label,1) size(Label,2)]);
G=zeros([size(Label,1) size(Label,2)]);
B=zeros([size(Label,1) size(Label,2)]);
U=64;
V=255;
W=128;
for i=1:N
    Pos=find(Label==i);
    R(Pos)=mod(i,2)*V;
    G(Pos)=mod(i,5)*U;
    B(Pos)=mod(i,3)*W;
   
   
 end
RGBIm(:,:,1)=R;
RGBIm(:,:,2)=G;
RGBIm(:,:,3)=B;
RGBIm=uint8(RGBIm);
figure,imshow(RGBIm);title('Labelled Components');






For each label, unique color is given.  Here is another example for labeling and extracting the components. Read the image, ‘coins.png’ , convert it into binary and fill the holes. Then perform labeling and extraction.





Total =

Total Number of coins: 10



like button Like "IMAGE PROCESSING" page
Next Post Home
Google ping Hypersmash.com