# IMAGE PROCESSING

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

### How to use different images and color maps on a same figure in MATLAB

• Display different images on same figure
• Display stack of images with same colormap
• Display Stack of Images with different colormap

Display different images on same figure

Consider two different images. For instance, let us consider the picture of the cathedral in Milan and the logo of image processing blog.

The image processing logo will be placed on the cathedral image using matlab command ‘imagesc’
MATLAB CODE:
display(size(I));
display(size(L));
figure,imagesc(1,1,I);hold on;
imagesc(3400,1150,imresize(L,[900 900]));
hold off; axis off;

Explanation:
The size of ‘duomo.jpg’ is 2053  x     4320   x         3
i.e 2053 rows and 4320 columns
The size of ‘logo.jpg’ is 328 rows and 328 columns
First the image of the cathedral is displayed using ‘imagesc’ command then on the same figure the logo is placed by mentioning the position.
imagesc(3400,1150,imresize(L,[900 900]));

Here 3920,1650 represents the position to place the logo.
And the logo is resized to 900x900
Since we want to display the images on the same figure, ‘hold on’ command is used.
Display stack of images with single colormap
MATLAB CODE:
T = I;
Numimg = 5;
rng = [1,1];
for in=1:numimg

hold on;
imagesc(rng(1),rng(2),T);colormap(gray);axis ij;
rng = round(size(I)/(numimg*2)*in);

fsz = size(I)-(rng*2);
if fsz==0
break;
else
T = imresize(T,fsz)+1;
end
end

hold off; axis off;

Explanation:
Same image with different size and different starting position is placed on the same figure.
The colormap gray is used for all the images.

Fig. Colormap(jet)

Display Stack of Images with different colormap
MATLAB CODE:

I1 = imresize(I1,[400,400]);
I = rgb2gray(I1);

T = I+1;
%Predefined colormaps
Cname = {'hsv(256)','jet(256)','hot(256)','spring(256)','summer(256)','cool(256)','summer(256)','lines(256)'};
RGB = zeros([size(I,1) size(I,2) 3]);
Numimg = 7; %Number of Images to display
rng = [1 1];

for in=1:numimg-1

%Define the colormap
map1 = im2uint8(colormap(cname{in}));
m = map1(:,1);
RGB(:,:,1) = m(T);
m = map1(:,2);
RGB(:,:,2) = m(T);
m = map1(:,3);
RGB(:,:,3) = m(T);

RGB = uint8(RGB);

hold on;
imagesc(rng(1),rng(2),RGB);axis ij;
rng = round(size(I)/(numimg*2)*in);

fsz = size(I)-(rng*2);
if fsz==0
break;
else
T = imresize(T,fsz)+1;
clear RGB
end
end
I2 = imresize(I1,size(T));
imagesc(rng(1),rng(2),I2); %Actual Image
hold off;axis off;

Explanation:
Here same image with different size and different colormap is displayed on the same figure.
To increase or decrease the number of images, first try to resize the image accordingly and then modify the number of images to display.
The above method can also be used for different images and different color maps can be applied to those images on a single figure.

STACK OF IMAGES:

For More Images and code:
Check : Create Stack of Images notes in Facebook

or
Create Stack of Images in Google Collections

Like "IMAGE PROCESSING" page

### Tile Memory Game

Tile Memory game - Win the game by matching equivalent tiles.

Initially, there will be a 2 by 2 matrix having 2 pairs of equivalent images hidden behind. User will be allowed to select 2 tiles in random. If both the images are equivalent, both the tiles will disappear. If not, it goes back to its original form. When all the pairs are matched, the level is completed and the user can proceed to the next level.

We will try to implement this game using pushbutton in the uicontrol and with some images.

Let’s write a main function called tile_memory_game
We will initialize our variables here and then fetch some images details.
Inside this function, we will have the following functions arrange_tile, display_tile, chk_new_tiles and calculate_moves.

The overall flow of our code:
MATLAB CODE:
function tile_memory_game
clear all;
clc
close all

%GLOBAL VARIABLES
global pname randicon sz flag PId fname items pv ni nj lc Ic Fg nm ;

%FIGURE WINDOW
Fg=figure('Position',[300 200 800 550] ,'Name','TILE MEMORY GAME','NumberTitle','off','MenuBar','None');

%FETCH PNG FORMAT FILES/IMAGES
files = dir('*.png');
fname = {files.name};

%INITIALIZATION
items=2;
ni=2;
nj=2;
sz=100;
lc=1;
nm= uicontrol('Style','Pushbutton','Position',[650 320 150 50]);
arrange_tile;

function arrange_tile

end

function display_tile(obj,~)

end

function chk_new_tiles
end

function calculate_moves

end

end

Now let us try to explain in brief what each of the function does.

In tile_memory_game, all the global variables which will be used in other user defined functions will be mentioned.
Then the figure window which will be used to display the tiles (pushbuttons) is defined. By changing the values in  'Position', the window size can be increased or decreased based on our requirement.

The images used in the game are downloaded from web which are freely usable.

The images used in the game are downloaded from the web which are freely usable.These icons can be found in Iconfinder for free usage, but the license has to be read prior to usage. Usually a link has to be provided to the author's webpage if you are using for commercial purpose.

Initialize the number of rows and columns and the size of the pushbutton.
The function arrange_tile is called to arrange the tiles randomly.

Function arrange_tile
Level 1 contains 2x2 tiles. From the available PNG format icons, select two random icons and double it. That is, each icon should occur twice. A random shuffling will arrange the icons at different positions. See picture below:

The built-in function 'randperm' is used for random shuffling. The syntax randperm(30,2) will randomly select two distinct numbers between 1 and 30. For instance say it selects 28 and 10.
Now we replicate the two numbers selected. Now they become 10,28,10,28.
Again 'randperm' is used for randomly placing these 4 values in the 2x2 matrix.

Pushbuttons are created and the indices are stored as user data for checking in the later part.

MATLAB CODE:
function arrange_tile

Ic=0;
pv=0;

%RANDOMIZE THE TILES
rndno = randperm(numel(fname),items);
row = [rndno rndno];
randicon = row(:,randperm(numel(row)));

inc=1;
flag=0;

%CREATE PUSHBUTTONS
for i = 1 : ni
for j = 1:nj
pname(inc)=  uicontrol('Style','Pushbutton','Position',[5+(i*sz) 90*5-(j*sz) sz-2 sz-2],'UserData',inc,'callback',@display_tile);

inc=inc+1;
end
end

lstat ='Number of Moves: 0 ';
set(nm,'String',lstat);
end

Now the figure window will contain 2x2 tiles/pushbuttons. See figure below

Function display_tile

When a pushbutton is clicked/pressed, an icon/image will appear on it.

 FIRST CLICK
When another pushbutton is clicked, another icon/image will appear on it.

 SECOND CLICK
If both icons match then the icons will disappear.

 ICONS SAME - DISAPPEAR

If both the icons do not match , then it will go back to its original form. The images are displayed for certain duration of time before its hidden back. I use a duration of 0.35 seconds to show the images. See the code below ‘pause(0.35);’

 ICONS DIFFERENT

 Pushbutton Reset

To give it a more sportive look, the number of moves used to complete the game  is calculated. The user has to complete the game within the specified number of moves failing which the game is lost. The time taken can also be calculated and points given as per the time taken to complete the same.

MATLAB CODE:
function display_tile(obj,~)

%OBTAIN THE USERDATA FROM THE PUSHBUTTON CLICKED
currvalue=get(obj,'UserData');

%DISPLAY THE ICON/IMAGE ON THE PUSHBUTTON
cimg = imresize(img,[sz-8 sz-8]);
set(pname(currvalue),'CData',cimg);

if(flag==0)
PId = currvalue;
flag=1;
elseif(currvalue~=PId)

pause(0.35);
%                IF TWO ICONS ARE SAME
if(randicon(currvalue)==randicon(PId))
%                TO SET THE PUSHBUTTONS INVISIBLE
%                set(pname(currvalue),'visible','off');
%                set(pname(PId),'visible','off');

%                TO SET THE PUSHBUTTONS BLACK
set(pname(PId),'CData',zeros([sz sz 3]),'callback','default','String','n');
set(pname(currvalue),'CData',zeros([sz sz 3]),'callback','default','String','n');

pv=pv+1;

else
%                IF TWO ICONS ARE DIFFERENT
set(pname(currvalue),'CData','default');
set(pname(PId),'CData','default');

end

if(Ic>=(items*2))

else

flag=0;
calculate_moves;
chk_new_tiles;
end

end

end

Function calculate_moves
This function is just to display the number of moves during each pair of pushbutton clicks.

Function chk_new_tiles
Check whether all the tiles are matched in the current level. If yes, then increment either row or column or both according to the programmer's wish and proceed to the next level. If all the pairs are matched then increment either the rows or columns or both according to your requirement. When the user succeeds in completing 4x4 ie 16 tiles , a message box with the ‘Winner’ title is displayed and the game is terminated. You can also increase the maximum number of rows and columns based on your requirement.

 Winner

 GAME LOST

MATLAB CODE:
function chk_new_tiles
if(pv==items)

if(items==8)

%END OF THE GAME

else
%INCREASE THE TILE SIZE

lc=lc+1;

%Increment ni or nj or both
%ni = ni+1;
%nj = nj+1;

items=(ni*nj)/2;

arrange_tile;
end
end
end

The level of difficulty can be increased either by increasing the number of rows and columns or decreasing the duration of keeping the images open after wrong match or both.
Kindly note that the full MATLAB code for the game is not provided here.

Like "IMAGE PROCESSING" page

### 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'};
uicontrol('Style','text','position',[495 400 75 25],'String','SELECT IMAGE');
uicontrol('Style','text','position',[495 320 75 25],'String','# TILES');

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

ptr=get(fctrl,'Value');
filename=char(files(ptr));
%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 "IMAGE PROCESSING" page