如何使用 MATLAB 对图像中的对象进行颜色编码?

How to colour-code the objects in an image using MATLAB?

我有一张图像: 我已对其执行分割以接收二值图像。我想用不同的颜色标记图像中的每个对象。到目前为止我有以下代码:

img = imread('lab5a.tif');
BW = imbinarize(img,graythresh(img));
figure; imshowpair(img,BW,'montage')
title ('Opening Operation on Image');
se = strel ('disk', 3);
rem = imclose(BW,se);
figure; imshow (rem, []);
title ('Removed Undesired Features');
CC = bwconncomp(rem);
L = labelmatrix(CC);
RGB = label2rgb(L, spring, 'c', 'shuffle');
figure; imshow(RGB, []);

输出是这张图片: 这不是我想要的。它为背景着色,对象为白色。我只希望物体具有不同的颜色。

我们将不胜感激任何形式的帮助!

在您的示例中,图像的背景和前景与您认为的应该相反。 matlab 命令的默认设置是假设较高值像素(白色)是前景或感兴趣的项目,而较低值像素(黑色)是背景。因此,当您 运行 您的示例代码时,对象 CC 仅包含 1 个对象(图像中的蓝色 "background"):

CC = 

  struct with fields:

    Connectivity: 8
       ImageSize: [256 256]
      NumObjects: 1
    PixelIdxList: {[43341×1 double]}

解决这个问题的任何简单方法就是使用 imcomplement 命令反转清理后的图像。将此行添加到您的代码中:

% invert the image so that the background is black
rem = imcomplement(rem);

现在 CC 结构包含已识别的 62 个对象:

CC = 

  struct with fields:

    Connectivity: 8
       ImageSize: [256 256]
      NumObjects: 62
    PixelIdxList: {1×62 cell}

你会得到这张图片:

如果要更改项目使用的颜色,请查看 label2rgb 命令的 colormap 属性。