Matlab识别边界处的物体

Matlab identify objects at boundary

我知道识别图片中对象的基本命令,例如:

level = graythresh(bw); 

bw = im2bw(bw,level);

cc = bwconncomp(bw, 4);

cc.NumObjects;

graindata = regionprops(cc, 'basic');

perimeter = regionprops(cc, 'perimeter');

上面这些代码是我正在使用的代码。 在附图中,我可以得到数字是 4。所以代码确定总共有 4 个对象。

然而,这张图片实际上包含两个对象。如果我们复制这张图片,将复制品上下左右移动,可以看到只有两个物体。但是他们在边界"separated"。

做图的方式无法改变,所以我唯一能想到的办法就是用matlab中的一些函数或代码。

如果有人能提供一些matlab函数来解决这个问题,我将不胜感激。

您需要做的就是遍历边界行和列,并合并在对边排列的任何区域。以下代码将生成一个图像,其中的区域按照您想要的方式用数字标记。

cc=bwconncomp(bw);
[rows,cols] = size(reg);

% matrix of region labels
regions = uint8(zeros(rows,cols));

% label each pixel with an integer for its region number
for i = 1:length(cc.PixelIdxList)
    region(cc.PixelIdxList{i}) = i;
end

% loop over rows, merge the regions if pixels line up
for i = 1:rows
    left = region(i,1);
    right = region(i,end);
    if (left>0) && (right>0) && (left~=right)
        region(region==right) = left;
    end
end


% loop over columns, merge the regions if pixels line up
for j = 1:cols
    top = region(1,j);
    bottom = region(end,j);
    if (top>0) && (bottom>0) && (top~=bottom)
        region(region==bottom) = top;
    end
end