matlab:将图像分割成重叠的块

时间:2014-03-08 15:18:41

标签: matlab image-processing matrix overlap

我的图片大小为[M,N],我想将其拆分为overlapping[rr,cc]。每个块移动yyxx像素。下面的代码完成了这项工作。有没有更有效的方法呢?例如避免for循环?我找到的解决方案approach #1approach #2主要用于non-overlapping阻止。

SOL 1

Im = imread('cameraman.tif');
[M,N,~] = size(Im);
rr = 64; cc = 64; xx = 32; yy = 32;

numBlocksYY = numel(1:rr-xx:(M-(rr-1)));
numBlocksXX = numel(1:cc-yy:(N-(cc-1)));
[numBlocksYY, numBlocksXX]
C = cell(numBlocksYY*numBlocksXX,1);
counter = 1;
for ii=1:rr-xx:(M-(rr-1))
    for jj=1:cc-yy:(N-(cc-1))
        fprintf('[%d:%d, %d:%d]\n',ii,ii+rr-1,jj,jj+cc-1);
        C{counter} =  Im(ii:(ii+rr-1), jj:(jj+cc-1), : );
        counter = counter + 1;
    end
    fprintf('\n');
end

figure;
for ii=1:numBlocksYY*numBlocksXX
    subplot(numBlocksYY,numBlocksYY,ii), imagesc( C{ii} ); axis image; colormap gray;
end

SOL 2 受到post中提出的一些解决方案的启发,我试图使用ndgrid找到解决方案,但我怎么能在以后填写输出cell C并访问子图像使用XXYY索引?我也很想知道是否有其他解决方案:-)?

[YY,XX]=ndgrid( 1:(rr-xx):(M-(rr-1)) , 1:(cc-yy):(N-(cc-1)));

1 个答案:

答案 0 :(得分:1)

您可以从 SOL 2 中的cell CXX获取输出YY,如下所示:

% indices of the first rr x cc block
IDX1 = bsxfun(@plus, (1:rr)', ((1:cc)-1)*M);
% offset in indices for each block
offset = (XX(:)-1) + (YY(:)-1)*M;
% indices of each block, the block is indexed with the 3rd dimension
IDX = bsxfun(@plus, IDX1, reshape(offset, [1 1 numel(offset)]));
% convert to cell of blocks
C = mat2cell(Im(IDX), rr, cc, ones(1, numel(XX)));