是否可以在图像中绘制多个轮廓

Is it possible to draw multiple contour in an image

我有一个包含三个 classes 的图像。每个 class 由数字 {2,3,4} 标记,背景为 {1}。我想在图像中绘制每个 class 的轮廓。我尝试了下面的 MATLAB 代码,但轮廓看起来重叠在一起(蓝色和绿色,黄色和绿色)。如何根据 class 绘制轮廓?

Img=ones(128,128);
Img(20:end-20,20:end-20)=2;
Img(30:end-30,30:end-30)=3;
Img(50:end-50,50:end-50)=4;
%%Img(60:end-60,60:end-60)=3; %% Add one more rectangular
imagesc(Img);colormap(gray);hold on; axis off;axis equal;
[c2,h2] = contour(Img==2,[0 1],'g','LineWidth',2);
[c3,h3] = contour(Img==3,[0 1],'b','LineWidth',2);
[c4,h4] = contour(Img==4,[0 1],'y','LineWidth',2);
hold off;

这是我的预期结果

这是因为每个 "class" 在形状上都被定义为空心正方形。因此,当您使用 contour 时,它会遍历正方形的所有边界。举个例子,当你在图上画这个时,只有一个 class。具体来说,看一下您使用 Img == 2 创建的第一个二进制图像。我们得到这张图片:

因此,如果您在此形状上调用 contour,您实际上是在追踪此对象的边界。现在更有意义了不是吗?如果您对 classes 的其余部分重复此操作,这就是等高线颜色重叠的原因。空心正方形的最内部与另一个正方形的最外部重叠。现在,当您第一次调用 contour 时,您实际上会得到:

如你所见,"class 2"实际上被定义为镂空的灰色方块。如果您想实现您的愿望,一种方法是 填写 每个空心方块,然后将 contour 应用于此结果。假设您有图像处理工具箱,请在每个步骤中使用 imfill'holes' 选项:

Img=ones(128,128);
Img(20:end-20,20:end-20)=2;
Img(50:end-50,50:end-50)=3;
Img(30:end-30,30:end-30)=3;
Img(35:end-35,35:end-35)=3;
Img(50:end-50,50:end-50)=4;
imagesc(Img);colormap(gray);hold on; axis off;axis equal;

%// New
%// Create binary mask with class 2 and fill in the holes
im = Img == 2;
im = imfill(im, 'holes');
%// Now draw contour
[c2,h2] = contour(im,[0 1],'g','LineWidth',2);

%// Repeat for the rest of the classes
im = Img == 3;
im = imfill(im, 'holes');

[c3,h3] = contour(im,[0 1],'b','LineWidth',2);
im = Img == 4;
im = imfill(im, 'holes');

[c4,h4] = contour(im,[0 1],'y','LineWidth',2);
hold off;

我们现在得到这个: