理论知识参考:【基础教程】基于matlab图像处理图像分割【含Matlab源码 191期】
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(dimrand(k, 1));%初始means是k行k列随机数作为聚类中心
rand_y = ceil(dimrand(k, 1));
for i = 1:k
means(i,:) = A(rand_x(i), rand_y(i), ;%在图像中找到初始聚类中心
end
for 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)=