【问题标题】:Accurately detect color regions in an image using K-means clustering使用 K-means 聚类准确检测图像中的颜色区域
【发布时间】:2015-11-09 03:26:02
【问题描述】:

我在基于颜色的图像分割中使用 K-means 聚类。我有一个 2D 图像,它有 3 种颜色,黑色、白色和绿色。这是图片,

我想让K-means产生3个簇,一个代表绿色区域,第二个代表白色区域,最后一个代表黑色区域。

这是我使用的代码,

%Clustering color regions in an image. 

%Step 1: read the image using imread, and show it using imshow. 

img =  (imread('img.jpg'));

figure, imshow(img), title('X axis rock cut'); %figure is for creating a figure window.
text(size(img,2),size(img,1)+15,...
     'Unconventional shale x axis cut', ...
     'FontSize',7,'HorizontalAlignment','right');

 %Step 2: Convert Image from RGB Color Space to L*a*b* Color Space
 conversionform = makecform('srgb2lab'); %the form of the conversion is defined as from rgb to l a b
 lab_img = applycform(img,conversionform); %converting the rgb image to l a b image using the conversion form defined above.

 %Step 3: Classify the Colors in 'a*b*' Space Using K-Means Clustering
 ab = double(lab_img(:,:,2:3));
 nrows = size(ab,1);
 ncols = size(ab,2);
 ab = reshape(ab,nrows*ncols,2);

 nColors = 3;
% repeat the clustering 3 times to avoid local minima
[cluster_idx, cluster_center] = kmeans(ab,nColors,'distance','sqEuclidean', ...
                                      'Replicates',3);
%Step 4: Label Every Pixel in the Image Using the Results from KMEANS

%For every object in your input, kmeans returns an index corresponding to a cluster. The cluster_center output from kmeans will be used later in the example. Label every pixel in the image with its cluster_index.

pixel_labels = reshape(cluster_idx,nrows,ncols);
figure, imshow(pixel_labels,[]), title('image labeled by cluster index');

segmented_images = cell(1,3);
rgb_label = repmat(pixel_labels,[1 1 3]);

for k = 1:nColors
    color = img;
    color(rgb_label ~= k) = 0;
    segmented_images{k} = color;
end

figure, imshow(segmented_images{1}), title('objects in cluster 1');
figure, imshow(segmented_images{2}), title('objects in cluster 2');
figure, imshow(segmented_images{3}), title('objects in cluster 3');

但我没有得到所需的结果。我得到一个带有绿色区域的簇,一个带有绿色区域边界的簇,以及一个带有灰色、黑色和白色的簇。这是生成的集群。

这样做的目的是在得到正确的聚类结果后,我想用连通分量的概念统计每个区域的像素数。

所以,我的目标是知道每个颜色区域中有多少像素。我尝试了另一种更简单的方法,即获取 2D 图像的矩阵并尝试计算每种颜色的像素数。但是,我在矩阵中发现了超过 3 种 RGB 颜色,可能是因为相同颜色的像素的颜色级别略有不同。这就是我进行图像分割的原因。

谁能告诉我如何修复上面的代码以获得所需的结果?

如果您能给我一些关于如何以更简单的方式执行此操作的提示(如果有的话),我将不胜感激。

编辑:这是我为迭代图像中的每个像素而编写的代码。请注意,我使用红色、黄色、蓝色和白色 4 种颜色而不是绿色、白色和黑色,但想法是一样的。 rgb2name 是返回给定 RGB 颜色的颜色名称的函数。

im= imread ('img.jpg'); 

[a b c] = size (im); 
%disp ([a b]);
yellow=0; 
blue=0; 
white=0; 
red=0; 


for i=1:a
    for j=1:b
        x= impixel(im, i, j)/255 ;
        color= rgb2name (x);
        if (~isempty (strfind (color, 'yellow')))
            yellow= yellow+1; 
        elseif (~isempty (strfind(color, 'red')))
            red= red+1; 
        elseif (~isempty (strfind (color, 'blue')))
            blue= blue+1; 
        elseif (~isempty (strfind (color, 'white')))
           white= white+1; 
        else 
            %disp ('warning'); break; 
        end            
        disp (color);
        disp (i);
    end
end
disp (yellow)
disp (red)
disp (blue)
disp (white)

谢谢。

【问题讨论】:

  • 那是因为在您的图像中,您没有恰好有 3 种颜色。由于 jpg 压缩,您会在生成其他颜色的锐利边缘附近创建伪影。此外,在 Lab 空间中,a 和 b 在此图像中的判别性不是很大。如果您可以发布未压缩(如 png)的图像,它会容易得多(不要从 jpg 转换为 png,而是将图像直接从您的数据中保存为 png)。
  • 感谢@Miki,我尝试使用 png 图像运行代码,但仍然得到相同的结果。有没有更简单的方法来计算每个颜色区域的像素?我编写了一个代码来读取 2D 图像中的每个像素,然后调用一个函数(我下载的 .m 文件中的一个就绪函数),该函数使用最近邻方法返回颜色名称。但是图像有 655 X 653 像素,所以需要太多时间,我已经运行了 2 个小时,直到现在才完成。你有什么建议吗?谢谢。
  • 您可以非常快速地计算每种颜色的像素数。这里的问题是你不只有 3 种颜色!所以你有几个选择:1)处理未压缩的图像(没有压缩伪影); 2) 找到 3 个 主导 颜色,并将抗锯齿生成的颜色分配给其中一个。我强烈建议1)。如果您可以访问原始数据,它会简单得多。如果您不能做到 1),那么颜色(黑色、白色、绿色)是否总是完全相同?
  • 谢谢@Miki,我只有一个 .jpg 图片。我下载的功能包含许多RGB颜色变化,它可以找到颜色。不,颜色不一样,每种颜色的多个级别可能略有不同。为了解决这个问题,我删除了函数中的所有颜色值,并保留了与绿色、黑色和白色相对应的颜色值。不需要很多级别,因为该函数使用最近邻方法。我的问题是我使用 2 个 for 循环(655 X 653 迭代)遍历像素,这需要很长时间。有没有办法摆脱循环?谢谢。
  • 贴出包含两个嵌套循环的代码

标签: matlab image-processing 2d k-means image-segmentation


【解决方案1】:

我觉得这个问题很有趣,所以如果答案有点过火,我提前道歉。简而言之,k-means 是一种正确的策略,一般来说,对于想要将图像分割成离散颜色空间的问题。但是,您的示例图像主要仅包含三种颜色,每种颜色在颜色空间中都很好地分离,仅使用直方图即可轻松分割。有关使用阈值的分段,请参见下文。

您可以通过对每个矩阵求和来轻松获得像素数。例如,bCount = sum(blackPixels(:))

filename = '379NJ.png';
x = imread(filename); 
x = double(x); % cast to floating point
x = x/max(max(max(x))); % normalize

% take histogram of green dimension
g = x(:, :, 2);
c = hist(g(:), 2^8);

% smooth the hist count 
c = [zeros(1, 10), c, zeros(1, 10)];
N = 4;
for i = N+1:length(c) - N; 
   d(i - N) = mean(c(i -N:i)); 
end
d = circshift(d, [1, N/2]);

% as seen in histogram, the three colors fall nicely into 3 peaks
figure, plot(c, '.-');
[~, clusterCenters] = findpeaks(d, 'MinPeakHeight', 1e3);

% set the threshold halfway between peaks 
boundaries = [floor((clusterCenters(2) - clusterCenters(1))/2), ...
                 clusterCenters(2) + floor((clusterCenters(3) - clusterCenters(2))/2)];
thresh1 = boundaries(1)*ones(size(g))/255;
thresh2 = boundaries(2)*ones(size(g))/255;

% categorize based on threshold
blackPixels = g < thresh1;
greenPixels = g >= thresh1 & g < thresh2;
whitePixels = g >= thresh2;

【讨论】:

  • 感谢您的回答。我试图运行代码,但我得到一个错误 x = double(x)/(max(max(max(double)))) 说输入参数不够。因此,我将其设置为 x= double (x) 并运行代码。这是正确的吗?此外,当我运行代码时,我得到一条代表两个峰值的蓝色曲线。这是我应该得到的还是我做错了什么?还有一件事,我有另一张黄色、蓝色、红色和白色的图像。我想知道前 3 种颜色的数量(剩下的是白色)。所以我们有3个集群。我可以使用您发布的相同代码还是需要更改它?
  • 我修正了导致您出现错误的错字。运行代码后,为每个 *Pixels 变量尝试 imshow。它们应该看起来像附图。另外,请注意,正如我在回答中提到的,此策略适用于您提供的图像,并非通用。但是,如果将图像分离成一小部分(比如 5 个或更少)不同的颜色,那么通过直方图进行分割应该可以正常工作。但是,它可能需要针对每种情况进行调整。
  • 非常感谢。检测黄色、红色和蓝色怎么样?如果这是一个基本问题,我深表歉意,但我仍然是初学者。我可以这样做吗,我需要什么阈值?谢谢。
【解决方案2】:

这是我计算每个区域像素数的方法。鉴于(如 cmets 中所述):

  • 颜色的值 (RGB) 和颜色数量 (K) 是先验已知的
  • 压缩伪影和抗锯齿生成了额外的颜色,必须将其视为 K 种已知颜色中的最近邻。

由于您先验地知道颜色,因此您不需要 k-means。正如你的问题一样,它实际上可能会导致糟糕的结果。 @crowdedComputeeer 的方法处理了这方面的问题。

您可以使用pdist2 直接在像素值上计算最近邻。无需使用查找颜色名称的非常​​慢的函数。

这里是代码。您只需修改变量colors 即可更改颜色的数量和值。这将计算每种颜色的像素数,并输出掩码。

img =  (imread('path_to_image'));

colors = [  0 0 0;    % black
            0 1 0;    % green
            1 1 1];   % white


% % You can change the colors        
% colors = [  0 0 1;    % red
%             1 1 0;    % yellow
%             1 0 0;    % blue
%             1 1 1];   % white


% Find nearest neighbour color
list = double(reshape(img, [], 3)) / 255;
[~, IDX] = pdist2(colors, list, 'euclidean', 'Smallest', 1);
% IDX contains the indices to the nearest element


N = zeros(size(colors, 1), 1);
for i = 1 : size(colors, 1)
    % Count the number of pixels for each color
    N(i) = sum( IDX == i );
end

% This will display the number of pixels for each color
disp(N);



% Eventually build the masks
indices = reshape(IDX, [size(img,1), size(img,2)]);

figure();
szc = size(colors,1);
for i = 1 : szc
    subplot(1,szc,i);
    imagesc(indices == i);
end

结果计数:

97554     % black
16894     % green
31852     % white

生成的掩码:

【讨论】:

  • 非常感谢,这很棒。但是,我在图像中有一个红色(不完全是红色),我得到了红色 = 0 的计数。为什么会这样?谢谢。
  • @Dania 你能分享那张图片让我弄清楚吗?
  • 很遗憾,我不能分享它,因为它不是我的。我们可以在数组中包含不同的红色级别吗?也许这样它就可以捕捉到它?
  • @Dania 您可以 1)检查“几乎是红色”像素的值,并将该值用于数组中的“红色”。 2) 在colors 中添加任意数量的颜色(注意K 的数量会增加)。
  • @Dania 您将图像划分为 K 种颜色(K = 4 表示红色、黄色、蓝色、白色)。这对应于colors 的行。如果您添加一种颜色(例如深红色、红色、黄色、蓝色、白色),则 K 变为 5,您实际上是将像素分为 5 组。
【解决方案3】:

也许this project 有帮助,请尝试一下。

【讨论】:

    猜你喜欢
    • 2017-03-22
    • 2017-05-23
    • 2017-12-08
    • 2018-01-12
    • 2014-12-30
    • 2016-08-26
    • 2018-02-27
    • 2013-08-08
    • 2014-09-12
    相关资源
    最近更新 更多