%% SPLIT & MERGE
close all
clear all
X = zeros(32);
X(4:12,4:12)=150;

X(18:25,18:25)=150;

X = uint8(X);
X = imnoise(X,'gaussian',0, 0.002);
R = mysplit(X,15,40);

mean2(X(4:12,4:12))
mean2(X(18:25,18:25))
std2(X(4:12,4:12))
std2(X(18:25,18:25))
mean2(X)
std2(X)

figure
subplot(1,2,1)
imshow(X,[])
subplot(1,2,2)
imshow(R,[])

%% REGION GROWING
clc
close all
clear all
img =imread('coronal.png');

figure
imagesc(img)
[x,y] = ginput(1);
x = floor(x);
y = floor(y);

R = my_region_growing(img, x, y, 25);

figure
subplot(1,2,1)
imshow(img,[])
subplot(1,2,2)
imshow(R,[])

%% KNN
clc
close all
clear all
load('Training.mat');
load('Testing.mat');
figure
subplot(1,2,1)
plot(Train(label==0,1),Train(label==0,2),'r+');
hold on;
plot(Train(label==1,1),Train(label==1,2),'g+');
hold off
title('Training','FontSize',14,'fontweight','bold')

subplot(1,2,2)
plot(Test(label==0,1),Test(label==0,2),'r+');
hold on;
plot(Test(label==1,1),Test(label==1,2),'g+');
hold off
title('Testing','FontSize',14,'fontweight','bold')


labels_test = my_knn(Train,label,Test,11);

figure
plot(Test(label==0,1),Test(label==0,2),'r+');
hold on;
plot(Test(label==1,1),Test(label==1,2),'g+');

plot(Test(labels_test==0,1),Test(labels_test==0,2),'ro');
plot(Test(labels_test==1,1),Test(labels_test==1,2),'go');

title('Results','FontSize',14,'fontweight','bold')

error = sum(abs(labels_test-label)) / length(label) *100

%% KNN2

clc
close all
clear all
load('Training.mat');
load('Testing.mat');

l = length(label);
label2 = label;
r = rand(l,1)> 0.98;
label2(r) = abs(label2(r)-1);

figure
subplot(1,2,1)
plot(Train(label2==0,1),Train(label2==0,2),'r+');
hold on;
plot(Train(label2==1,1),Train(label2==1,2),'g+');
hold off
title('Training','FontSize',14,'fontweight','bold')

subplot(1,2,2)
plot(Test(label==0,1),Test(label==0,2),'r+');
hold on;
plot(Test(label==1,1),Test(label==1,2),'g+');
hold off
title('Testing','FontSize',14,'fontweight','bold')


labels_test = my_knn(Train,label2,Test,1);

figure
plot(Test(label==0,1),Test(label==0,2),'r+');
hold on;
plot(Test(label==1,1),Test(label==1,2),'g+');

plot(Test(labels_test==0,1),Test(labels_test==0,2),'ro');
plot(Test(labels_test==1,1),Test(labels_test==1,2),'go');

title('Results','FontSize',14,'fontweight','bold')

error = sum(abs(labels_test-label)) / length(label) *100

%% K-means
clc;
clear all
close all;
%img = imread('penguin.jpg');
img = imread('peppers.png');
img = imresize(img,0.5);
[x,y,c] = size(img);

img2 = reshape(img,[x*y,c]);
%figure;
%scatter3(img2(:,1),img2(:,2),img2(:,3),[],img2/256.0,'filled')
k  = 5;
M = (rand(k,3)*255);
labels= my_kmeans(img2, M,k);
labels = reshape(labels,[x,y,3]);

figure
subplot(1,2,1)
imshow(img)
subplot(1,2,2)
imshow(labels)
