1 简介
对图像进行颜色区域分割.将图像转换到CIE Lab颜色空间,用K均值聚类分析算法对描述颜色的a和b通道进行聚类分析;通过提取各个颜色区域独立成为单色的新图像,对图像进行分割处理.实验结果表明,在CIE Lab空间使用K—means聚类算法可以有效地分割彩色纺织品图像的颜色区域.
2 完整代码
clear all; close all; clc;A = double(imread('bird_small.tiff'));% 载入图片dim = size(A,1); % 图片行数k = 16; % 颜色分类的层数means = zeros(k, 3); % Initialize means to randomly-selected colors in the original photo.rand_x = ceil(dim*rand(k, 1));%初始means是k行k列随机数作为聚类中心rand_y = ceil(dim*rand(k, 1));for i = 1:k means(i,:) = A(rand_x(i), rand_y(i), :);%在图像中找到初始聚类中心endfor itr=1:100 s_x=zeros(k,3); s_ind=zeros(k,1); for i=1:dim for j=1:dim r=A(i,j,1);g=A(i,j,2);b=A(i,j,3); [val ind]=min(sum((repmat([r,g,b],k,1)-means).^2,2)); %repmat(A,k,1)对A矩阵进行k行的复制 s_x(ind,:)=s_x(ind,:)+[r,g,b]; s_ind(ind)=s_ind(ind)+1; end end for ii=1:k if s_ind(ii)>0 s_x(ii,:)=s_x(ii,:)./s_ind(ii); end end d=sum(sqrt(sum((s_x-means).^2,2)));%计算距离 if d<1e-5 break end means=s_x; endmeans = round(means);itrfigure; hold onfor i=1:k col = (1/255).*means(i,:); rectangle('Position', [i, 0, 1, 1], 'FaceColor', col, 'EdgeColor', col);endaxis offlarge_image = double(imread('bird_large.tiff'));figure;subplot(121);imshow(A,[]);title('原图')large_dim = size(large_image, 1);for i = 1:large_dim for j = 1:large_dim r = large_image(i,j,1); g = large_image(i,j,2); b = large_image(i,j,3); [val ind]=min(sum((repmat([r,g,b],k,1)-means).^2,2)); large_image(i,j,:) = means(ind,:); end endsubplot(122);imshow(uint8(round(large_image)));title('Kmean分割图')imwrite(uint8(round(large_image)), 'bird_kmeans.jpg');% Save image
3 仿真结果
4 参考文献
博主简介:擅长智能优化算法、神经网络预测、信号处理、元胞自动机、图像处理、路径规划、无人机等多种领域的Matlab仿真,相关matlab代码问题可私信交流。
部分理论引用网络文献,若有侵权联系博主删除。