
imagePath = 'images/'
yourImages = dir(imagePath);
count = 1;
X = [];
for p = 3 : length(yourImages)
    IMGdir = yourImages(p).name;
    PNGdir = ['images/',IMGdir, '/']
    ANNdir = ['annotation/',IMGdir]

    d=dir([PNGdir,'/*.jpg']);
    for i = 1 : length(d),
        [path, name, ext] = fileparts(d(i).name);
        imgfilepath{count} = [PNGdir, d(i).name];
        imgfilename{count} = d(i).name;
        annfile = [ANNdir, '/', name, '.txt'];
        count = count + 1;
        
        data = load(annfile);
%        data = data ./ 256;
        data = reshape(data, 1, 20);
        X = [X; data];
    end
end

tmpX = X;
for i = 1 : size(X, 1)
    disp(num2str(i));
    tmpX(i,:) = X(i,:);
    if isempty(X(i,:) < 0)
        continue;
    end
    
    indices = find(X(i,:) > 0);
    min_diffvalue = 99999999;
    min_id = 1;
    for j = 1 : size(X, 1)
        if isempty(X(j,:) < 0)
            diffvalue = sum(abs(X(i,indices) - X(j,indices)));
            if diffvalue < min_diffvalue
                min_diffvalue = diffvalue;
                min_id = j;
            end
        end
    end
    indices = find(X(i,:) < 0);
    tmpX(i,indices) = X(min_id,indices);
end

clear X;
X(:,1) = (tmpX(:,1) + tmpX(:,2)) / 2;
X(:,2) = (tmpX(:,11) + tmpX(:,12)) / 2;
X(:,3) = (tmpX(:,3) + tmpX(:,4)) / 2;
X(:,4) = (tmpX(:,13) + tmpX(:,14)) / 2;
X(:,5) = (tmpX(:,5) + tmpX(:,6)) / 2;
X(:,6) = (tmpX(:,15) + tmpX(:,16)) / 2;
X(:,7) = (tmpX(:,6) + tmpX(:,7)) / 2;
X(:,8) = (tmpX(:,16) + tmpX(:,17)) / 2;
X(:,9) = (tmpX(:,8) + tmpX(:,9)) / 2;
X(:,10) = (tmpX(:,18) + tmpX(:,19)) / 2;
X(:,11) = (tmpX(:,9) + tmpX(:,10)) / 2;
X(:,12) = (tmpX(:,19) + tmpX(:,20)) / 2;

Z = linkage(X, 'complete', 'euclidean');