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

Run Length Encoding


Consider a matrix A with 15 elements,
A= [10 10 9 9 9 9 4 0 0 0 0 0 10 10 10]
In the given example,
10 has occurred 2 times, 9 has occurred 4 times, 4 has occurred once, 0 has occurred 5 times and 10 has occurred 3 times.
After Run length encoding, we obtain the matrix without any repetition in the adjacent elements, [10     9     4     0    10].  And the occurrences of each element [2     4     1     5     3]
Thus the matrix is reduced to 10 elements from 15 elements.
Let’s see how to code this reduction method.
Consider the above matrix A,
1.     Find the difference between adjacent elements. Use the function ‘diff(A)’ to find the difference. 
[0    -1     0     0     0    -5    -4     0     0     0     0    10     0     0]
2.     Convert it to logical format.  The elements without repetition are denoted with one and the repeated elements with zero.
 [0         0     0     0     1     1     0     0     0     0     1     0     0     1]
3.     Find the position of the elements that has the value one in the above step.
[2     6     7    12    15].
4.     Find the unique element values using the positions obtained from the above step. In the matrix A, the element at the position 2 is 10, the element at the position 6 is 9, the element at the position 7 is 4, the element at the position 12 is 0 and the element at the position 15 is 10.
[10     9     4     0    10]
5.     The first element in the matrix is 10, it has occurred 2 times. We obtained the occurrence of the first element alone from the matrix in the step 3. For the remaining elements, find the difference of the matrix in the step 3.
i.e. diff([2     6     7    12    15]); The result after concatenating the first element of the matrix obtained in step 3 with difference for the matrix in the step 3 is [2     4     1     5     3]
6.     Thus in the step 4 we obtain the elements without repetition,
[10     9     4     0    10] and the occurrences in step 5, [2     4     1     5     3].

MATLAB CODE:
A=[5 2 2 2 3 3 3 3 4 4 1 1 1 1 1 1 1 6 6 4 4]
F=[logical(diff(A)) 1];
In=find(F~=0);

Ele=A(In);

C=[In(1) diff(In)];

Result=zeros([numel(Ele) 2]);
Result(:,1)=Ele;
Result(:,2)=C;
display(Result);

SAMPLE OUTPUT:
Result =

     5     1
     2     3
     3     4
     4     2
     1     7
     6     2
     4     2
EXPLANATION:
5  has occurred 1 times, 2 has occurred 3 times, 3 has occurred 4 times, 4 has occurred 2 times, 1 has occurred 7 times, 6 has occurred 2 times and 4 has occurred 2 times.
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

Auto Cropping- Based on labeling the connected components


                                                     This post is about labeling the connected components in a binary image and crop the connected components based on the label. The main two functions used for this simple operation are ‘bwlabel’ and ‘regionprops’.
                                                     I used ‘bwlabel’ to label the connected components.  After labeling, I used ‘regionprops’ function to find the rectangle containing the region.  To find the rectangle points, I used ‘BoundingBox’ property.
                                                    Then the labeled components are automatically cropped and the image is displayed. To crop an image, ‘imcrop’ function is used.

MATLAB CODE:


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





                                 


%Convert the Image to binary
B=im2bw(A);
 
%Fill the holes
C=imfill(B,'holes');
 
%Label the connected components
[Label,Total]=bwlabel(C,8);
figure,imshow(C); title('Labelled Image');










%Rectangle containing the region
Sdata=regionprops(Label,'BoundingBox');
 
%Crop all the Coins 
for i=1:Total
    Img=imcrop(A,Sdata(i).BoundingBox);
    Name=strcat('Object Number:',num2str(i));
    figure,imshow(Img); title(Name);
end








Another Example:

'coins.png'

Labeled Image




like button Like "IMAGE PROCESSING" page

Text On Sphere - MATLAB CODE


Text on Sphere-MATLAB CODE

              We can see how to wrap a text around a sphere. First obtain the x,y and z co-ordinates of  the sphere.These co-ordinates can be used as an input for surface object.
Surface object generates sphere using the co-ordinates.  Example:[x,y,z]=sphere(25); surface(x,y,z);
Now read a text image and convert it into binary.  Label the components in the image. You can also check how to label components without BWLABELfunction in MATLAB.   Now use the labeled image as a CDATA value in surface object.
Example: surface(x,y,z, ‘CDATA’,matrix);

MATLAB CODE:


%Input a text image
A=imread('quotes.png');


         


A=~im2bw(A);
B=bwlabel(A,8);
F=double(B);
mytext=flipud(F);


% Create the surface.
[x,y,z] = sphere(100);


figure,surface(x,y,z,'CData',mytext,'FaceColor','texturemap','FaceLighting','phong','EdgeLighting','phong','EdgeColor','none');




%set the colormap. Some built-in colormaps are pink, copper, jet, hot...
%colormap pink

%Here I created my own colormap, the colors are white[1 1 1], black[0 0 0] and %blue [0 0 1]. Initialize the map with zeros(black) for 256x3 matrix. %Add blue 
%color to some components(words). Initialize the first row with [ 1 1 1](white).





map=zeros([253 3]);
map(1,:)=0;
map(50:80,3)=1;
colormap(map);



%Create light object
light('position',[1 2 0 ],'Style','infinite','color',[0.8 0.7 0.8]);
light('position',[-2 -3 0 ],'color',[0.8 0.7 0.8]);


%Specify the viewpoint
axis square off
view(12,0);










Another Example: To create a GLOBE from a WORLD MAP



INPUT IMAGE















To convert a RGB image into SPHERE:
MATLAB CODE:




A=imread('mountain.jpg');
[mytext,map]=rgb2ind(A,256);
mytext=flipud(mytext);

% Create the surface.
[x,y,z] = sphere(100);

figure,surface(x,y,z,'CData',mytext,'FaceColor','texturemap','FaceLighting','phong','EdgeLighting','phong','EdgeColor','none');
%set the colormap. 

colormap(map);


%Create light object
light('position',[1 2 0 ],'Style','infinite','color',[0.8 0.7 0.8]);
light('position',[-2 -3 0 ],'color',[0.8 0.7 0.8]);


%Specify the viewpoint
axis square off
%view(12,0);
view(180,0);










Hope you enjoyed this post. Check the link for more images:http://www.facebook.com/media/set/?set=a.352096201499476.75050.241768945865536&type=1

like button Like "IMAGE PROCESSING" page

How to add caption/subtitles to Video in MATLAB


                                    In my previous post, I discussed about how to create videofrom still images and now we can add subtitles to the video. I used the ‘text’ function to add the subtitles.
The procedure to add subtitles to the Video:
·         Read an video file
·         Read each video frame data
·         Add text to each frame using the syntax ‘text(x,y,string)’.
·         Use imshow to display the image.
·         Get the frame from the figure displayed.

MATLAB CODE:
%Input a Video file
obj=mmreader('Poem.avi');
A=read(obj);
j=1;
%Preallocate the frame structure
Frame=struct('cdata',1,'colormap',cell([1 100]));

                                 INPUT VIDEO
 

%Get the first frame as image
%Add text
%Use 'getframe' to grab the figure
Caption={'How to add Caption/Subtitles';'to video in MATLAB';'GET CODE AT http://angeljohnsy.blogspot.com/';};
I=A(:,:,:,1);
imshow(I),hold on
text(80,100,Caption{1},'Color','w','FontWeight','Bold','FontSize',30);
text(150,200,Caption{2},'Color','w','FontWeight','Bold','FontSize',30);
text(300,480,Caption{3},'Color','r','FontWeight','Bold','FontSize',15);
Frame(j:j+9)=getframe;
j=j+10;


%Get the Second frame as an image i.eA(:,:,:,2);
%Add the Poem title and the author name
Title_={'THE ROAD NOT TAKEN';'-ROBERT FROST'};
I=A(:,:,:,2);
imshow(I), hold on
text(40,100,Title_{1},'Color','k','FontWeight','Bold','FontSize',40);
text(350,550,Title_{2},'Color','k','FontWeight','Bold','FontSize',30);
Frame(j:j+9)=getframe;
j=j+10;


%Create a cell array with the Poem versus
Txt={'TWO roads diverged in a yellow wood,';
'And sorry I could not travel both';
'And be one traveler, long I stood';
'And looked down one as far as I could';   
'To where it bent in the undergrowth;';
'Then took the other, as just as fair,';   
'And having perhaps the better claim,';
'Because it was grassy and wanted wear;';  
'Though as for that the passing there';
'Had worn them really about the same,';
'And both that morning equally lay';   
'In leaves no step had trodden black.';
'Oh, I kept the first for another day!';   
'Yet knowing how way leads on to way,';
'I doubted if I should ever come back.';
'I shall be telling this with a sigh'
'Somewhere ages and ages hence:';  
'Two roads diverged in a wood, and I—';
'I took the one less traveled by,';
'And that has made all the difference.';};

%display the image
%Add the poem lines
%Grab the frame
%There are 20 lines totally
%Add 3 and 2 lines alternatively in each frame
    inc=0;
for i=3:size(A,4)
   
    n=mod(i,2);  
    I=A(:,:,:,i);
   
    imshow(I), hold on
for k=1:2+n
    text(80,440+(k*40),Txt{k+inc},'Color','w','FontWeight','Bold','FontSize',25);
   
end
    inc=inc+2+n;
    Frame(j:j+19)=getframe;
    j=j+20;
 end


Create a Video File:
obj=avifile('Road Not Taken.avi','FPS',3);
 obj=addframe(obj,Frame);
obj=close(obj);


                            VIDEO WITH  SUBTITLE






Explanation:
       text(40,100,Title_{1},'Color','k','FontWeight','Bold','FontSize',40);

                This code will add the text ‘THE ROAD NOT TAKEN’ with color font size 40, font weight bold and color black (k).

          

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