How to prevent exceeding matrix dimensions while dividing an image into blocks?

101 views Asked by At

I have an image which I want to divide into overlapping blocks.

I have set the box to be of size 8 rows and 8 columns, and the overlapping factor to be 4 rows/columns.

This is what I have written to solve this:

img = imread('a03-017-05.png');
overlap = 4
count = 1;
for i = 1:overlap:size(img,1)
    for j = 1:overlap:size(img,2)
        new{count} = img(i:i+8,j:j+8);
        count = count+1;
    end
end

This works right until it reaches the end of the image where j+8 or i+8 will go beyond the dimensions of the image. Is there any way to avoid this with minimal data loss?

Thanks

2

There are 2 answers

1
beaker On BEST ANSWER

If you simply want to ignore the columns/rows that lie outside full sub-blocks, you just subtract the width/height of the sub-block from the corresponding loop ranges:

overlap = 4
blockWidth = 8;
blockHeight = 8;
count = 1;
for i = 1:overlap:size(img,1) - blockHeight + 1
    for j = 1:overlap:size(img,2) - blockWidth + 1
        ...

Let's say your image is 16x16. The block beginning at column 8 will account for the remainder of the columns, so having a starting index between 9 and 16 is pointless.

Also, I think your example miscalculates the block size... you're getting blocks that are 9x9. I think you want to do:

        new{count} = img(i:i+blockHeight-1,j:j+blockWidth-1);

As an example, in a 13x13 image with the code above, your row indices will be [1, 5] and the row ranges of the blocks will be 1:8 and 5:12. Row/column 13 will be left out.

0
user1543042 On

I'm not sure how you want them arranged but I did a checker board pattern, ie

x [] x [] ...
[] x [] x ...

So to do that

%The box size
k = 8;
%The overlap
overlap = 4;

%One layer of the checker board
new1 = mat2cell(img, [k*ones(1, floor(size(img,1)/k)), mod(size(img,1), k)], [k*ones(1, floor(size(img,2)/k)), mod(size(img,2), k)]);

%Get the overlap cells
img2 = img(overlap + 1:end - overlap, overlap + 1:end - overlap);

%Create the other part of the checker board
new2 = mat2cell(img2, [k*ones(1, floor(size(img2,1)/k)), mod(size(img2,1), k)], [k*ones(1, floor(size(img2,2)/k)), mod(size(img2,2), k)]);

%They will all end up in new
new = cell(size(new1) + size(new2));
new(1:2:end, 1:2:end) = new1;
new(2:2:end, 2:2:end) = new2;