-->

divide the image into 3*3 blocks

2019-02-26 13:20发布

问题:

I have a matrix that does not happen to have dimensions that are multiples of 3 or it might. How can we divide the entire image into blocks of 3*3 matrices. (Can ignore the last ones which does not come under the 3*3 multiples. Also, the 3*3 matrices can be be saved in arrays.

a=3; b=3; %window size
x=size(f,1)/a; y=size(f,2)/b; %f is the original image
m=a*ones(1,x); n=b*ones(1,y);
I=mat2cell(f,m,n);

回答1:

I have never used mat2cell to divide matrices, and thinking about it now it seems like a really good idea. As I don't have MATLAB here in this computer, I'll describe the way I do it, which does not involve mat2cell.

Ignoring the last columns and rows is easy:

d = 3; % the dimension of the sub matrix
[x,y] = size(f);

% perform integer division by three
m = floor(x/d);
n = floor(y/d);

% find out how many cols and rows have to be left out
m_rest = mod(x,d);
n_rest = mod(y,d);

% remove the rows and columns that won't fit
new_f = f(1:(end-m_rest), 1:(end-n_rest));

%  this steps you won't have to perform if you use mat2cell
% creates the matrix with (m,n) pages 
new_f = reshape( new_f, [ d m d n ] );
new_f = permute( new_f, [ 1 3 2 4 ] );

Now you can access the sub-matrices like this:

new_f(:,:,1,1) % returns the 1st one

new_f(:,:,3,2) % returns the one at position [3,2]

If you'd like to use mat2cell to do that, you could do something like the following:

% after creating new_f, instead of the reshape, permute
cells_f = mat2cell(new_f, d*ones(1,m), d*ones(1,n));

Then you would access it in a different way:

cells_f{1,1}
cells_f{3,2}

The cell approach I cannot test because I don't have MATLAB on this PC, but if I can recall the usage of mat2cell correctly, it should work fine.

Hope it helps :)