Thursday, 5 April 2018

Source Code For K-Means Clustering For Images (In MATLAB)

clear all;

kc = 4;

x = double(zeros(512,512,4));
x(:,:,1) = imread('E:\band\band1.gif');
x(:,:,2) = imread('E:\band\band2.gif');
x(:,:,3) = imread('E:\band\band3.gif');
x = double(x);

centers = zeros(kc,3);
for i = 1:kc
    temp = zeros(1,2);
    temp(:) = randi([1,512],1,2);
    centers(i,1) = x(temp(1),temp(2),1);
    centers(i,2) = x(temp(1),temp(2),2);
    centers(i,3) = x(temp(1),temp(2),3);
end

for l = 1:5
    count = zeros(kc,1);
    new_c = zeros(kc,3);
    for i = 1:512
        for j = 1:512
            dist = double(zeros(kc));
            min = intmax;
            pointer = -1;
            for k = 1:kc
                v1 = [x(i,j,1),x(i,j,2),x(i,j,3)];
                v2 = [centers(k,1),centers(k,2),centers(k,3)];
                dist(k) = norm(v1-v2);
                if dist(k) < min
                    min = dist(k);
                    pointer = k;
                end
            end
            x(i,j,4) = pointer;
            count(pointer) = count(pointer) + 1;
            new_c(pointer,1) = new_c(pointer,1) + x(i,j,1);
            new_c(pointer,2) = new_c(pointer,2) + x(i,j,2);
            new_c(pointer,3) = new_c(pointer,3) + x(i,j,3);
        end
    end
    for i = 1:kc
        centers(i,1) = new_c(i,1)/count(i);
        centers(i,2) = new_c(i,2)/count(i);
        centers(i,3) = new_c(i,3)/count(i);
    end
    disp(l);
end

for i = 1:512
    for j = 1:512
        p = x(i,j,4);
        switch(p)
            case 1
                x(i,j,:) = [255,255,255,1];
            case 2
                x(i,j,:) = [255,0,0,2];
            case 3
                x(i,j,:) = [0,255,0,3];
           case 4
              x(i,j,:) = [0,0,255,4];
%             case 5
%                 x(i,j,:) = [300,0,100,5];
        end
    end
end

y = x(:,:,1:3);
imshow(y,[]);

No comments:

Post a Comment