%% k-means section
% Here we separate water pixels from land pixels using the k-means
% algorithm

display = 0;

test = ima2mat('19BASEIMAGES/BASEIMAGES/landsattarasconC1');
nrow = size(test, 1);
ncol = size(test, 2);

% Chargement de toutes les images
ims = zeros(8, nrow, ncol);
mats = zeros(nrow * ncol, 8);
for i = 1 : 8
    ims(i,:,:) = ima2mat(strcat('19BASEIMAGES/BASEIMAGES/landsattarasconC', int2str(i)));
    if display
        figure();
        colormap(gray(256));
        image(reshape(ims(i,:,:), nrow, ncol));
    end;
    temp = ims(i,:,:);
    mats(:, i) = temp(:);
end;

% Class 0 is water, class 1 is land
c1 = [ 190 179 ]; c2 = [ 277 229 ];

centroids = zeros(2, 8);

% mats = ims(4,:,:);
% mats = mats(:);

centroids(1,:) = mats(c1(1) * ncol + c1(2), :);
centroids(2,:) = mats(c2(1) * ncol + c2(2), :);

done = 0;

while ~done
    done = 1;
    classes = kmeans2(mats, centroids);
    for i = 1 : size(centroids, 1)
        class_i = mats(find(classes == i), :);
        new_centroid_i = sum(class_i) / size(class_i, 1);
        if centroids(i,:) ~= new_centroid_i
            done = 0;
        end;
        centroids(i,:) = new_centroid_i;
    end;
end;

figure();
colormap(gray(2));
image(reshape(classes, nrow, ncol));
