noPCcomp=9;

blkrowsize = 5;
blkcolsize = 5;
num_cluster=4;
a=imread('gt4.jpg');

a = rgb2gray(a);
m=size(a,1);
n=size(a,2);
a=im2double(a);
figure,imshow(a);

b= im2col(a,[blkrowsize blkcolsize],'sliding');

mb=size(b,1);
nb=size(b,2);
c = b';
%k= sum(c(:,1))/16
 for i= 1:mb;                  % the no of pixels
     
      k=ones(nb,1)*sum(c(:,i))/nb; %no of subimages
  c(:,i)=c(:,i)-k;
end
 covar = cov(c);

 [pc, latent, explained] = pcacov(covar);
 
 
PCAproj=pc(:,1:noPCcomp);


projX=(PCAproj'*c'); 

projX= projX';
[distance,label,tse] = kmeans2(projX,num_cluster);

%nb is number of subimages
%ma is the size of the images
tempmat= ones(mb,nb);

for z =1:nb;
    lab=label(z);
    tempmat(:,z)=lab*(255/num_cluster);
end

tempmat=mean(tempmat);

A = col2im(tempmat,[blkrowsize blkcolsize],[m n], 'sliding');

L1 = medfilt2(A,[5 5]);

figure ,imshow(L1,gray(255));
 
 
 pcmean= mean(pc,2);
   
 pcvar = (var(pc'))';
 
 pcmeanvar = [ pcmean pcvar];
 
 
 pcgaus = ones(blkrowsize*blkcolsize,blkrowsize*blkcolsize);
 for i = 1 : blkrowsize*blkcolsize;
     pcgaus(i,:) = random('norm', pcmeanvar(i,1),tanh(pcmeanvar(i,2)),1,blkrowsize*blkcolsize);
 end

pcnew = pc* pcgaus';

PCAproj = pcnew(:,1:noPCcomp);

projX=(PCAproj'*c'); 

projX= projX';
[distance,label,tse] = kmeans2(projX,num_cluster);

%nb is number of subimages
%ma is the size of the images
tempmat= ones(mb,nb);

for z =1:nb;
    lab=label(z);
    tempmat(:,z)=lab*(255/num_cluster);
end
tempmat=mean(tempmat);

A = col2im(tempmat,[blkrowsize blkcolsize],[m n], 'sliding');

figure ,imshow(A,gray(255));

L = medfilt2(A,[3 3]);



figure ,imshow(L,gray(255));









