[Matlab] How to Split Image into Small Parts

Split image is one of methods for understanding image in details. Usually, this function is applied in several programs of computer vision or pattern recognition.  Before we code, prepare a picture which will be split into small dimensions. For instance,  you can see a cat as shown below  (Is it right that a cat is so innocent ? 😀 ) . I called this image file with “Kucing.png”

1185689_654528644557537_1774417776_n
From the image above, now we will split in, and put every single part into a folder which named “folderPus”. The results of running program is shown below.  How build a function of split image in Matlab code? Well, let check this out!

Screen Shot 2013-08-19 at 5.18.26 AM

Here some codes in Matlab. I have explained through comments among codes.  You can save this function using file name “Split.m”

[code language=”matlab”]
% Created by Yuita Arum Sari
% Input yang dibutuhkan adalah
% file : nama file tempat kita meletakkan file gambar
% dimensi : ukuran dimensi yang digunakan untuk memotong gambar menjadi
% bagian yang lebih kecil
% folderTitle : folder tempat menyimpan file-file gambar dengan dimensi
% yang lebih kecil

function Split(file,dimensi,folderTitle);

[pathstr, name, ext] = fileparts(file);
gambar=imread(file);
[panjang lebar tinggi]=size(gambar);

% pecahan dimensi panjang
% banyaknya kotak dari panjang berdasarkan dimensi
p=[];
panjang=panjang/dimensi;
for i=1:panjang;
p=[p;i*dimensi];
end

% pecahan dimensi lebar
% banyaknya kotak dari lebar berdasarkan dimensi
l=[];
lebar=lebar/dimensi;
for i=1:lebar;
l=[l;i*dimensi];
end

% menambahkan elemen 0 diatas data panjang
pjg=[0;p];
% menambahkan elemen 0 diatas data lebar
lbr=[0;l];

jumlah=size(l,1);
folder=(folderTitle); % mendeklarasikan nama folder
mkdir(folder); % mebuat folder baru
% relative path yang digunakan untuk menyimpan file gambar yang telah
% terpotong kecil-kecil
basePath = ([‘/Users/yuitaarumsari/Documents/testing/’,folder])

for k=1:size(p,1)
a=k
for i=1:a
for j=1:size(l,1)
g=gambar(1+pjg(i):p(i),1+lbr(j):l(j),:)
baseFileName = sprintf(([name,’-‘,’%d.png’]), j+jumlah*(a-1));
fullFileName = fullfile(basePath, baseFileName);
imwrite(g, fullFileName, ‘png’);
end
end
end
[/code]

And you can run function above using these codes

[code language=”matlab”]
file = ‘/Users/yuitaarumsari/Documents/testing/Kucing.png’;
dimensi = 100;
folderTitle = ‘folderPus’;
Split(file, dimensi, folderTitle);
[/code]

Well, that’s my simple case and you can improve or modify the code based on your necessity. Happy coding! 🙂

0 thoughts on “[Matlab] How to Split Image into Small Parts

Leave a Reply

Your email address will not be published.