2

在此处输入图像描述

在我的进步工作中,我必须检测寄生虫。我用 HSV 发现了寄生虫,后来把它做成了灰色图像。现在我也做了边缘检测。我需要一些代码来告诉 MATLAB 找到最大的轮廓(寄生虫)并将该区域的其余部分设为黑色像素。

4

3 回答 3

3

由于我的答案几乎都写出来了,所以无论如何我都会给你,但这个想法类似于@rayryeng 的答案。

基本上我在调用过程中使用Perimeterand标志,因此一旦使用.PixelIdxListregionpropsimclearborder

这是代码:

clc
clear


BW = imclearborder(im2bw(imread('http://i.stack.imgur.com/a5Yi7.jpg')));

S= regionprops(BW, 'Perimeter','PixelIdxList');

[~,idx] = max([S.Perimeter]);

Indices = S(idx).PixelIdxList;

NewIm = false(size(BW));

NewIm(Indices) = 1;

imshow(NewIm)

和输出:

在此处输入图像描述

如您所见,有很多方法可以达到相同的结果哈哈。

于 2015-02-19T19:11:17.040 回答
3

您可以通过填充每个轮廓围绕的孔来选择“最大”轮廓,找出哪个形状为您提供最大的区域,然后使用最大区域的位置并将其复制到最终图像。正如 Benoit_11 所建议的那样,使用regionprops- 特别是AreaandPixelList标志。像这样的东西:

im = imclearborder(im2bw(imread('http://i.stack.imgur.com/a5Yi7.jpg')));
im_fill = imfill(im, 'holes');
s = regionprops(im_fill, 'Area', 'PixelList');
[~,ind] = max([s.Area]);
pix = sub2ind(size(im), s(ind).PixelList(:,2), s(ind).PixelList(:,1));
out = zeros(size(im));
out(pix) = im(pix);
imshow(out);

第一行代码直接从 StackOverflow 读取图像。由于某种原因,该图像也是 RGB 图像,因此我通过im2bw. 图像周围还有一个白色边框。您很可能已在 a 中打开此图像figure并保存了图中的图像。imclearborder我通过使用删除白色边框摆脱了这个。

接下来,我们需要填充轮廓围绕的区域,因此imfillholes标志一起使用。接下来,用于regionprops分析图像中不同的填充对象——具体来说,Area填充图像中的每个对象以及哪些像素属于。一旦我们获得这些属性,找到为您提供最大区域的填充轮廓,然后访问正确的regionprops元素,提取属于对象的像素位置,然后使用这些并将像素复制到输出图像并显示结果.

我们得到:

在此处输入图像描述

或者,您可以使用Perimeter建议的标志(如 Benoit_11 所示),并简单地找到对应于最大轮廓的最大周长。这仍然应该给你你想要的。因此,只需将第三行和第四行代码中的Area标志替换为,您仍然应该得到相同的结果。Perimeter

于 2015-02-19T18:58:55.353 回答
3

这可能是一种方法 -

%// Read in image as binary
im = im2bw(imread('http://i.stack.imgur.com/a5Yi7.jpg'));
im = im(40:320,90:375); %// clear out the whitish border you have
figure, imshow(im), title('Original image')

%// Fill all contours to get us filled blobs and then select the biggest one
outer_blob = imfill(im,'holes');
figure, imshow(outer_blob), title('Filled Blobs')

%// Select the biggest blob that will correspond to the biggest contour
outer_blob = biggest_blob(outer_blob); 

%// Get the biggest contour from the biggest filled blob
out = outer_blob & im;
figure, imshow(out), title('Final output: Biggest Contour')

基于的功能biggest_blobbsxfun此处发布的其他答案的替代方法regionprops。根据我的经验,我发现这种bsxfun基于技术的速度比regionprops. 以下是在我之前的一个答案中比较这两种技术的运行时性能的几个基准。

相关功能 -

function out = biggest_blob(BW)

%// Find and labels blobs in the binary image BW
[L, num] = bwlabel(BW, 8); 

%// Count of pixels in each blob, basically should give area of each blob
counts = sum(bsxfun(@eq,L(:),1:num)); 

%// Get the label(ind) cooresponding to blob with the maximum area 
%// which would be the biggest blob
[~,ind] = max(counts);

%// Get only the logical mask of the biggest blob by comparing all labels 
%// to the label(ind) of the biggest blob
out = (L==ind);

return;

调试图像 -

在此处输入图像描述

在此处输入图像描述

在此处输入图像描述

于 2015-02-19T19:07:00.593 回答