如何在 Matlab 中绘制二值图像的外轮廓

How can I draw a outer contour for binary image in Matlab

我有一个图像,其中有 3 个 class 标记为 {2,3,4} 作为第一行的左图。

对于每个 class,我想绘制一个轮廓,它是 class 的外部轮廓,作为第二行中的图像。我尝试使用下面的 Matlab 代码,但它显示重叠轮廓。我怎样才能达到预期的结果? 谢谢大家

Img=ones(128,128);
Img(20:end-20,20:end-20)=2;
Img(30:end-30,30:end-30)=3;
Img(45:end-45,45:end-45)=4;
Img(50:end-65,68:end-48)=2; %% Add one more rectangular
Img(68:end-48,50:end-65)=3; %% Add one more rectangular

subplot(121);imagesc(Img);colormap(gray);hold on; axis off;axis equal;
subplot(122);imagesc(Img);colormap(gray);hold on; axis off;axis equal;
[c2,h2] = contour(Img==2,[0 1],'r','LineWidth',2);
[c3,h3] = contour(Img==3,[0 1],'g','LineWidth',2);
[c4,h4] = contour(Img==4,[0 1],'b','LineWidth',2);
hold off;  

好的,与其说是答案,不如说是一个想法。

我认为您可以更改边界的颜色而不是使用 contour

figure
Img=ones(128,128);

 %the boundaries of two boxes
Img(20:end-20, 20)=2;
Img(20:end-20, end-20)=2;
Img(20, 20:end-20)=2;
Img(end-20, 20:end-20)=2;

Img(30:end-30, 30)=3;
Img(30:end-30, end-30)=3;
Img(30, 30:end-30)=3;
Img(end-30, 30:end-30)=3;


imagesc(Img);
cm = colormap(gray);

%modify the colormap for the different boundaries
colordata = cm;
colordata(findnearest([1:length(colordata)]/length(colordata), 2/max(max(Img))),:) = [1 0 0];
cm = colormap(colordata);

colordata = cm;
colordata(findnearest([1:length(colordata)]/length(colordata), 3/max(max(Img))),:) = [0 1 0];
colormap(colordata)

如果您了解为什么颜色条中的红色不在 2 处,您就完成了。我想不通。希望这能以某种方式帮助..

N.B。我用 findneareest 找到了我想修改的 colomap 条目。

要获得预期的结果,您必须在组件中使用 bwlabel to label connected components. Then, for each component, we will draw a single contour by using imfill to fill 一个孔。这种方式将保证您将为每个组件绘制一个外部轮廓。使用 for 绘制 class 的所有可能组件。这是代码

Img=ones(128,128);
Img(20:end-20,20:end-20)=2;
Img(30:end-30,30:end-30)=3;
Img(45:end-45,45:end-45)=4;
Img(50:end-65,68:end-48)=2; %% Add one more rectangular
Img(68:end-48,50:end-65)=3; %% Add one more rectangular
subplot(121);imagesc(Img);colormap(gray);axis off;axis equal;
L = bwlabel(Img==2);
% imshow(L==1);colormap(gray);hold on; axis off;axis equal;
subplot(122);imagesc(Img);colormap(gray);hold on; axis off;axis equal;
hold on
for label_index=1:max(L(:))
    im = imfill(L==label_index, 'holes');
    [c2,h2] = contour(im,[0 1],'r','LineWidth',2);
end


L = bwlabel(Img==3);
for label_index=1:max(L(:))
    im = imfill(L==label_index, 'holes');
    [c3,h3] = contour(im,[0 1],'g','LineWidth',2);
end

L = bwlabel(Img==4);
for label_index=1:max(L(:))
    im = imfill(L==label_index, 'holes');
    [c3,h3] = contour(im,[0 1],'b','LineWidth',2);
end
hold off

输出: