cascade.cpp
10.2 KB
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
#include <opencv2/imgproc/imgproc.hpp>
#include <openbr/plugins/openbr_internal.h>
#include <openbr/core/common.h>
#include "openbr/core/opencvutils.h"
#include <QtConcurrent>
using namespace cv;
namespace br
{
struct Miner
{
Mat src;
Mat scaledSrc;
Size windowSize;
Point offset, point;
float scale, scaleFactor, stepFactor;
Miner(const Mat &m, const Size &windowSize, const Point &offset) :
src(m),
windowSize(windowSize),
offset(offset),
point(offset)
{
scale = 1.0F;
scaleFactor = 1.4142135623730950488016887242097F;
stepFactor = 0.5F;
scale = max(((float)windowSize.width + point.x) / ((float)src.cols),
((float)windowSize.height + point.y) / ((float)src.rows));
Size size((int)(scale*src.cols + 0.5F), (int)(scale*src.rows + 0.5F));
resize(src, scaledSrc, size);
}
Mat mine(bool *newImg)
{
// Copy region of winSize region of img into m
Mat window(windowSize.height, windowSize.width, CV_8U,
(void*)(scaledSrc.data + point.y * scaledSrc.step + point.x * scaledSrc.elemSize()),
scaledSrc.step);
Mat sample;
window.copyTo(sample);
if ((int)(point.x + (1.0F + stepFactor) * windowSize.width) < scaledSrc.cols)
point.x += (int)(stepFactor * windowSize.width);
else {
point.x = offset.x;
if ((int)(point.y + (1.0F + stepFactor) * windowSize.height) < scaledSrc.rows)
point.y += (int)(stepFactor * windowSize.height);
else {
point.y = offset.y;
scale *= scaleFactor;
if (scale <= 1.0F) {
Size size((int)(scale*src.cols), (int)(scale*src.rows));
resize(src, scaledSrc, size);
} else {
*newImg = true;
return sample;
}
}
}
*newImg = false;
return sample;
}
};
/*!
* \brief A meta Classifier that creates a cascade of another Classifier. The cascade is a series of stages, each with its own instance of a given classifier. A sample can only reach the next stage if it is classified as positive by the previous stage.
* \author Jordan Cheney \cite jcheney
* \author Scott Klum \cite sklum
* \br_property int numStages The number of stages in the cascade
* \br_property int numPos The number of positives to feed each stage during training
* \br_property int numNegs The number of negatives to feed each stage during training. A negative sample must have been classified by the previous stages in the cascade as positive to be fed to the next stage during training.
* \br_property float maxFAR A termination parameter. Calculated as (number of passed negatives) / (total number of checked negatives) for a given stage during training. If that number is below the given maxFAR cascade training is terminated early. This can help prevent overfitting.
* \br_paper Paul Viola, Michael Jones
* Rapid Object Detection using a Boosted Cascade of Simple Features
* CVPR, 2001
* \br_link Rapid Object Detection using a Boosted Cascade of Simple Features https://www.cs.cmu.edu/~efros/courses/LBMV07/Papers/viola-cvpr-01.pdf
*/
class CascadeClassifier : public Classifier
{
Q_OBJECT
Q_PROPERTY(QString stageDescription READ get_stageDescription WRITE set_stageDescription RESET reset_stageDescription STORED false)
Q_PROPERTY(int numStages READ get_numStages WRITE set_numStages RESET reset_numStages STORED false)
Q_PROPERTY(int numPos READ get_numPos WRITE set_numPos RESET reset_numPos STORED false)
Q_PROPERTY(int numNegs READ get_numNegs WRITE set_numNegs RESET reset_numNegs STORED false)
Q_PROPERTY(float maxFAR READ get_maxFAR WRITE set_maxFAR RESET reset_maxFAR STORED false)
Q_PROPERTY(bool requireAllStages READ get_requireAllStages WRITE set_requireAllStages RESET reset_requireAllStages STORED false)
BR_PROPERTY(QString, stageDescription, "")
BR_PROPERTY(int, numStages, 20)
BR_PROPERTY(int, numPos, 1000)
BR_PROPERTY(int, numNegs, 1000)
BR_PROPERTY(float, maxFAR, pow(0.5, numStages))
BR_PROPERTY(bool, requireAllStages, false)
QList<Classifier *> stages;
TemplateList posImages, negImages;
TemplateList posSamples, negSamples;
QList<int> indices;
int negIndex, posIndex, samplingRound;
QMutex samplingMutex, miningMutex;
void init()
{
negIndex = posIndex = samplingRound = 0;
}
bool getPositive(Template &img)
{
if (posIndex >= posImages.size())
return false;
img = posImages[indices[posIndex++]];
return true;
}
Template getNegative(Point &offset)
{
Template negative;
const Size size = windowSize();
// Grab negative from list
int count = negImages.size();
for (int i = 0; i < count; i++) {
negative = negImages[negIndex++];
samplingRound += negIndex / count;
samplingRound = samplingRound % (size.width * size.height);
negIndex %= count;
offset.x = qMin( (int)samplingRound % size.width, negative.m().cols - size.width);
offset.y = qMin( (int)samplingRound / size.width, negative.m().rows - size.height);
if (!negative.m().empty() && negative.m().type() == CV_8U
&& offset.x >= 0 && offset.y >= 0)
break;
}
return negative;
}
uint64 mine()
{
uint64 passedNegatives = 0;
forever {
Template negative;
Point offset;
QMutexLocker samplingLocker(&samplingMutex);
negative = getNegative(offset);
samplingLocker.unlock();
Miner miner(negative.m(), windowSize(), offset);
forever {
bool newImg;
Template sample(negative.file, miner.mine(&newImg));
if (!newImg) {
if (negSamples.size() >= numNegs)
return passedNegatives;
float confidence;
if (classify(sample, true, &confidence) != 0) {
QMutexLocker miningLocker(&miningMutex);
if (negSamples.size() >= numNegs)
return passedNegatives;
negSamples.append(sample);
printf("Negative samples: %d\r", negSamples.size());
}
passedNegatives++;
} else
break;
}
}
}
void train(const TemplateList &data)
{
foreach (const Template &t, data)
t.file.get<float>("Label") == 1.0f ? posImages.append(t) : negImages.append(t);
qDebug() << "Total images:" << data.size()
<< "\nTotal positive images:" << posImages.size()
<< "\nTotal negative images:" << negImages.size();
indices = Common::RandSample(posImages.size(), posImages.size(), true);
stages.reserve(numStages);
for (int i = 0; i < numStages; i++) {
Classifier *next_stage = Classifier::make(stageDescription, NULL);
stages.append(next_stage);
}
for (int i = 0; i < numStages; i++) {
qDebug() << "===== TRAINING" << i << "stage =====";
qDebug() << "<BEGIN";
float currFAR = getSamples();
if (currFAR < maxFAR && !requireAllStages) {
qDebug() << "FAR is below required level! Terminating early";
return;
}
stages[i]->train(posSamples + negSamples);
qDebug() << "END>";
}
}
float classify(const Template &src, bool process, float *confidence) const
{
float stageConf = 0.0f;
foreach (const Classifier *stage, stages) {
float result = stage->classify(src, process, &stageConf);
if (confidence)
*confidence += stageConf;
if (result == 0.0f)
return 0.0f;
}
return 1.0f;
}
int numFeatures() const
{
return stages.first()->numFeatures();
}
Template preprocess(const Template &src) const
{
return stages.first()->preprocess(src);
}
Size windowSize(int *dx = NULL, int *dy = NULL) const
{
return stages.first()->windowSize(dx, dy);
}
void load(QDataStream &stream)
{
int numStages; stream >> numStages;
for (int i = 0; i < numStages; i++) {
Classifier *nextStage = Classifier::make(stageDescription, NULL);
nextStage->load(stream);
stages.append(nextStage);
}
}
void store(QDataStream &stream) const
{
stream << stages.size();
foreach (const Classifier *stage, stages)
stage->store(stream);
}
private:
float getSamples()
{
posSamples.clear(); posSamples.reserve(numPos);
negSamples.clear(); negSamples.reserve(numNegs);
posIndex = 0;
float confidence;
while (posSamples.size() < numPos) {
Template pos;
if (!getPositive(pos))
qFatal("Cannot get another positive sample!");
if (classify(pos, true, &confidence) > 0.0f) {
printf("POS current samples: %d\r", posSamples.size());
posSamples.append(pos);
}
}
qDebug() << "POS count : consumed " << posSamples.size() << ":" << posIndex;
QFutureSynchronizer<uint64> futures;
for (int i=0; i<QThread::idealThreadCount(); i++)
futures.addFuture(QtConcurrent::run(this, &CascadeClassifier::mine));
futures.waitForFinished();
uint64 passedNegs = 0;
QList<QFuture<uint64> > results = futures.futures();
for (int i=0; i<results.size(); i++)
passedNegs += results[i].result();
double acceptanceRatio = negSamples.size() / (double)passedNegs;
qDebug() << "NEG count : acceptanceRatio " << negSamples.size() << ":" << acceptanceRatio;
return acceptanceRatio;
}
};
BR_REGISTER(Classifier, CascadeClassifier)
} // namespace br
#include "classification/cascade.moc"