%% 4 2018
im = imread('kefir/sudo.jpg');

% find boxes in some way...

% cut up boxes
xx1 = linspace(52,510,6);
yy1 = linspace(49,508,6);
[X,Y]=meshgrid(xx1,yy1);
sudos = cell(6,6);
for iii = 1:6
    for jjj = 1:6
        indi = round(Y(iii,jjj)-40):round(Y(iii,jjj)+40);
        indj = round(X(iii,jjj)-40):round(X(iii,jjj)+40);
        sudos{iii,jjj}=double(im(indi,indj,:))/255;
    end
end

for iii = 1:6
    for jjj = 1:6
        imshow(sudos{iii,jjj});
        drawnow
        pause
    end
end

% features
bigX = [];
for iii = 1:6
    for jjj = 1:6
        tmp = imresize(sudos{iii,jjj},[11 11]);
        bigX = [bigX;tmp(:)'];
    end
end

disp(size(bigX))
disp(11*11*3)
% six symbols + background = 7 classes
[IDX, C] = kmeans(bigX, 7);

for iii = 1:7
    imshow(imresize(reshape(C(iii,:),[11 11 3]),[81 81]));
    drawnow
    pause
end
% number tableau
disp(reshape(IDX,6,6)')

% solve sudoku...

%% 3 2018
load('kefir/classdata.mat');

% classify using knn
IDX = knnsearch(X',x,'k',5);
disp(Y(IDX))

% classify using gaussian ML
X0 = X(:,Y==0)';
X1 = X(:,Y==1)';

m0 = mean(X0)
m1 = mean(X1)
X0n = X0-m0;
X1n = X1-m1;

v0 = var(X0n(:))
v1 = var(X1n(:))

p0 = mvnpdf(x, m0, v0*eye(6))
p1 = mvnpdf(x, m1, v1*eye(6))

%% 5 2018

imo = imread('kefir/grayoriginal.tif');
imt = imread('kefir/graytransformed.tif');
imo = double(imo)/255;
imt = double(imt)/255;
figure(1)
imshow([imo imt])

Y = imt(:);
X = imo(:);

figure(2)
clf
plot(X,Y,'.')
nn = length(X);

% least squares y = ax+(1-a)*x^2 = a(x-x^2)+x^2 

A = X-X.^2;
rhs = Y-X.^2;
a_ls = A\rhs;
xx = 0:.1:1;
figure(2)
hold on
ll=plot(xx,a_ls*xx+(1-a_ls)*xx.^2);
set(ll,'LineWidth',2);


% RANSAC

iter = 1000;
bnd = 0.05;

bestins = 0;

for iii = 1:iter
    id = randi(nn,1);
    a = gray_polyfit(X(id),Y(id));
    ins = sum(abs(a*X+(1-a)*X.^2-Y)<bnd);
    if ins>bestins
        bestins = ins;
        besta = a;
    end
end

figure(2)
hold on
xx = 0:.1:1;
ll=plot(xx,besta*xx+(1-besta)*xx.^2);
set(ll,'LineWidth',2);

imt2 = besta*imo+(1-besta)*imo.^2;
figure(1)
imshow([imo imt imt2])

%% 4 2017
load tentadata2017okt.mat
im0 = double(blood)/255;
imshow(im0)

se = strel('disk',40);
im1 = imclose(im0,se);
imshow(im1)
im2 = im1-im0;

im3 = im2>0.2;
se2 = strel('disk',3); 
im4 = imopen(im3,se2);
segs = bwlabel(im4);
imagesc(segs)
disp(max(segs(:)))






