# sample_neg_patch

## PURPOSE

sample_neg_patch - Collect random patches.

## SYNOPSIS

function sample_neg_patch(patch_size,num_patch,overwrite)

## DESCRIPTION

     sample_neg_patch - Collect random patches.

## CROSS-REFERENCE INFORMATION

This function calls:

This function is called by:

- PrepareNegativeImagePatches PrepareNegativeImagePatches - Crop image patches randomly from background images.

## SOURCE CODE

    0001 function sample_neg_patch(patch_size,num_patch,overwrite)
    0002 % sample_neg_patch - Collect random patches.
    0003
    0004 folder = '../image/neg';
    0005 if nargin < 1
    0006     patch_size = [120 120];
    0007 end
    0008 if nargin < 2
    0009     num_patch = 200;
    0010 end
    0011 if nargin < 3
    0012     overwrite = true;
    0013 end
    0014
    0015 % disp(sprintf('patch size: %d by %d',patch_size(1), patch_size(2)));
    0016 destFolder = sprintf('../image/neg_%d_%d',patch_size(1),patch_size(2));
    0017
    0018 if exist(destFolder,'dir')
    0019     if ~overwrite
    0020         return
    0021     end
    0022 else
    0023     mkdir(destFolder);
    0024 end
    0025
    0026 JPGs = dir([folder '/*.jpg']);
    0027 n = length(JPGs);
    0028 I = cell(n,1);
    0029 for i = 1:n
    0030     I{i} = imread([folder '/' JPGs(i).name]);
    0031 end
    0032
    0033 iToss = 1;
    0034 while iToss <= num_patch
    0035     % randomly select a scale
    0036     u = rand;
    0037     if u < 0.8
    0038         logscale = 0;
    0039     elseif u < 0.2 * 0.8
    0040         logscale = 1;
    0041     else
    0042         logscale = 2;
    0043     end
    0044
    0045     % randomly select an image
    0046     u = rand;
    0047     imageInd = ceil(u*n);
    0048
    0049     % rescale the image
    0050     if logscale~=0
    0051         im = imresize(I{imageInd},exp(-logscale),'nearest');
    0052     else
    0053         im = I{imageInd};
    0054     end
    0055
    0056     % possible rejection
    0057     if size(im,1) <= patch_size(1) || size(im,2) <= patch_size(2)
    0058         continue;
    0059     end
    0060
    0061     % randomly select a position
    0062     u = rand;
    0063     validHeight = size(im,1) - patch_size(1) + 1;
    0064     validWidth = size(im,2) - patch_size(2) + 1;
    0065     positionInd = ceil( u * validHeight * validWidth );
    0066     col = ceil( positionInd / validHeight );
    0067     row = positionInd - (col-1) * validHeight;
    0068
    0069     % output the random patch
    0070     patch = im(row+(0:patch_size(1)-1),col+(0:patch_size(2)-1),:);
    0071     imwrite(patch,[destFolder '/' num2str(iToss) '_' JPGs(imageInd).name],'jpg');
    0072
    0073     iToss = iToss + 1;
    0074 end
    0075
    0076