资源简介

K-means应用于图像处理matlab程序,自动将图像颜色聚类至少数K种

资源截图

代码片段和文件信息

clear all; close all; clc;
A = double(imread(‘bird_small.tiff‘));% Load small image
% A = double(imread(‘bird_large.tiff‘));% Load large image

dim = size(A1); % number of pixels in picture‘s length/width
k = 16; % number of colors to represent

means = zeros(k 3); % Initialize means to randomly-selected colors in the original photo.
rand_x = ceil(dim*rand(k 1));
rand_y = ceil(dim*rand(k 1));
for i = 1:k
    means(i:) = A(rand_x(i) rand_y(i) :);
end

for itr=1:100
    s_x=zeros(k3);
    s_ind=zeros(k1);
    for i=1:dim
        for j=1:dim
            r=A(ij1);g=A(ij2);b=A(ij3);
            [val ind]=min(sum((repmat([rgb]k1)-means).^22));
            s_x(ind:)=s_x(ind:)+[rgb];
            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).^22)))
    if d<1e-5
        break
    end
    means=s_x;   
end
means = round(means);
itr

figure; hold on
for i=1:k
   col = (1/255).*means(i:);
   rectangle(‘Position‘ [i 0 1 1] ‘FaceColor‘ col ‘EdgeColor‘ col);
end
axis off

% Recalculate the big image and display
large_image = double(imread(‘bird_large.tiff‘));
figure;imshow(uint8(round(large_image)));
large_dim = size(large_image 1);
for i = 1:large_dim
    for j = 1:large_dim
        r = large_image(ij1); g = large_image(ij2); b = large_image(ij3);
        [val ind]=min(sum((repmat([rgb]k1)-means).^22));
        large_image(ij:) = means(ind:);
    end 
end
figure;imshow(uint8(round(large_image))); hold off
imwrite(uint8(round(large_image)) ‘bird_kmeans.jpg‘);% Save image

 属性            大小     日期    时间   名称
----------- ---------  ---------- -----  ----
     目录           0  2015-03-13 10:46  K-means图像处理\
     文件      868678  2010-12-17 05:43  K-means图像处理\bird_large.tiff
     文件       49442  2010-12-17 05:43  K-means图像处理\bird_small.tiff
     文件        1720  2015-03-13 10:46  K-means图像处理\kmeans_my.m

评论

共有 条评论