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

Tile Swapping GAME

             The little one at my home likes to play the hidden object games. There are also mini games as a part of the hidden object game. One such game I came across was tile swapper, which is of course a good old one. I thought of trying this game with MATLAB and to my surprise ,it came out better than I expected.

Method I used:

I divided the image into equal parts and randomized the position of the images.
I created push buttons and placed these random parts on it.
When a button is clicked followed by another button click, the image on the previous button click is swapped with the last button clicked image. This process continues until all the image parts are at the correct position.

How to play:

1.       Select an image from the popup menu



2.       Select the number of tiles from the popup menu

3.       Click an image part

4.       Click another image part

The selected  image parts are swapped



5.       Continue the process until all the image parts are in correct position.


6.       If the image parts are in correct position then msgbox pops up with a message.


MATLAB CODE:


function tile_swap_game
clear all;
clc
%FIGURE WINDOW
figure('Position',[250 150 700 450],'Name','TILE SWAP GAME','NumberTitle','off','MenuBar','None','Resize','off');
%DECLARE THE GLOBAL VARIABLES
global indexvalue currvalue prevalue correctPos Pname x1 y1 flag A Rnum presentPos files I TImg;

%GET THE JPEG IMAGES IN THE CURRENT FOLDER
directory=dir('*.jpg');
files={directory.name}';
%TITLE SIZE
msize={'2X2';'3X3';'4X4';'5X5';'6X6';'7X7';'8X8'};
%DEFINE THE GUI POPMENUS
uicontrol('Style','text','position',[495 400 75 25],'String','SELECT IMAGE');
fctrl=uicontrol('Style','popupmenu','position',[495 350 160 40],'Value',1,'String',files,'Callback',@displayfile);
uicontrol('Style','text','position',[495 320 75 25],'String','# TILES');
sctrl=uicontrol('Style','popupmenu', 'position',[495 290 160 20],'Value',1,'String',msize,'Callback',@tile);

%DISPLAY THE SELECTED IMAGE FROM THE POPMENU OPTION
    function displayfile(~,~)

        ptr=get(fctrl,'Value');
        filename=char(files(ptr));
        I=imread(filename);
        %RESIZE IMAGE TO STANDARD SIZE
        I=imresize(I,[448 447]);
        TImg=im2double(I);
       uicontrol('Style','Pushbutton','Position',[1 1 448 447],'CData' ,TImg);
       
    end

%GET THE TITLE SIZE AND DIVIDE THE IMAGE BASED ON THE SIZE
    function tile(~,~)
         
        if(isempty(I))
         
            displayfile;
        end
        ptr1=get(sctrl,'Value');
        num=ptr1+1;
        mvalue=mod(size(I),num);
        A=imresize(I,[size(I,1)-mvalue(1,1) size(I,2)-mvalue(1,2)]);

      
        m=size(A,1)/num;
        n=size(A,2)/num;
        x=1;
        y=1;
        x1=m;
        y1=n;
        indexvalue=1;

        correctPos=zeros([num^2 5]);
        presentPos=zeros([num^2 5]);
        inc=1;
        %DIVIDE THE IMAGE SIZE INTO EQUAL PARTS
        %EXAMPLE: IF #TITLE IS 4X4 THEN IMAGE WILL BE DIVIDED INTO 16 EQUAL
        %PARTS
        for i = 1:num
            m=x1*i;
            for j=1:num
   
                n=y1*j;
                correctPos(inc,1:4)=[x y m n];
               inc=inc+1;
               y=n;
            end
            x=m;
            y=1;
        end
        %RANDOMIZE THE IMAGE PARTS
        Rnum=randperm(num^2);

        %RE-POSITION THE [X,Y] CO-ORDINATES FOR THE UICONTROL FIELD
        %'POSITION'
        presentPos=sortrows(correctPos,-2);
        correctPos(:,5)=[1:(inc-1)]';
        presentPos(:,5)=[1:(inc-1)]';

        for j = 1 : inc-1
            %GET THE RANDOM NUMBER
            i=Rnum(j);
            %READ THE IMAGE PART BASED ON THE RANDOM NUMBER
            Ind=im2double(A(correctPos(i,1):correctPos(i,3),correctPos(i,2):correctPos(i,4),:));
            %DISPLAY THE IMAGE PART ON THE UICONTROL OBJECT 'PUSHBUTTON'
            Pname(j)=uicontrol('Style','Pushbutton','Position',[presentPos(j,1) presentPos(j,2) x1 y1],'CData' ,Ind,'UserData',j,'callback',@swap);
   
        end
    end
   
    %FUNCTION TO SWAP TWO TITLES
    function swap(obj,~)
        currvalue=get(obj,'UserData');

        if indexvalue == 2
   
           Temp=presentPos(currvalue,:);
           presentPos(currvalue,:)=presentPos(prevalue,:);
           set(Pname(currvalue),'Position',[presentPos(currvalue,1) presentPos(currvalue,2) x1 y1]);
           presentPos(prevalue,:)=Temp;
           set(Pname(prevalue),'Position',[presentPos(prevalue,1) presentPos(prevalue,2) x1 y1]);
   
           Evaluate_Position;
   
           if(flag==1)
             winner;
           end
   
           indexvalue=1;
        else
           prevalue=currvalue;
           indexvalue=indexvalue+1;
        end
   
    end

    %CHECK IF ALL THE IMAGE PARTS ARE PLACED IN THE CORRECT POSITION
    function Evaluate_Position
       
        flag=1;      
      
        tot=find(presentPos(:,5)==Rnum');
        if(numel(tot)==size(Rnum,2))
           flag=1;
        else
           flag=0;
        end
    end

    %DISPLAY THE IMAGE AND 
    function winner
        uicontrol('Style','Pushbutton','Position',[1 1 448 447],'CData' ,TImg);
        msgbox('YOU WIN!!!','CONGRATS');
    end
end




NOTE:  

a. Check whether the current directory contains JPEG images before executing the code
b. If you find the code is broken or unable to execute, mail me.I will mail you the code. Happy Weekend:-)

like button Like "IMAGE PROCESSING" page

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

Create Video with Sequence of Images


                   Have you ever tried to create Movie trailer of your favorite movie or playback of your favorite pictures?  Here let’s create one. Let’s try to create a Movie trailer, a simple one.
Store all the images that are needed to create your video in a folder.
There are two methods to create a video file.  First method is creating video with array of Images and the second method is write one frame at a time to the video file.

Method 1:

Read all the images into an array and write to the video file.

MATLAB CODE:

%Create Video with Image Sequence
clear all
clc
%Make the Below path as the Current Folder
cd('C:\Documents and Settings\AARON\My Documents\MATLAB\Images');

%Obtain all the JPEG format files in the current folder
Files = dir('*.jpg');


%Find the total number of JPEG files in the Current Folder
NumFiles= size(Files,1);

%Preallocate a 4-D matrix to store the Image Sequence
%Matrix Format : [Height Width 3 Number_Of_Images]
Megamind_Images = uint8(zeros([600 1000 3 NumFiles*5]));

%To write Video File
VideoObj = VideoWriter('Create_Video.avi');
%Number of Frames per Second
VideoObj.FrameRate = 5; 
%Define the Video Quality [ 0 to 100 ]
VideoObj.Quality   = 80;  


count=1;

for i = 1 : NumFiles
  
   %Read the Images in the Current Folder one by one using For Loop
   I = imread(Files(i).name);
  
   %The Size of the Images are made same
   ResizeImg = imresize(I,[600 1000]);
  
   %Each Image is copied 5 times so that in a second 1 image can be viewed
   for j = 1 : 5
     Megamind_Images(:,:,:,count)=ResizeImg;
     count = count + 1;
   end
 
end

%Open the File 'Create_Video.avi'
open(VideoObj);


%Write the Images into the File 'Create_Video.avi'
writeVideo(VideoObj, Megamind_Images);


%Close the file 'Create_Video.avi'
close(VideoObj);



EXPLANATION:

1. %Make the Below path as the Current Folder
      cd('C:\Documents and Settings\AARON\My Documents\MATLAB\Images');

               The ‘cd’ command is used to make the given path as current folder.
               When you execute the above command, you can find the current folder changed to the path specified in the above command.
2. %Obtain all the JPEG format files in the current folder
        Files = dir('*.jpg');

                   The ‘Files’ variable contains metadata.
>> Files(:).name

ans =

Megamind_01.jpg


ans =

Megamind_02.jpg


ans =

Megamind_03.jpg


ans =

Megamind_04.jpg


ans =

Megamind_05.jpg


ans =

Megamind_06.jpg


ans =

Megamind_07.jpg



3. %To write Video File
VideoObj = VideoWriter('Create_Video.avi');

Mention the Video file name

4. %Number of Frames per Second
VideoObj.FrameRate = 5; 

Five frames will be played in 1 second.


5.  ‘NumFiles’ contain number of JPEG images in the current folder.
In our example, the number of JPEG images is 7.
>> NumFiles

NumFiles =

     7

6.  Read the first Image using ‘Imread’ function.
7.  Resize the image to a size of your choice. See that you resize all the images to a constant size.
8.  If we use only these 7 images then the video will be played within 1.4 seconds. And you may not be able to view the images in the video. So in order to make all the images viewable for certain time, each frame is replicated 5 times.
9.  The Number of Frames per second is 5. Since each image is replicated for 5 times, one image will be seen per second. Therefore, our video will run for 7 seconds with 7 Images * 5 repetition = 35 Images.



10.Store these 35 images in a matrix.
   Images(:,:,:,count)=ResizeImg; 
11.Finally, open the video file and write the image matrix and close the file.

METHOD 2:


In the previous method, we wrote the entire 35 images stored matrix to the video file at once. Here we are going to read the image, convert to movie frame and write it one by one to the video file.

MATLAB CODE:


%Create Video with Image Sequence
clear all
clc

%Make the Below path as the Current Folder
cd('C:\Documents and Settings\AARON\My Documents\MATLAB\Images');

%Obtain all the JPEG format files in the current folder
Files = dir('*.jpg');

%Number of JPEG Files in the current folder
NumFiles= size(Files,1);


%To write Video File
VideoObj = VideoWriter('Create_Video01.avi');
%Number of Frames per Second
VideoObj.FrameRate = 5; 
%Define the Video Quality [ 0 to 100 ]
VideoObj.Quality   = 80;  

%Open the File 'Create_video01.avi'
open(VideoObj);

for i = 1 : NumFiles
   
   %Read the Image from the current Folder
   I = imread(Files(i).name);
  
   %Resize Image
   ResizeImg = imresize(I,[600 1000]);
  
   %Convert Image to movie Frame
   frame = im2frame(ResizeImg);
  
   %Each Frame is written five times.
      for j = 1 : 5
          %Write a frame
          writeVideo(VideoObj, frame);
      end
 
end


%Close the File 'Create_Video01.avi
close(VideoObj);



EXPLANATION:


1.  After reading the image from the current folder, convert the image to movie frame using ‘im2frame’ function.
2.  Write the frame to the file and read next image and repeat the process of converting and writing to the file till the last image is processed and written.










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