使用K均值聚类(使用RGB特征)对图像进行颜色量化

sel*_*cia 3 matlab image image-processing k-means

是否可以使用matlab对图像的RGB +空间特征进行聚类?

注意:我想kmeans用于群集.

事实上,基本上我想做一件事,我想得到这个形象

在此输入图像描述

由此

在此输入图像描述

Par*_*kar 6

我想你正在寻找颜色量化.

[imgQ,map]= rgb2ind(img,4,'nodither'); %change this 4 to the number of desired colors
                                       %in quantized image
imshow(imgQ,map);
Run Code Online (Sandbox Code Playgroud)

结果:

量化图像

使用kmeans:

%img is the original image

imgVec=[reshape(img(:,:,1),[],1) reshape(img(:,:,2),[],1) reshape(img(:,:,3),[],1)];
[imgVecQ,imgVecC]=kmeans(double(imgVec),4); %4 colors
imgVecQK=pdist2(imgVec,imgVecC); %choosing the closest centroid to each pixel, 
[~,indMin]=min(imgVecQK,[],2);   %avoiding double for loop

imgVecNewQ=imgVecC(indMin,:);  %quantizing
imgNewQ=img;
imgNewQ(:,:,1)=reshape(imgVecNewQ(:,1),size(img(:,:,1))); %arranging back into image
imgNewQ(:,:,2)=reshape(imgVecNewQ(:,2),size(img(:,:,1)));
imgNewQ(:,:,3)=reshape(imgVecNewQ(:,3),size(img(:,:,1)));

imshow(img)
figure,imshow(imgNewQ,[]);
Run Code Online (Sandbox Code Playgroud)

结果kmeans:

通过<code>kmeans</code>,代码将略有不同.基本上,您还需要连接相应像素值的像素坐标.但请记住,在为每个像素指定最近的质心时,只分配颜色,即前3个维度,而不是最后2个维度.显然,这没有意义.代码与之前的代码非常相似,请注意更改并理解它们.</p>

<pre><code>[col,row]=meshgrid(1:size(img,2),1:size(img,1));
imgVec=[reshape(img(:,:,1),[],1) reshape(img(:,:,2),[],1) reshape(img(:,:,3),[],1) row(:)   col(:)];
[imgVecQ,imgVecC]=kmeans(double(imgVec),4); %4 colors
imgVecQK=pdist2(imgVec(:,1:3),imgVecC(:,1:3));

[~,indMin]=min(imgVecQK,[],2);
imgVecNewQ=imgVecC(indMin,1:3);  %quantizing
imgNewQ=img;
imgNewQ(:,:,1)=reshape(imgVecNewQ(:,1),size(img(:,:,1))); %arranging back into image
imgNewQ(:,:,2)=reshape(imgVecNewQ(:,2),size(img(:,:,1)));
imgNewQ(:,:,3)=reshape(imgVecNewQ(:,3),size(img(:,:,1)));

imshow(img)
figure,imshow(imgNewQ,[]);
</code></pre><a target=Run Code Online (Sandbox Code Playgroud)

kmeans距离约束的结果:

在此输入图像描述