我正在使用基于颜色的图像分割中的K-means聚类算法。我有一张2D图像,其中包含三种颜色:黑色、白色和绿色。这是图片:
我希望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)
谢谢。