MATLAB: How to divide image into non-overlapping blocks?

digital image encryption

my input image is M*M size. i have to divide the image into nonlapping blocks each of size m*n .

Best Answer

What do you want to do with the blocks? Would using blockproc be sufficient already?
If not, what should happen with the margins if M is not a multiple of m or n?
Creating a loop is not hard:
X = rand(1000, 1000);
m = 21;
n = 17;
siz = size(X);
vm = 1:m:siz(1) - m + 1;
vn = 1:n:siz(2) - n + 1;
B = cell(numel(vm), numel(vn));
for im = 1:numel(vm)
for in = 1:numel(vn)
B{im, in} = X(vm(im):vm(im)+m-1, vn(in):vn(in)+n-1);
end
end
Now you have a cell matrix containing the blocks. Maybe a multi-dimensional numerical array is much better:
X = rand(1000, 1000);
m = 21;
n = 17;
% Crop not matching right and bottom margin:
siz = size(X);
M = siz(1) - mod(siz(1), m);
N = siz(2) - mod(siz(2), n);
X = X(1:M, 1:N);
% Reshape the matrix:
C = reshape(X, m, M/m, n, N/n);
C = permute(C, [1, 3, 2, 4]);
Now C(:, :, i, j) is the block in row i and column j.