Skip to content

Instantly share code, notes, and snippets.

@erogol
Created September 24, 2013 13:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erogol/6684750 to your computer and use it in GitHub Desktop.
Save erogol/6684750 to your computer and use it in GitHub Desktop.
sample negative instances from real folder structure given the root folder the the interest paths
function [] = sample_neg_examples(ROOT_PATH, num_sample, OUTPUT_PATH)
SEARCH_PATH = fullfile(ROOT_PATH,'**','*');
SAVE_PATH = 'neg_examples'
paths = rdir(SEARCH_PATH);
if exist('OUTPUT_PATH','var')
SAVE_PATH = OUTPUT_PATH;
end
% find number of classes
img_paths = {paths.name};
% find class numbers
img_cluster_paths = cellfun(@(x)fileparts(x), img_paths, 'UniformOutput', false);
img_root_paths = cellfun(@(x)fileparts(x), img_cluster_paths, 'UniformOutput', false);
unique_root_paths = unique(img_root_paths);
num_classes = numel(unique_root_paths);
% number of images for each class
count_string = cellfun(@(x) sum(ismember(img_root_paths,x)), unique_root_paths);
% create a set for each class
parfor j = 1:num_classes
display(['NEG set creation for class ',num2str(j)]);
class_path = unique_root_paths{j};
[~,class_name] = fileparts(class_path);
filtered_img_indices = cell2mat(cellfun(@(x)logical(isempty(findstr(x,class_path))), img_paths, 'UniformOutput', false));
filtered_img_paths = img_paths(filtered_img_indices)
indices = randperm(numel(filtered_img_paths),num_sample);
IMG_SAVE_PATH = fullfile(SAVE_PATH,class_name);
mkdir(IMG_SAVE_PATH);
neg_img_paths = filtered_img_paths(indices);
for i = 1:numel(neg_img_paths)
img_path = neg_img_paths{i};
[img_root_path, img_name] = fileparts(img_path);
[~, img_class] = fileparts(fileparts(img_root_path));
SAVE_PATH_img = strrep(img_path, img_root_path, IMG_SAVE_PATH);
SAVE_PATH_img = strrep(SAVE_PATH_img, img_name, [img_class,'_',num2str(i)]);
if strcmp(img_class,class_name)
display('SAME IMG CLASS!!!');
end
copyfile(img_path, SAVE_PATH_img);
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment