我有一个图像,我试图计算对象主要填充圆圈的数量 - 所以要杀死圆圈之间的重叠我最终得到一个标签图像到目前为止工作得很好,没有我申请
bwconncomp(theLabeledImage,4);
以获得已填充圈数的方式,但我得到的内容看起来像这样
Connectivity: 4
ImageSize: [505 394 3]
NumObjects: 87
PixelIdxList: {1x87 cell}
恰好错误的是给定的输出是87,而我在图像中有48个。
图像:
所以任何建议:) ?.
答案 0 :(得分:1)
有几件事让你在这里绊倒。
首先,我认为您在标记图像上运行bwconncomp,而不是二进制图像。这会将很多区域重复计算,因为您最终会计算区域及其边界。请参阅下面我的代码(labelImageBWCC = bwconncomp(rgb,4);
),最后计算89个区域。
第二件事是分水岭变换有时不会在交叉点干净地破裂,而是最终会在边界上产生一堆小区域。这是分水岭变换的“高原问题”,但幸运的是,我们可以通过简单地过滤掉具有面积阈值的小区域来避免这个问题的后果。
通过纠正这些问题,您可以获得正确数量的硬币。代码在这里:
img = imread('coins.tif');
% Threshold and binarize image and fill holes
binImg = ~im2bw(img, graythresh(img));
binImg = imfill(binImg, 'holes');
% Distance transform and watershed segmentation
D = bwdist(~binImg);
D = -D;
D(~binImg) = -Inf;
L = watershed(D);
% Generate label image
rgb = label2rgb(L,'jet',[.5 .5 .5]);
% Show results of watershed
figure, imshow(rgb,'InitialMagnification','fit')
title('Watershed transform of coins.tif')
% Count number of label regions. Note - this is incorrect! This will
% count borders and background, which we don't want
labelImageBWCC = bwconncomp(rgb,4);
% Generate new binary image that only looks at individual regions generated
% by watershed segmentation so we are counting watershed regions, not label
% colors
binWatershed = L > 1; % 1 is background region; any region with index > 1 is coin
minCoinSize = 50; % minimum size in pixels
regs = regionprops(binWatershed, 'Area', 'Centroid', 'PixelIdxList');
% Remove all regions with size below threshold
regs(vertcat(regs.Area) < minCoinSize) = [];
% Display image with coin count labeled
figure, imshow(img)
hold on
for k = 1:numel(regs)
text(regs(k).Centroid(1), regs(k).Centroid(2), num2str(k), ...
'Color', 'r', 'HorizontalAlignment', 'center')
end
hold off