function Blocks = matrix_to_blocks(image, B)

[H, W] = size(image);

nBlocks = ceil(size(image) / B);    % number of blocks (2d)

% horizontal padding
topad = B * nBlocks(1) - H;
if topad > 0
    image = [image; repmat(image(end,:), topad, 1)];
end

% vertical padding
topad = B * nBlocks(2) - W;
if topad > 0
    image = [image repmat(image(:,end), 1, topad)];
end

bsh = B * ones(nBlocks(1), 1);
bsw = B * ones(nBlocks(2), 1);
Blocks = mat2cell(image, bsh, bsw);

end
