[英]Color quantization of an image using K-means clustering (using RGB features)
是否可以使用matlab对图像的RGB +空间特征进行聚类?
注意:我想使用kmeans
进行聚类。
事实上,基本上我想做一件事,我想得到这个形象
由此
我想你正在寻找颜色量化。
[imgQ,map]= rgb2ind(img,4,'nodither'); %change this 4 to the number of desired colors
%in quantized image
imshow(imgQ,map);
结果:
使用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,[]);
kmeans
结果:
如果要将距离约束添加到kmeans
,代码将略有不同。 基本上,您还需要连接相应像素值的像素坐标。 但请记住,在为每个像素指定最近的质心时,只分配颜色,即前3个维度,而不是最后2个维度。显然,这没有意义。 代码与之前的代码非常相似,请注意更改并理解它们。
[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,[]);
距离约束的kmeans
结果:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.