K-means 处理 RGB 图像 标签: clusteringkmeansRGBmatlab 2015-08-16 16:49 255人阅读
代码:
clear all; close all; clc; im = imread('yy.jpg'); imr = im(:,:,1); img = im(:,:,2); imb = im(:,:,3); [m,n] = size(imr); % set the parameters k = 4; tic; [mur,outlabelr,Jr] = dckmeans(imr,k,40); [mug,outlabelg,Jg] = dckmeans(img,k,40); [mub,outlabelb,Jb] = dckmeans(imb,k,40); toc; % get mu mu = [mur; mug; mub]; for i = 1:m for j = 1:n outim(i,j,1) = mu(1,outlabelb(i,j)); outim(i,j,2) = mu(2,outlabelb(i,j)); outim(i,j,3) = mu(3,outlabelb(i,j)); end end figure, imshow(im); figure, imshow(uint8(outim));
其中dckmeans为:
function [mu,outlabel,J] = dckmeans(im,k,N) copyim = im; % im = im + 1; % set the parameters [m,n] = size(im); % initialization mu = zeros(1,k); for i = 1 : k mu(i) = 255./i; end h = zeros(1,max(im(:))); y = zeros(1,max(im(:))); l = length(h); for i= 1:m for j=1:n h(im(i,j)) = h(im(i,j))+1; end end % start the iteration for r = 1:N for i = 1:l for j = 1:k delta(j) = abs( i - mu(j)); end minloc = find(delta == min(delta)); y(i) = minloc(1); end % for j = 1:k a = find(y==j); mu(j) = sum(a.*h(a))./sum(h(a)); end % J(r) = 0; for i = 1:l J(r) = J(r) + abs( i - mu(y(i))).*h(i); end %if(J(r)-J(r-1)<J(r)*0.000001) % break; %end end figure,plot(1:length(J),J); % Output outlabel= zeros(m,n); for i =1:m for j= 1:n outlabel(i,j) = y(copyim(i,j)+1); end end