how can i split an image into 25 blocks using for loop?

i have a lot of images i need to split each image into blocks then i have to convert each block into one vector (now i have 25 vectors) i need to concatenate these vectors in one row vector finally i want to obtain an array each row in this array is a large vector(25 concatenated vectors) of one image how can i do this thanks in advance

 Accepted Answer

B = im2col(your_image,[m n],'distinct');
B=B(:)';
m and n are the image block sizes.
B at the end is one row vector with your image blocks in it.

8 Comments

sorry but what about im2col function i have my own function which convert the block to vector i just need to split image into various blocks with equal size then convert each block of image to generate the vector with my function after that need to concatenate these vectors to generate one global vector for the source image finally i have n(num of source images) vectors need to but them in one array one vector per row. thanks for your response any suggestions
What about im2col function!?
im2col is a built-in MATLAB function that splits an image into blocks based on the given block size. For more information click here .
Each block would be one column on B. and then B(:)' will concatenate all blocks in a row vector that you wanted.
Pretty much that two lines of code above does everything that you asked.
If you want 25 image block (let's say you divide the image 5 by 5) then m and n are calculated as:
[r,c,~]=size(your_image);
m=floor(r/5);
n=floor(c/5);
If image size is exactly divisible by 5 then no problem but if it is not, then some rows and column ad the end are omitted. If you want you can also use imresize to first resize the image into something that is divisible by 5 and then do the procedure.
You have to reiterate this for each image that you read. if your images are of size R*C and you have n images then something like this:
for i=1:n
I=read image n % write appropriate code here.
B = im2col(your_image,[m n],'distinct');
myDataVector(i,:)=B(:)';
end
Each row of myDataVector would be for one image.
The FAQ handles cases where the image is not an integer multiple of block sizes.
ok this is right but i need to ask how can i append a group of n row vectors to the end of another using for loop i need to append this list of vectors to an empty vector when i use allvectors(end+1)=vector; this give me an error as allvectors is empty
allvectors = [allvectors, vector]; % or use ; if they're column vectors.
exactly now how can i empty this allvectors in order to refill it with this way in the next loop
As image analyst mentioned before entering the loop initialize all vectors to an empty variable. Something like this:
allvectors=[];
some code here
for i=1:n
some more code
vector= ....
allvectors = [allvectors, vector];
end

Sign in to comment.

More Answers (2)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!