在 MATLAB 中为分割图片分配颜色

Assigning colors to segmented pictures in MATLAB

我正在使用 MATLAB 处理颜色分割。我使用了基于 this 文档的 k 均值聚类,并以代码方式走到了这一步;

global imgRGB;
global imgLAB;
img = imgRGB;

cform = makecform('srgb2lab');
imgLAB = applycform(img, cform);
ab = double(imgLAB(:,:,2:3));
rows = size(ab,1)
cols = size(ab,2);
ab = reshape(ab, rows*cols, 2);
cluster = 5;
[idx center] = kmeans(ab, cluster, 'distance', 'sqEuclidean', 'Replicates', 5);
label = reshape(idx, rows, cols);
figure; imshow(label, []);
imgSeg = cell(5);
rgb_label = repmat(pixel_labels, [1 1 3]);
for k=1:cluster
    color = img;
    color(rgb_label ~= k) = 0;
    imgSeg{k} = color;
end
figure; 
imshow(imgSeg{1});

我将图像作为输入,这就是它被定义为全局的原因。

对于 link 中的彩色图像,它会生成灰度输出。

我认为它将灰色调指定为颜色,但我需要为每个簇指定一种颜色。我的意思不是灰色调,而是一种颜色。我怎样才能做到这一点?

当直接显示标签时,你应该为你的图形使用不同的colormap

尝试:

figure; 
imshow(label, []);
colormap( rnad(max(imgSeg{1}(:))+1, 3) ); % use random color map

但是,如果您希望将 pixel_labels 转换为 RGB 图像(每个像素 3 个颜色通道),您需要使用 ind2rgb(而不是将标签复制到所有通道)。将 rgb_label = repmat(pixel_labels, [1 1 3]); 替换为

rgb_label = ind2rgb(pixel_labels, rand(max(pixel_labels(:)),3));