% make_data.m by Seiji Hotta
close all;
clear all;

coef=[0.2989;0.5870;0.1140]; % for gray-scaling
imsize=15;  % size of small images
nclass=10;  % number of classes per animal
trailist=[1:2:41]; % training image list

traicount=1;
testcount=1;
for animal = 1 : 3
  % image loading and masking
  for jj = 1 : nclass
    if animal == 1, aniname='dog';, end
    if animal == 2, aniname='cow';, end
    if animal == 3, aniname='horse';, end
    
    impath=sprintf('./eth80-cropped-close128/%s%d/*.png',aniname,jj);
    mppath=sprintf('./eth80-cropped-close128/%s%d/maps/*.png',aniname,jj);
    
    imlist=dir(impath);
    mplist=dir(mppath);
    nimg=size(imlist,1);
    X=zeros(imsize.^2,nimg);
    for ii = 1 : nimg
      imfile=sprintf('./eth80-cropped-close128/%s%d/%s',aniname,jj,imlist(ii).name);
      IMG=imread(imfile);
      IMG=uint8(IMG(:,:,1).*coef(1)+IMG(:,:,2).*coef(2)+IMG(:,:,3).*coef(3));
      mpfile=sprintf('./eth80-cropped-close128/%s%d/maps/%s',aniname,jj,mplist(ii).name);
      MP=imread(mpfile);
      if size(MP,3)==3
        MP=uint8(MP(:,:,1).*coef(1)+MP(:,:,2).*coef(2)+MP(:,:,3).*coef(3));
      end
      % image x mask for background substraction
      IMG=IMG.*(MP./255);
      % image resize with nearest neighbors
      scal = 128./imsize + eps;% actual scaling between images, eps is needed
      IMG = IMG(floor(scal/2:scal:end)+1,floor(scal/2:scal:end)+1,:);
      % image vectorization
      X(:,ii)=IMG(:);
      % uncomment for showing images
      %subplot(7,6,ii),imshow(IMG);,pause(0.01)
    end
    % training data
    trai(traicount).X=X(:,trailist);
    trai(traicount).label=traicount;
    % test data
    for sp = 2 : 2 : 22
      testlist=[sp:2:sp+18];
      test(testcount).X=X(:,testlist);
      test(testcount).label=traicount;
      testcount=testcount+1;
    end
    fprintf(2,'%s traicount=%d testcount=%d\n',aniname,traicount,testcount-1);
    traicount=traicount+1;
  end
end
% save data
save('-mat','doubutsu.mat','trai','test');
