close all
clear all
clc
%%
srcFiles = dir('G:\6.szemeszter\BBCA\Nonogram\Mobile\*.jpg');
% srcFiles = dir('G:\6.szemeszter\BBCA\Nonogram\OneByOne\*.jpg');
p=1;
%% Nacitani obrazu a binarizace
filename = strcat('G:\6.szemeszter\BBCA\Nonogram\Mobile\',srcFiles(p).name)
% filename = strcat('G:\6.szemeszter\BBCA\Nonogram\OneByOne\',srcFiles(p).name)

I = imread(filename);


I=rgb2gray(I);
adI=imbinarize(I,'adaptive','ForegroundPolarity','dark');

adI=1-adI;% negativ obrazu

LCC = bwareafilt(logical(adI),1);
%BOUNDINGBOX CHOP
box=regionprops(LCC,'BoundingBox');
I=I(ceil(box.BoundingBox(2)):floor(box.BoundingBox(2))+box.BoundingBox(4),ceil(box.BoundingBox(1)):floor(box.BoundingBox(1))+box.BoundingBox(3));
LCC=LCC(ceil(box.BoundingBox(2)):floor(box.BoundingBox(2))+box.BoundingBox(4),ceil(box.BoundingBox(1)):floor(box.BoundingBox(1))+box.BoundingBox(3));
adI=adI(ceil(box.BoundingBox(2)):floor(box.BoundingBox(2))+box.BoundingBox(4),ceil(box.BoundingBox(1)):floor(box.BoundingBox(1))+box.BoundingBox(3));
% figure;imshow(LCC);

%Zjistovani velikosti stran mrizky
complement=medfilt2(1-LCC);
CC = bwconncomp(complement);
numPixels = cellfun(@numel,CC.PixelIdxList);
avg = trimmean(numPixels,30);
SideSize=round(sqrt(avg));
%% ROTATE a BIT
[H,T,R] = hough(LCC);
P = houghpeaks(H,10,'threshold',ceil(0.2*max(H(:))));
lines = houghlines(LCC,T,R,P,'FillGap',SideSize,'MinLength',round(SideSize/2));
M=mode(P(:,2));
I=imrotate(I,M);
adI=imrotate(adI,M);
LCC=imrotate(LCC,M);
clear M P T H;
%% ONLY NUMBERS
onlynum=adI;
if SideSize>75
    n=7;
else
    n=5;
end

onlynum=imopen(onlynum,ones(n));
CC = bwconncomp(onlynum);
numPixels = cellfun(@numel,CC.PixelIdxList);
[~,indexOfMax] = max(numPixels);
onlynum(CC.PixelIdxList{indexOfMax}) = 0;
clear indexOfMax
avg=trimmean(numPixels,30);
onlynum=double(bwareafilt(logical(onlynum),[avg/3 avg*3]));
%figure;imshow(onlynum)
% dalsi otoceni podle cisla
%CISLA MOHOU BYT JENOM VLEVO A NAHORE
hor=sum(onlynum,1);
ver=sum(onlynum,2);
[~,hmx]=max(hor);
[~,vmx]=max(ver);
if hmx<length(hor)/2 && vmx<length(ver)/2
    
else
    if hmx>length(hor)/2 && vmx<length(ver)/2
        onlynum=rot90(onlynum);
        LCC=rot90(LCC);
        adI=rot90(adI);
        I=rot90(I);
    else
        if hmx>length(hor)/2 && vmx>length(ver)/2
            onlynum=rot90(onlynum,2);
            LCC=rot90(LCC,2);
            adI=rot90(adI,2);
            I=rot90(I,2);
        else onlynum=rot90(onlynum,3);
             LCC=rot90(LCC,3);
             adI=rot90(adI,3);
             I=rot90(I,3);
        end
    end
end
% figure;imshow(onlynum);
hor=sum(onlynum,1);
ver=sum(onlynum,2);
vermax=place(ver);
hormax=place(hor);
% ERRORY PRO VERMAX/HORMAX
if vermax==length(ver)
     error('Error. No vermax found.');
end
if hormax==length(hor)
     error('Error. No hormax found.');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%SEGMENTACE OBRAZU, podle toho, kde jsou cislice
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%jenom cislice
hornicisla=onlynum(find(ver,1):vermax+ceil(SideSize*2/3),hormax-ceil(SideSize/2):end);
levecisla=onlynum(vermax-ceil(SideSize/2):end,find(hor,1):vermax+ceil(SideSize*2/3));
%cely obraz
% hornicislaFULL=adI(find(ver,1):vermax+ceil(SideSize),hormax-ceil(SideSize/2):end);
% levecislaFULL=adI(vermax-ceil(SideSize/2):end,find(hor,1):vermax+ceil(SideSize));
% clear ver hor vermax hormax vmx hmx
% figure('Name','horni/dolni cisla');imshow(hornicisla);
% figure('Name','prave/leve cisla');imshow(levecisla);



%%  OCR

horres = ocr(hornicisla, 'CharacterSet', '0123456789', 'TextLayout','Block');
levres = ocr(levecisla, 'CharacterSet', '0123456789', 'TextLayout','Block');

%ERRORY pro ORC
if isempty(horres.Text)
     error('Error. OCR did not find any results in "hornicisla".');
end
if isempty(levres.Text)
     error('Error. OCR did not find any results in "levedisla".');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% HORNI CAST%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Sort the character confidences
[HsortedConf, HsortedIndex] = sort(horres.CharacterConfidences, 'descend');

% Keep indices associated with non-NaN confidences values + pridana
% podminka pro charconf
HindexesNaNsRemoved = HsortedIndex( ~isnan(HsortedConf) & HsortedConf>0.5 );

% Select the top ten results
hordigits = num2cell(horres.Text(HindexesNaNsRemoved));
horbboxes = horres.CharacterBoundingBoxes(HindexesNaNsRemoved, :);

horIdigits = insertObjectAnnotation(hornicisla, 'rectangle', horbboxes, hordigits);
figure;
imshow(horIdigits);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% LEVI CAST%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Sort the character confidences
[LsortedConf, LsortedIndex] = sort(levres.CharacterConfidences, 'descend');

% Keep indices associated with non-NaN confidences values + pridana
% podminka pro charconf
LindexesNaNsRemoved = LsortedIndex( ~isnan(LsortedConf) & LsortedConf>0.5 );

% Select the top ten results
levdigits = num2cell(levres.Text(LindexesNaNsRemoved));
levbboxes = levres.CharacterBoundingBoxes(LindexesNaNsRemoved, :);

levIdigits = insertObjectAnnotation(levecisla, 'rectangle', levbboxes, levdigits);
figure;
imshow(levIdigits);



%end
%%
ToSortLev=[levbboxes,cellfun(@str2num,levdigits)']; 
ToSortHor=[horbboxes,cellfun(@str2num,hordigits)'];

%% SORT LEVE CISLA
ToSortLev=sortrows(ToSortLev,[2 1]);
    
cislaL{1}(1,1:5)=ToSortLev(1,:);
p=2;
k=1;
for i=2:size(ToSortLev,1)
   if (ToSortLev(i,2)-ToSortLev(i-1,2))<SideSize*0.6
       cislaL{k}(p,1:5)=ToSortLev(i,:);
       p=p+1;
   else
       k=k+1;
       p=1;
       cislaL{k}(p,1:5)=ToSortLev(i,:);
       p=p+1;
   end
end


%%%%%%%%%%%%%%%%%%%%%%%%%%%
% BOCNI CISLA DO CELL ARRAY
%%%%%%%%%%%%%%%%%%%%%%%%%%%
    FNindxL=zeros(1,length(cislaL));
    cislaLL{1,length(cislaL)}=[];
    for i=1:length(cislaL)
        cislaL{i}=sortrows(cislaL{i},-1);
        if size(cislaL{i},1)>1  
            sz=size(cislaL{i},1);
            j=2;
            while j<=sz
                if cislaL{1,i}(j-1,1)-cislaL{1,i}(j,1)<SideSize/2
                    cislaL{1,i}(j-1,5)=str2num(strcat(num2str(cislaL{1,i}(j,5)),num2str(cislaL{1,i}(j-1,5))));
                    cislaL{1,i}(j,:)=[];
                    sz=sz-1;
                end
                j=j+1;
            end
        end
        FNindxL(1,i)=cislaL{i}(1);
        cislaLL{i}=fliplr(cislaL{i}(:,5)');
    end




%% SORT HORNI CISLA
ToSortHor=sortrows(ToSortHor,[1 2]);

cislaH{1}(1,1:5)=ToSortHor(1,:);
p=2;
k=1;
for i=2:size(ToSortHor,1)
   if (ToSortHor(i,1)-ToSortHor(i-1,1))<SideSize*0.6
       cislaH{k}(p,1:5)=ToSortHor(i,:);
       p=p+1;
   else
       k=k+1;
       p=1;
       cislaH{k}(p,1:5)=ToSortHor(i,:);
       p=p+1;
   end
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%
% HORNI CISLA DO CELL ARRAY
%%%%%%%%%%%%%%%%%%%%%%%%%%%
    FNindxH=zeros(1,length(cislaH));
    cislaHH{1,length(cislaH)}=[];
    for i=1:length(cislaH)
        cislaH{i}=sortrows(cislaH{i},-2);
        if size(cislaH{i},1)>1 
            sz=size(cislaH{i},1);
            j=2;
            while j<=sz
                if abs(cislaH{1,i}(j-1,2)-cislaH{1,i}(j,2))<SideSize/2
                    if cislaH{1,i}(j-1,1)<cislaH{1,i}(j,1)
                        cislaH{1,i}(j-1,5)=str2num(strcat(num2str(cislaH{1,i}(j-1,5)),num2str(cislaH{1,i}(j,5))));
                    else
                        cislaH{1,i}(j-1,5)=str2num(strcat(num2str(cislaH{1,i}(j,5)),num2str(cislaH{1,i}(j-1,5))));
                    end
                    cislaH{1,i}(j,:)=[];
                    sz=sz-1;
                end
                j=j+1;
            end
        end
 
        FNindxH(1,i)=cislaH{i}(1,2);
        cislaHH{i}=fliplr(cislaH{i}(:,5)');
    end
%     clear sz
%     celldisp(cislaLL')
%     celldisp(cislaHH')
%     figure;imshow(adI);
%    pause;
%    close all
%    clc
%    clearvars -except p srcFiles

%% FORMATOVANI INPUTU
%https://github.com/Samjayyy/logicpuzzles/tree/master/nonogram
FILE = fopen('tosolve.txt','w');

prvniradek=strcat(num2str(length(cislaLL)),{' '},num2str(length(cislaHH)));
fprintf(FILE, '%s\r\n', prvniradek{:});

LL=cellfun(@mat2str,cislaLL,'UniformOutput',false)';
LL=cellfun(@(x)regexprep(x, '\[(.*)\]', '$1'),LL,'UniformOutput',false);
fprintf(FILE,'%s\r\n',LL{:});

HH=cellfun(@mat2str,cislaHH,'UniformOutput',false)';
HH=cellfun(@(x)regexprep(x, '\[(.*)\]', '$1'),HH,'UniformOutput',false);
fprintf(FILE,'%s\r\n',HH{:});
    
vypln{length(cislaLL),1}=[];
for i=1:length(cislaLL)
    vypln{i}(1)=num2str(0);
    for j=2:length(cislaHH)
        vypln{i}=strcat(vypln{i},num2str(0));
    end
end
fprintf(FILE,'%s\r\n',vypln{:});
clear prvniradek LL HH vypln
fclose(FILE);
pause

%https://github.com/Samjayyy/logicpuzzles/tree/master/nonogram
%% SOLVER
 nonogramsolver.Main.main('');

%% SHOW SOLUTION

data=fileread('G:\6.szemeszter\BBCA\matlab scripts\solved.txt');

delete solved.txt 
delete tosolve.txt

data=data(find(~isspace(data)));
if numel(data)~=length(cislaLL)*length(cislaHH)
     error('Error. Solution does not contain enough elements to reconstruct the picture');
else
solution=zeros(length(cislaLL),length(cislaHH));

for i=1:length(cislaLL)
    solution(i,:)=data((i-1)*length(cislaHH)+1:(i-1)*length(cislaHH)+length(cislaHH));
end

clearvars -except cislaHH cislaLL adI LCC SideSize solution srcFiles
solution(solution==48)=1;
solution(solution==35)=0;
solution=logical(solution);
%%
solutionIMG=imresize(solution,SideSize,'box');
figure;imshow(solutionIMG);
[rows, columns, numberOfColorChannels] = size(solutionIMG);
hold on;

for row = 1 : SideSize : size(solutionIMG,1)
    line([1, columns], [row, row], 'Color', 'k', 'LineWidth', 1);
end
for col = 1 : SideSize : size(solutionIMG,2)
    line([col, col], [1, rows], 'Color', 'k', 'LineWidth', 1);
end
line([1, columns], [size(solutionIMG,1), size(solutionIMG,1)], 'Color', 'k', 'LineWidth', 1);
line([size(solutionIMG,2), size(solutionIMG,2)], [1, rows], 'Color', 'k', 'LineWidth', 1);

end
%% NAPOVEDA

napoveda=uint8(ones(size(solutionIMG,1),size(solutionIMG,2),3)*255);
figure('Name','Napoveda');

for row = 1 : SideSize : size(solutionIMG,1)
    napoveda(row,:,:)=0;
end
for col = 1 : SideSize : size(solutionIMG,2)
    napoveda(:,col,:)=0;
end

napoveda(end,:,:)=0;
napoveda(:,end,:)=0;
imshow(napoveda);hold on
while(1)
    [y,x]=ginput(1);
    if(x<0 ||y<0 || x>size(solutionIMG,1) || y>size(solutionIMG,2))
        close
        break;
    end
    if(solutionIMG(floor(x),floor(y))==0)
        napoveda(floor(x/SideSize)*SideSize+1:(ceil(x/SideSize))*SideSize,floor(y/SideSize)*SideSize+1:(ceil(y/SideSize))*SideSize,3)=0;
        napoveda(floor(x/SideSize)*SideSize+1:(ceil(x/SideSize))*SideSize,floor(y/SideSize)*SideSize+1:(ceil(y/SideSize))*SideSize,1)=0;
    else
        napoveda(floor(x/SideSize)*SideSize+1:(ceil(x/SideSize))*SideSize,floor(y/SideSize)*SideSize+1:(ceil(y/SideSize))*SideSize,3)=0;
        napoveda(floor(x/SideSize)*SideSize+1:(ceil(x/SideSize))*SideSize,floor(y/SideSize)*SideSize+1:(ceil(y/SideSize))*SideSize,2)=0;
    end
    imshow(napoveda);
end