%% Crop natural images
negativeFolderName = 'croppedNegativeImagePatch'; % put the cropped images into this folder, just to check everything is okay
if (exist(negativeFolderName)==0)
   mkdir(['croppedNegativeImagePatch']); 
else
   delete(['croppedNegativeImagePatch' '/*.*']); % have an empty folder 
end  
clear negativeI; % all the negative image patches 
naturalImageName = dir([naturalImageFolder '/*.jpg']);  % folder of natural images for cropping 
numNaturalImage = size(naturalImageName, 1); % number of training images 
disp(['number of natural images = ' num2str(numNaturalImage)]);
k = 0; 
for (img = 1 : numNaturalImage)
%% resize the original image and remove boundary 
    tmpIm = imread([naturalImageFolder '/' naturalImageName(img).name]); 
    if size(tmpIm,3) == 3
        tmpIm = rgb2gray(tmpIm);
    end
    [sizexOriginal sizeyOriginal] = size(tmpIm); 
    if (sizexOriginal>sizeyOriginal)  % resize the image so that the maximum length or width is less than maxSize 
        if (sizexOriginal>maxSize)
            Inatural = imresize(single(tmpIm), maxSize/sizexOriginal, 'nearest');
        else
            Inatural = single(tmpIm); 
        end
        [sizexResize sizeyResize] = size(Inatural); 
    else 
        if (sizeyOriginal>maxSize)
            Inatural = imresize(single(tmpIm), maxSize/sizeyOriginal, 'nearest');
        else
            Inatural = single(tmpIm); 
        end
        [sizexResize sizeyResize] = size(Inatural); 
    end
    Ifinal = Inatural(boundary:sizexResize-boundary, boundary:sizeyResize-boundary); % remove the boundary 
    [sizexFinal sizeyFinal] = size(Ifinal); 
%% go through image patches at different resolutions and crop 
    while ((sizexFinal>sizex)&&(sizeyFinal>sizey))
        v = var(Ifinal(:)); % variance of the image to be cropped 
        x = 1; 
        while (x+sizex<sizexFinal) % go through all image patches every (increasex, increasey) pixels 
          y = 1; 
          while (y+sizey<sizeyFinal)
            if (rand(1)<samplingRate)  % only sample a proportion of image patches 
              Itmp = Ifinal(x:x+sizex-1, y:y+sizey-1);
              if (var(Itmp(:))>lowerVar*v)  % skipping flat image patches such as sky 
                  k = k + 1; 
                  negativeI{k} = Itmp; 
                  towrite =  negativeI{k}; 
                  towrite = uint8(255 * (towrite-min(towrite(:)))/(max(towrite(:))-min(towrite(:))));
                  imwrite(towrite, ['croppedNegativeImagePatch/' num2str(100000+k) '.jpg'], 'jpeg');
              end
            end
            y = y + increasey;
          end
          x = x + increasex; 
        end
        Ifinal = imresize(Ifinal, downScaleFactor, 'nearest'); % downscale the image and then crop again 
        [sizexFinal sizeyFinal] = size(Ifinal); 
    end
end   
negativeNumImage = k; 
disp(['number of negative images = ' num2str(negativeNumImage)]);

