用Matlab去除图像中不需要的区域

5

我有一张包含物体和一些不需要的区域(小点)的图像。我想要移除这些区域。因此,我使用了一些形态学运算符,例如“闭运算”来移除它们。但是效果并不完美。你有其他更清晰的方法可以移除吗?你可以在原始图像中下载示例图像。

这是我的代码:

load Image.mat %load Img value
Img= bwmorph(Img,'close');
imshow(Img);

enter image description here enter image description here


“Raw image”链接似乎已经损坏了。 - Divakar
2个回答

9
你可能更喜欢一种更快且基于向量的方法,使用bwlabel本身所获得的信息以及bsxfun来进行操作。
注意:bsxfun需要大量内存,但这正是它更快的原因。因此,请注意下面代码中B1的大小。该方法在达到系统内存限制之前可以提供较好的加速,但在此之后将变慢,而regionprops方法则没有这个问题。
代码:
[L,num] = bwlabel( Img );
counts = sum(bsxfun(@eq,L(:),1:num));
B1 = bsxfun(@eq,L,permute(find(counts>threshold),[1 3 2]));
NewImg = sum(B1,3)>0;

编辑 1: 接下来将讨论一些用于比较 bsxfunregionprops 方法的基准测试。

案例 1

基准测试代码

Img = imread('coins.png');%%// This one is chosen as it is available in MATLAB image library
Img = im2bw(Img,0.4); %%// 0.4 seemed good to make enough blobs for this image

lb = bwlabel( Img );
threshold = 2000;

disp('--- With regionprops method:');
tic,out1 = regionprops_method1(Img,lb,threshold);toc
clear out1

disp('---- With bsxfun method:');
tic,out2 = bsxfun_method1(Img,lb,threshold);toc

%%// For demo, that we have rejected enough unwanted blobs
figure,
subplot(211),imshow(Img);
subplot(212),imshow(out2);

输出

输入图像说明

基准测试结果

--- With regionprops method:
Elapsed time is 0.108301 seconds.
---- With bsxfun method:
Elapsed time is 0.006021 seconds.

案例2

基准代码(仅列出与案例1不同的部分)

Img = imread('snowflakes.png');%%// This one is chosen as it is available in MATLAB image library
Img = im2bw(Img,0.2); %%// 0.2 seemed good to make enough blobs for this image
threshold = 20;

输出

enter image description here

基准测试结果

--- With regionprops method:
Elapsed time is 0.116706 seconds.
---- With bsxfun method:
Elapsed time is 0.012406 seconds.

正如之前所指出的,我已经测试了其他更大的图像和许多不需要的斑点,其中bsxfun方法在regionprops方法上没有任何改进。由于MATLAB库中没有这样的更大图像,它们无法在此处讨论。总之,建议根据输入特征使用这两种方法中的任一种。有趣的是看看这两种方法如何处理你的输入图像。


你能提供 tic toc 运行时间比较和 regionprops 吗?bsxfun 快多少? - Shai
@Shai,请查看编辑-1。 - Divakar
+1 非常感谢您进行了广泛的基准测试!非常好的高质量回答。 - Shai

5
您可以使用regionpropsbwlabel选择所有面积(即像素数)小于某个特定值的区域。
lb = bwlabel( Img );
st = regionprops( lb, 'Area', 'PixelIdxList' );
toRemove = [st.Area] < threshold; % fix your threshold here
newImg = Img;
newImg( vertcat( st(toRemove).PixelIdxList ) ) = 0; % remove

谢谢您先生。但是您的代码有一些错误。我构建它并收到了错误消息:“Error using horzcat CAT arguments dimensions are not consistent.Error in removeUnwantedRegion (line 6) newImg( [st(toRemove).PixelIdxList] ) = 0; % remove " . 我的图像大小为384x384。 - user3336190
错误发生在 newImg( [st(toRemove).PixelIdxList] ) = 0; 这一行。我进行了调试,发现了问题。 - user3336190
@user3336190 我的错误:Matlab将每个区域的PixelIdxList存储为列向量。当将它们全部连接在一起时,需要使用vertcat进行垂直连接,而不是使用[]进行水平连接。 - Shai

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接