% source images

clear;
close all;
addpath ./HoGPackage

idx = 7; % choose your category

dataNames    = {'dogs','cow','butterfly_dragonfly_bug','bike_car_motor_Scooter', 'faces_butterflies_horses', 'horse_pigeons_eagles_swans_fishes','DeerCatWolf'};
gtNumCluster = [2, 2, 3, 4, 3, 5, 3];
windowsizeList = {[100, 110], [100, 110],[100, 110],[70, 90],[100, 110],[60, 70],[100, 100]};
gtClusterIdxFile = 'gt.txt';


resultPath = './resultHoG';
if ~exist(resultPath,'dir')
    mkdir(resultPath)
    mkdir(fullfile(resultPath,'img'));
else
    rmdir(resultPath,'s')
    mkdir(resultPath)
    mkdir(fullfile(resultPath,'img'));
end


% s = matlabpool('size');
% if s==0
%     matlabpool('open');
% end

for ii=1:10
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

seed = ii
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

rng(seed);
dataName = dataNames{idx};
numClusters = gtNumCluster(idx);
windowsize = windowsizeList{idx};

maxIter = 30;
%cellsize = 1; 
fprintf('========= %s run clustering experiments on %s\n', dataName);
    
% read images
inPath = ['.' filesep 'positiveImages' filesep dataName];
imgFiles = dir(fullfile(inPath,'*.jpg'));
gtFile = ['.' filesep 'positiveImages' filesep dataName filesep gtClusterIdxFile];
    
if isempty(imgFiles)
        error('Can not find images');
end
numImg = length(imgFiles);

fv = [];    

for i = 1 : numImg
       copyfile(fullfile(inPath,imgFiles(i).name),fullfile(resultPath,'img',imgFiles(i).name));
       fprintf('Extracting HoG features for image %d \n', i); 
       curImgFile = ['.' filesep 'positiveImages' filesep dataName filesep imgFiles(i).name];  

       im = imread(curImgFile);
       im = imresize(im, windowsize);
       
       if size(im,3)==1
          im=gray2rgb(im); 
       end
       
       im=rgb2gray(im);
       im=im2double(im);
       im = im - mean(im(:)); % global image normalization
       im = im / std(im(:));
   
       %descrip=HOG(im,5,5, 9);
       descrip=HOG(im,6,6, 9);
       fv=[fv; descrip(:)'];  
 
end       
    
    
[clusters, probs]  = clustering_OrigEM_HOG(numClusters, fv, maxIter,resultPath,imgFiles, windowsize);
       
%% evaluation
[purity(ii), entropy(ii)] = evaluateClusteringHoG(probs, imgFiles, gtFile)  

end
    
disp(['mean of purity: ' num2str(mean(purity)) '. standard error of purity: ' num2str(std(purity))]);
disp(['mean of entropy: ' num2str(mean(entropy)) '. standard error of entropy: ' num2str(std(entropy))]);
