将图像分成块时如何防止超出矩阵尺寸?

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

我有一张图片,我想将其分成重叠的块。

我已将框的大小设置为 8 行 8 列,重叠因子为 4 rows/columns。

这是我为解决这个问题而写的:

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

这一直有效,直到它到达图像的末尾,其中 j+8i+8 将超出图像的尺寸。有什么方法可以避免这种情况,同时最大限度地减少数据丢失吗?

谢谢

如果你只想忽略位于完整子块之外的columns/rows,你只需从相应的循环范围中减去子块的width/height:

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
        ...

假设您的图片是 16x16。从列 8 开始的块将占列的其余部分,因此起始索引在 9 到 16 之间是没有意义的。

此外,我认为您的示例错误计算了块大小...您得到的块是 9x9。我想你想做的是:

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

例如,在使用上述代码的 13x13 图像中,您的行索引将为 [1, 5],块的行范围将为 1:85:12。 Row/column 13 将被排除在外。

我不确定你想要它们如何排列,但我做了一个棋盘图案,即

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

所以要这样做

%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;