2012-04-07 188 views
5

如您所见,我有形状和白色边界。我想填充白色的形状。Matlab填充白色形状

输入是: enter image description here

我想获得这个输出: http://s12.postimage.org/z3txnlb3f/untitled33.png

任何人可以帮助我,请与此代码?它不会将黑色椭圆更改为白色。 非常感谢:]

I = imread('untitled4.bmp'); 
Ibw = im2bw(I); 
CC = bwconncomp(Ibw); %Ibw is my binary image 
stats = regionprops(CC,'pixellist'); 

% pass all over the stats 
for i=1:length(stats), 
size = length(stats(i).PixelList); 
% check only the relevant stats (the black ellipses) 
if size >150 && size < 600 
    % fill the black pixel by white  
    x = round(mean(stats(i).PixelList(:,2))); 
    y = round(mean(stats(i).PixelList(:,1))); 
    Ibw = imfill(Ibw, [x, y]); 
end; 
end; 

imshow(Ibw); 
+0

相关的http://stackoverflow.com/questions/10053651/获得像素属于一个形状 – Gray 2012-04-07 15:05:44

回答

1

如果您的图像是全黑&白色,并且您有图像处理工具箱,那么这是不是您所需要的: http://www.mathworks.co.uk/help/toolbox/images/ref/imfill.html

喜欢的东西:

imfill(image, [startX, startY]) 

其中startX,startY是您要填充的区域中的像素。

+0

谢谢,但我怎么能找到每个形状的像素? – 2012-04-07 13:53:07

+0

您可以使用bwconncomp(http://www.mathworks.co.uk/help/toolbox/images/ref/bwconncomp.html)。如果你做了'c = bwconncomp(image)',那么你可以用'c.PixelIdxList'查看组件。这些是图像中的线性索引,告诉您哪些像素位于哪个组件中。您希望忽略一个组件(背景),您可以假设它是PixelIdxList中的最大列表,或者您可以查找包含边缘像素的列表。从c中的其他组件中,您需要检查它们是否是黑色的。如果是,请使用imfill。 – Richante 2012-04-07 14:34:24

+0

哦,我注意到你的图片也有一个巨大的白色边框。你也想忽略这个组件(所以可能忽略'PixelIdxList'中最大的两个组件)。 – Richante 2012-04-07 14:39:11

3

您的代码可以改进和简化如下。首先,否定Ibw并使用BWCONNCOMP查找4连接的组件将为您提供每个黑色区域的索引。其次,按照其中的像素数量对连通区域进行排序,然后选择除最大两个之外的所有区域,将为您指定所有较小的圆形区域。最后,可以收集这些较小区域的线性指数并用其填充白色区域。下面的代码(相当多短,不需要任何环路):

I = imread('untitled4.bmp'); 
Ibw = im2bw(I); 

CC = bwconncomp(~Ibw, 4); 
[~, sortIndex] = sort(cellfun('prodofsize', CC.PixelIdxList)); 

Ifilled = Ibw; 
Ifilled(vertcat(CC.PixelIdxList{sortIndex(1:end-2)})) = true; 
imshow(Ifilled); 

而这里的结果图像:

enter image description here

+0

嗨gnovice,谢谢你的帮助,它不工作,但Richante帮助我..谢谢:] – 2012-04-07 21:18:38