-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathexample_classifier.m
executable file
·107 lines (86 loc) · 2.81 KB
/
example_classifier.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
function example_classifier
% change this path if you install the VOC code elsewhere
addpath([cd '/VOCcode']);
% initialize VOC options
VOCinit;
% train and test classifier for each class
for i=1:VOCopts.nclasses
cls=VOCopts.classes{i};
classifier=train(VOCopts,cls); % train classifier
test(VOCopts,cls,classifier); % test classifier
[recall,prec,ap]=VOCevalcls(VOCopts,'comp1',cls,true); % compute and display PR
if i<VOCopts.nclasses
fprintf('press any key to continue with next class...\n');
drawnow;
pause;
end
end
% train classifier
function classifier = train(VOCopts,cls)
% load training set for class
[ids,classifier.gt]=textread(sprintf(VOCopts.clsimgsetpath,cls,VOCopts.trainset),'%s %d');
% extract features for each image
classifier.FD=zeros(0,length(ids));
tic;
for i=1:length(ids)
% display progress
if toc>1
fprintf('%s: train: %d/%d\n',cls,i,length(ids));
drawnow;
tic;
end
fdp=sprintf(VOCopts.exfdpath,ids{i});
if exist(fdp,'file')
% load features
load(fdp,'fd');
else
% compute and save features
I=imread(sprintf(VOCopts.imgpath,ids{i}));
fd=extractfd(VOCopts,I);
save(fdp,'fd');
end
classifier.FD(1:length(fd),i)=fd;
end
% run classifier on test images
function test(VOCopts,cls,classifier)
% load test set ('val' for development kit)
[ids,gt]=textread(sprintf(VOCopts.imgsetpath,VOCopts.testset),'%s %d');
% create results file
fid=fopen(sprintf(VOCopts.clsrespath,'comp1',cls),'w');
% classify each image
tic;
for i=1:length(ids)
% display progress
if toc>1
fprintf('%s: test: %d/%d\n',cls,i,length(ids));
drawnow;
tic;
end
fdp=sprintf(VOCopts.exfdpath,ids{i});
if exist(fdp,'file')
% load features
load(fdp,'fd');
else
% compute and save features
I=imread(sprintf(VOCopts.imgpath,ids{i}));
fd=extractfd(VOCopts,I);
save(fdp,'fd');
end
% compute confidence of positive classification
c=classify(VOCopts,classifier,fd);
% write to results file
fprintf(fid,'%s %f\n',ids{i},c);
end
% close results file
fclose(fid);
% trivial feature extractor: compute mean RGB
function fd = extractfd(VOCopts,I)
fd=squeeze(sum(sum(double(I)))/(size(I,1)*size(I,2)));
% trivial classifier: compute ratio of L2 distance betweeen
% nearest positive (class) feature vector and nearest negative (non-class)
% feature vector
function c = classify(VOCopts,classifier,fd)
d=sum(fd.*fd)+sum(classifier.FD.*classifier.FD)-2*fd'*classifier.FD;
dp=min(d(classifier.gt>0));
dn=min(d(classifier.gt<0));
c=dn/(dp+eps);