-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbewisx.cpp
387 lines (354 loc) · 16.5 KB
/
bewisx.cpp
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
#include <bewis.hpp>
using namespace std;
using namespace cv;
char buffer[1024];
const string WinTitle = "BeWIS - BG Estimator";
// Colors
Scalar bgcolor = Scalar(106,117,181);
// Gui settings
void rgb2rgb(Mat in, Mat &out) {
out = in;
}
void rgb2lab(Mat in, Mat &out) {
cvtColor(in, out, CV_BGR2Lab);
}
void rgb2hsv(Mat in, Mat &out) {
cvtColor(in, out, CV_BGR2HSV);
}
void lab2rgb(Mat in, Mat &out) {
cvtColor(in, out, CV_Lab2BGR);
}
void hsv2rgb(Mat in, Mat &out) {
cvtColor(in, out, CV_HSV2BGR);
}
void rgb2gray(Mat in, Mat &out) {
cvtColor(in, out, CV_BGR2GRAY);
}
void lab2gray(Mat in, Mat &out) {
cvtColor(in, out, CV_Lab2BGR);
cvtColor(out, out, CV_BGR2GRAY);
}
void hsv2gray(Mat in, Mat &out) {
cvtColor(in, out, CV_HSV2BGR);
cvtColor(out, out, CV_BGR2GRAY);
}
int getdir(string dir, vector<string> &files, string ext) {
DIR *dp;
struct dirent *dirp;
int cnt=0;
string fn;
if((dp = opendir(dir.c_str())) == NULL) {
cout << "Error(" << -1 << ") wrong dir " << dir << endl;
return -1;
}
while ((dirp = readdir(dp)) != NULL) {
if (dirp->d_name[0] != '.') { /* ignore hidden files */
fn = string(dirp->d_name);
if(fn.substr(fn.find_last_of(".") + 1) == ext) {
files.push_back(fn);
cnt++;
}
}
}
closedir(dp);
if (cnt == 0) {
cout << "Error(" << -2 << ") empty dir " << dir << endl;
return -2;
}
return cnt;
}
Mat& discretize(Mat& I, int dimTics) {
// accept only char type matrices
CV_Assert(I.depth() != sizeof(uchar));
int channels = I.channels();
int nRows = I.rows;
int nCols = I.cols * channels;
if (I.isContinuous())
{
nCols *= nRows;
nRows = 1;
}
int i,j;
uchar* p;
for( i = 0; i < nRows; ++i)
{
p = I.ptr<uchar>(i);
for ( j = 0; j < nCols; ++j)
{
p[j] = (unsigned char) ((p[j] / dimTics) * dimTics);
;
}
}
return I;
}
void showImages(Mat &dispimg, list< pair < Mat, Rect > > imglist, list< pair < string, Point > > tlist) {
int baseline;
Size tsize = getTextSize("dummy",CV_FONT_HERSHEY_PLAIN,1.0,1,&baseline);
for (std::list< pair < Mat, Rect > >::const_iterator it = imglist.begin(); it != imglist.end(); ++it) {
(*it).first.copyTo(dispimg((*it).second));
}
for (std::list< pair < string, Point > >::const_iterator it = tlist.begin(); it != tlist.end(); ++it) {
putText(dispimg,(*it).first,(*it).second,CV_FONT_HERSHEY_PLAIN,1.0,Scalar(255,255,255));
}
imshow(WinTitle,dispimg);
}
int main(int argc, char** argv) {
// Parse commands globs
DIR *dp, *op; // input dir
FILE *fp;
int numframes;
int key;
vector<string> dlist = vector<string>();
string videoname;
double incr=1.0, decr=1.0;
int err;
int delta;
bool outflag= false;
// Graphics globs
Mat frame, frame_orig; //current frame
int frameidx = 0;
double scalefactor = 1;
Mat bgmodel, bgmodel_out; //fg/bg masks generated by MOG2 method
Mat frameYCrCb, bgmodelYCrCb; //fg/bg masks generated by MOG2 method
Mat tmpMask, deltaimg;
Mat frameY[3], bgmodelY[3];
list< pair < Mat, Rect > > imglist; // image/ROI list for display
list< pair < string, Point > > titlelist; // image/ROI list for display
void (*convert)(Mat, Mat &);
void (*backconvert)(Mat, Mat &);
string titleupleft, titleupright="BG Model", titledownleft="Diff |Input-BG|", titledownright="FG Detection";
// Timing globs
double fps, rfps;
struct timeval t0, t1, t2;
// Set Command Line Parser
bool displayFlag = false;
bool movieinput = false;
bool verboseFlag = false;
bool erosionFlag = false; bool blurFlag = false;
bool reverseFlag = false;
int w,h;
string videofile = "prova.avi";
string outfilename = "bg.png";
string extArg = "png";
string coding = "RGB";
int nbit = 4, ntics = 256, learntime = 1, cachesize = 20;
string policy = "1:1";
double watermark = 0.0, uppermark = 50.0, thresh = 0.75;
int selectthresh = -1;
vector<string> args(argv + 1, argv + argc);
string arg, value;
for (vector<string>::iterator i = args.begin(); i != args.end(); ++i) {
arg = String(*i);
if (arg == "-h" || arg == "--help") {
cout << "Syntax: bewis -i <infile>" << endl;
cout << string(CHARSKIP1, ' ') << "video file (or frame filename <path>/video_%d.png))" << endl;
cout << string(CHARSKIP2, ' ') << "-o <outfile>, --outfile <outfile>" << endl;
cout << string(CHARSKIP1, ' ') << "BG output filename" << endl;
cout << string(CHARSKIP2, ' ') << "-m <RGB|Lab|HUV>, --mode <RGB|Lab|HUV>" << endl;
cout << string(CHARSKIP1, ' ') << "color mode (default: RGB)" << endl;
cout << string(CHARSKIP2, ' ') << "-p <int:int>, --policy <int:int>" << endl;
cout << string(CHARSKIP1, ' ') << "NN policy (default: 1:1)" << endl;
cout << string(CHARSKIP2, ' ') << "-b <int>, --bits <int>" << endl;
cout << string(CHARSKIP1, ' ') << "NN bit resolution (default: 4)" << endl;
cout << string(CHARSKIP2, ' ') << "-z <int>, --scale <int>" << endl;
cout << string(CHARSKIP1, ' ') << "color discretization scale (default: 256)" << endl;
cout << string(CHARSKIP2, ' ') << "-t <double>, --threshold <double>" << endl;
cout << string(CHARSKIP1, ' ') << "NN threshold (default: 0.75)" << endl;
cout << string(CHARSKIP2, ' ') << "-u <double>, --uppermark <double>" << endl;
cout << string(CHARSKIP1, ' ') << "NN rams saturation limit (default: 50)" << endl;
cout << string(CHARSKIP2, ' ') << "-w <double>, --watermark <double>" << endl;
cout << string(CHARSKIP1, ' ') << "NN rams firing threshold (default: 0)" << endl;
cout << string(CHARSKIP2, ' ') << "-k <int>, --cap <int>" << endl;
cout << string(CHARSKIP1, ' ') << "color repetition time (default: -1)" << endl;
cout << string(CHARSKIP2, ' ') << "-q <int>, --qsize <int>" << endl;
cout << string(CHARSKIP1, ' ') << "cache queue size (default: 20)" << endl;
cout << string(CHARSKIP2, ' ') << "-l <int>, --learntime <int>" << endl;
cout << string(CHARSKIP1, ' ') << "pre-learning time (in no of frames) (default: 1)" << endl;
cout << string(CHARSKIP2, ' ') << "-h, --help" << endl;
cout << string(CHARSKIP1, ' ') << "display this help" << endl;
cout << string(CHARSKIP2, ' ') << "-v, --verbose" << endl;
cout << string(CHARSKIP1, ' ') << "display system and video configuration" << endl;
cout << string(CHARSKIP2, ' ') << "-s <double>, --scale <double>" << endl;
cout << string(CHARSKIP1, ' ') << "video scale factor (default: 1)" << endl;
cout << string(CHARSKIP2, ' ') << "-x, --display" << endl;
cout << string(CHARSKIP1, ' ') << "enable graphic display (default: disabled)" << endl;
return 0;
} else if (arg == "-v" || arg == "--verbose") {
verboseFlag = true;
} else if (arg == "-x" || arg == "--display") {
displayFlag = true;
} else if (arg == "-g" || arg == "--blur") {
blurFlag = true;
} else {
arg = String(*i);
if (++i == args.end()) {cout << "Parse error: Wrong argument syntax " << arg << endl; exit(-1);}
value = String(*i);
if (arg == "-i" || arg == "--input") {
videofile = value;
int pos;
if ((pos = videofile.find_last_of("/\\")) == videofile.size() - 1) {
videofile = videofile.substr(0,videofile.size()-1);
pos = videofile.find_last_of("/\\");
}
videoname = videofile.substr(pos+1);
} else if (arg == "-o" || arg == "--outfile") {
outfilename = value;
outflag = true;
} else if (arg == "-m" || arg == "--mode") {
coding = value;
} else if (arg == "-k" || arg == "--cap") {
selectthresh = atoi((value).c_str());
cout << "READ" << endl;
} else if (arg == "-q" || arg == "--qsize") {
cachesize = atoi((value).c_str());
} else if (arg == "-b" || arg == "--bits") {
nbit = atoi((value).c_str());
} else if (arg == "-w" || arg == "--watermark") {
watermark = (double)atof((value).c_str());
} else if (arg == "-u" || arg == "--uppermark") {
uppermark = (double)atof((value).c_str());
} else if (arg == "-z" || arg == "--scale") {
ntics = atoi((value).c_str());
} else if (arg == "-l" || arg == "--learntime") {
learntime = atoi((value).c_str());
} else if (arg == "-t" || arg == "--threshold") {
thresh = (double)atof((*i).c_str());
} else if (arg == "-s" || arg == "--scale") {
scalefactor = (double)atof((*i).c_str());
} else if (arg == "-p" || arg == "--policy") {
policy = value;
if ((err = parsePolicy(policy,incr,decr)) < 0) {
cerr << "Parse error: Argument: -w" << endl;
cerr << string(13, ' ') << "policy setting must be <int>:<int>" << endl;
exit(-1);
}
} else {
cout << "Parse error: wrong argument syntax " << value << endl;
exit(-1);
}
}
}
if (coding == "RGB") {
convert = &rgb2rgb;
backconvert = &rgb2rgb;
titleupleft = "Input(RGB): ";
} else if (coding == "Lab") {
convert = &rgb2lab;
backconvert = &lab2rgb;
titleupleft = "Input(Lab): ";
} else if (coding == "HSV") {
convert = &rgb2hsv;
backconvert = &hsv2rgb;
titleupleft = "Input(HSV): ";
} else {
cerr << "Parse error: Argument: -m" << endl;
cerr << string(13, ' ') << "Color space must be RGB|HSV|Lab" << endl;
exit(-1);
}
delta = 256 / ntics;
// Get sequence info (from frame set or movie file)
VideoCapture cap(videofile);
if(!cap.isOpened()) { // check if we succeeded
cout << "I/O error: problem opening video/sequence" << endl;
exit(-1);
}
cap.read(frame_orig);
w = (int)(cap.get(CV_CAP_PROP_FRAME_WIDTH) * scalefactor);
h = (int)(cap.get(CV_CAP_PROP_FRAME_HEIGHT) * scalefactor);
resize(frame_orig, frame, cv::Size(w, h));
numframes = (int)cap.get(CV_CAP_PROP_FRAME_COUNT);
fps = (int)cap.get(CV_CAP_PROP_FPS);
if (numframes <= 0) {
cout << "Processing Video Streaming (" << w << "x" << h << ")"<< endl;
numframes = 0;
} else {
cout << "Processing Local Video (" << w << "x" << h << ") with " << numframes << " frames"<< endl;
}
// Initialize Background Subtractor algorithm
Ptr<BackgroundSubtractorWIS> Subtractor;
Subtractor = createBackgroundSubtractorWIS();
Subtractor->set("noBits", nbit);
Subtractor->set("noTics", ntics);
Subtractor->set("trainIncr", incr);
Subtractor->set("trainDecr", decr);
Subtractor->set("cacheSize", cachesize);
Subtractor->set("varWatermark", watermark);
Subtractor->set("varThreshold", thresh);
Subtractor->set("varUpWatermark", uppermark);
Subtractor->set("selectThreshold", selectthresh);
Subtractor->set("learningStage", learntime);
Subtractor->initialize(frame.size(), frame.type());
if (verboseFlag) {
cout << left << setw(MAXWIDTH) << setfill(filler) << "I/O GRAPHICS PARAMS" << endl;
cout << left << setw(MAXWIDTH) << setfill(filler) << "Video Coding" << ": " << coding << endl;
cout << left << setw(MAXWIDTH) << setfill(filler) << "Video Name" << ": " << videoname << endl;
cout << left << setw(MAXWIDTH) << setfill(filler) << "Output file" << ": " << outfilename << endl;
cout << left << setw(MAXWIDTH) << setfill(filler) << "Blur" << ": " << (blurFlag ? "enabled" : "diasbled") << endl;
cout << left << setw(MAXWIDTH) << setfill(filler) << "Reverse" << ": " << (reverseFlag ? "enabled" : "diasbled") << endl;
cout << left << setw(MAXWIDTH) << setfill(filler) << "WISARD DETECTOR PARAMS" << endl;
cout << left << setw(MAXWIDTH) << setfill(filler) << "noBits: " << Subtractor->getInt("noBits") << endl;
cout << left << setw(MAXWIDTH) << setfill(filler) << "noTics: " << Subtractor->getInt("noTics") << "(" << Subtractor->getInt("dimTics") << ")" << endl;
cout << left << setw(MAXWIDTH) << setfill(filler) << "noRams: " << Subtractor->getInt("noRams") << endl;
cout << left << setw(MAXWIDTH) << setfill(filler) << "Train Policy: " << Subtractor->getDouble("trainIncr") << ":" << Subtractor->getDouble("trainDecr") << endl;
cout << left << setw(MAXWIDTH) << setfill(filler) << "Classification Thresh: " << Subtractor->getDouble("varThreshold") << endl;
cout << left << setw(MAXWIDTH) << setfill(filler) << "Selection Thresh: " << Subtractor->getInt("selectThreshold") << endl;
cout << left << setw(MAXWIDTH) << setfill(filler) << "Watermark: " << Subtractor->getDouble("varWatermark") << endl;
cout << left << setw(MAXWIDTH) << setfill(filler) << "Uppermark: " << Subtractor->getDouble("varUpWatermark") << endl;
cout << left << setw(MAXWIDTH) << setfill(filler) << "LearningStage: " << Subtractor->getInt("learningStage") << endl;
cout << left << setw(MAXWIDTH) << setfill(filler) << "Cachesize: " << Subtractor->getInt("cacheSize") << endl;
}
// Create output display and its geometry
int hskip = 16, wskip = 4;
int dcols = 3;
Mat outFrame(h+hskip+wskip,w*dcols+(dcols+1)*wskip,CV_8UC3,bgcolor);
// Create window an put icons
if (displayFlag) cvNamedWindow(WinTitle.c_str(),CV_WINDOW_AUTOSIZE);
// Video processing loop
bool forward = true, stop = false;
gettimeofday(&t0,NULL);
for (;;) {
gettimeofday(&t1,NULL);
if (!cap.read(frame_orig)) { // if there is no frame to capture (es: ending of a video file)
break;
}
resize(frame_orig, frame, cv::Size(w,h));
if (blurFlag) blur(frame,frame,Size(3,3));
Subtractor->apply(frame, tmpMask); // update Background Model (training)
Subtractor->getBackgroundImage(bgmodel); // get Background Model
// back convert for display
backconvert(frame,frame);
backconvert(bgmodel, bgmodel);
// difference by luminance (Ycrcb)
cvtColor(frame,frameYCrCb,CV_RGB2YCrCb);
cvtColor(bgmodel,bgmodelYCrCb,CV_RGB2YCrCb);
split(frameYCrCb,frameY);
split(bgmodelYCrCb,bgmodelY);
absdiff(frameY[0],bgmodelY[0],deltaimg);
threshold(deltaimg,deltaimg, 20, 255, CV_THRESH_BINARY);
cvtColor(deltaimg,deltaimg,CV_GRAY2BGR,3);
// build up display
if (displayFlag) {
outFrame.setTo(bgcolor);
imglist.clear();
titlelist.clear();
imglist.push_back(make_pair(frame,Rect(Point(wskip,hskip-2),Size(w,h)))); // original frame (Up left)
titlelist.push_back(make_pair(titleupleft + format("%05d",frameidx),Point(wskip,hskip-5)));
imglist.push_back(make_pair(bgmodel,Rect(Point(wskip*2+w,hskip-2),Size(w,h)))); // bgmodel (Up right)
titlelist.push_back(make_pair(titleupright,Point(wskip*2+w,hskip-5)));
imglist.push_back(make_pair(deltaimg,Rect(Point(wskip*3+2*w,hskip-2),Size(w,h)))); // bgmodel (Up right)
titlelist.push_back(make_pair(titledownleft,Point(wskip*3+2*w,hskip-5)));
showImages(outFrame, imglist, titlelist);
if ((key = waitKey(1)) >= 0) {
cout << "\nKey pressed " << key << endl;
break;
}
}
++frameidx;
gettimeofday(&t2,NULL);
rfps = (int)(1.0 / ((double) (t2.tv_usec - t1.tv_usec)/1000000 + (double) (t2.tv_sec - t1.tv_sec)));
cout << '\r' << "Processing Frame " << std::setfill('0') << frameidx << "/" << numframes << std::flush;
if (outflag) imwrite(outfilename, bgmodel);
}
// Print timing statistics and BG
cout << "\nProcessed at " << (t2.tv_sec - t0.tv_sec) / frameidx << " FPS - Total time " << (t2.tv_sec - t0.tv_sec) << " sec"<< endl;
}