7 #include "opencv2/ocl/ocl.hpp"
8 #include "opencv2/highgui/highgui.hpp"
13 bool help_showed = false;
19 static Args read(int argc, char** argv);
40 bool hit_threshold_auto;
43 int win_stride_width, win_stride_height;
54 void handleKey(char key);
58 string hogWorkFps() const;
62 string workFps() const;
64 string message() const;
66 // This function test if gpu_rst matches cpu_rst.
67 // If the two vectors are not equal, it will return the difference in vector size
68 // Else if will return
69 // (total diff of each cpu and gpu rects covered pixels)/(total cpu rects covered pixels)
70 double checkRectSimilarity(Size sz,
71 std::vector<Rect>& cpu_rst,
72 std::vector<Rect>& gpu_rst);
94 static void printHelp()
96 cout << "Histogram of Oriented Gradients descriptor and detector sample.\n"
97 << "\nUsage: hog_gpu\n"
98 << " (<image>|--video <vide>|--camera <camera_id>) # frames source\n"
99 << " [--make_gray <true/false>] # convert image to gray one or not\n"
100 << " [--resize_src <true/false>] # do resize of the source image or not\n"
101 << " [--width <int>] # resized image width\n"
102 << " [--height <int>] # resized image height\n"
103 << " [--hit_threshold <double>] # classifying plane distance threshold (0.0 usually)\n"
104 << " [--scale <double>] # HOG window scale factor\n"
105 << " [--nlevels <int>] # max number of HOG window scales\n"
106 << " [--win_width <int>] # width of the window (48 or 64)\n"
107 << " [--win_stride_width <int>] # distance by OX axis between neighbour wins\n"
108 << " [--win_stride_height <int>] # distance by OY axis between neighbour wins\n"
109 << " [--gr_threshold <int>] # merging similar rects constant\n"
110 << " [--gamma_correct <int>] # do gamma correction or not\n"
111 << " [--write_video <bool>] # write video or not\n"
112 << " [--dst_video <path>] # output video path\n"
113 << " [--dst_video_fps <double>] # output video fps\n";
117 int main(int argc, char** argv)
123 Args args = Args::read(argc, argv);
129 catch (const Exception& e) { return cout << "error: " << e.what() << endl, 1; }
130 catch (const exception& e) { return cout << "error: " << e.what() << endl, 1; }
131 catch(...) { return cout << "unknown exception" << endl, 1; }
138 src_is_video = false;
139 src_is_camera = false;
155 hit_threshold_auto = true;
158 win_stride_width = 8;
159 win_stride_height = 8;
165 Args Args::read(int argc, char** argv)
168 for (int i = 1; i < argc; i++)
170 if (string(argv[i]) == "--make_gray") args.make_gray = (string(argv[++i]) == "true");
171 else if (string(argv[i]) == "--resize_src") args.resize_src = (string(argv[++i]) == "true");
172 else if (string(argv[i]) == "--width") args.width = atoi(argv[++i]);
173 else if (string(argv[i]) == "--height") args.height = atoi(argv[++i]);
174 else if (string(argv[i]) == "--hit_threshold")
176 args.hit_threshold = atof(argv[++i]);
177 args.hit_threshold_auto = false;
179 else if (string(argv[i]) == "--scale") args.scale = atof(argv[++i]);
180 else if (string(argv[i]) == "--nlevels") args.nlevels = atoi(argv[++i]);
181 else if (string(argv[i]) == "--win_width") args.win_width = atoi(argv[++i]);
182 else if (string(argv[i]) == "--win_stride_width") args.win_stride_width = atoi(argv[++i]);
183 else if (string(argv[i]) == "--win_stride_height") args.win_stride_height = atoi(argv[++i]);
184 else if (string(argv[i]) == "--gr_threshold") args.gr_threshold = atoi(argv[++i]);
185 else if (string(argv[i]) == "--gamma_correct") args.gamma_corr = (string(argv[++i]) == "true");
186 else if (string(argv[i]) == "--write_video") args.write_video = (string(argv[++i]) == "true");
187 else if (string(argv[i]) == "--dst_video") args.dst_video = argv[++i];
188 else if (string(argv[i]) == "--dst_video_fps") args.dst_video_fps = atof(argv[++i]);
189 else if (string(argv[i]) == "--help") printHelp();
190 else if (string(argv[i]) == "--video") { args.src = argv[++i]; args.src_is_video = true; }
191 else if (string(argv[i]) == "--camera") { args.camera_id = atoi(argv[++i]); args.src_is_camera = true; }
192 else if (args.src.empty()) args.src = argv[i];
193 else throw runtime_error((string("unknown key: ") + argv[i]));
199 App::App(const Args& s)
202 cout << "\nControls:\n"
204 << "\tm - change mode GPU <-> CPU\n"
205 << "\tg - convert image to gray or not\n"
206 << "\t1/q - increase/decrease HOG scale\n"
207 << "\t2/w - increase/decrease levels count\n"
208 << "\t3/e - increase/decrease HOG group threshold\n"
209 << "\t4/r - increase/decrease hit threshold\n"
213 make_gray = args.make_gray;
215 gr_threshold = args.gr_threshold;
216 nlevels = args.nlevels;
218 if (args.hit_threshold_auto)
219 args.hit_threshold = args.win_width == 48 ? 1.4 : 0.;
220 hit_threshold = args.hit_threshold;
222 gamma_corr = args.gamma_corr;
224 if (args.win_width != 64 && args.win_width != 48)
227 cout << "Scale: " << scale << endl;
229 cout << "Resized source: (" << args.width << ", " << args.height << ")\n";
230 cout << "Group threshold: " << gr_threshold << endl;
231 cout << "Levels number: " << nlevels << endl;
232 cout << "Win width: " << args.win_width << endl;
233 cout << "Win stride: (" << args.win_stride_width << ", " << args.win_stride_height << ")\n";
234 cout << "Hit threshold: " << hit_threshold << endl;
235 cout << "Gamma correction: " << gamma_corr << endl;
242 std::vector<ocl::Info> oclinfo;
243 ocl::getDevice(oclinfo);
245 cv::VideoWriter video_writer;
247 Size win_size(args.win_width, args.win_width * 2); //(64, 128) or (48, 96)
248 Size win_stride(args.win_stride_width, args.win_stride_height);
250 // Create HOG descriptors and detectors here
251 vector<float> detector;
252 if (win_size == Size(64, 128))
253 detector = cv::ocl::HOGDescriptor::getPeopleDetector64x128();
255 detector = cv::ocl::HOGDescriptor::getPeopleDetector48x96();
257 cv::ocl::HOGDescriptor gpu_hog(win_size, Size(16, 16), Size(8, 8), Size(8, 8), 9,
258 cv::ocl::HOGDescriptor::DEFAULT_WIN_SIGMA, 0.2, gamma_corr,
259 cv::ocl::HOGDescriptor::DEFAULT_NLEVELS);
260 cv::HOGDescriptor cpu_hog(win_size, Size(16, 16), Size(8, 8), Size(8, 8), 9, 1, -1,
261 HOGDescriptor::L2Hys, 0.2, gamma_corr, cv::HOGDescriptor::DEFAULT_NLEVELS);
262 gpu_hog.setSVMDetector(detector);
263 cpu_hog.setSVMDetector(detector);
270 if (args.src_is_video)
272 vc.open(args.src.c_str());
274 throw runtime_error(string("can't open video file: " + args.src));
277 else if (args.src_is_camera)
279 vc.open(args.camera_id);
283 msg << "can't open camera: " << args.camera_id;
284 throw runtime_error(msg.str());
290 frame = imread(args.src);
292 throw runtime_error(string("can't open image file: " + args.src));
295 Mat img_aux, img, img_to_show;
298 // Iterate over all frames
300 while (running && !frame.empty())
304 // Change format of the image
305 if (make_gray) cvtColor(frame, img_aux, CV_BGR2GRAY);
306 else if (use_gpu) cvtColor(frame, img_aux, CV_BGR2BGRA);
307 else frame.copyTo(img_aux);
310 if (args.resize_src) resize(img_aux, img, Size(args.width, args.height));
314 gpu_hog.nlevels = nlevels;
315 cpu_hog.nlevels = nlevels;
319 // Perform HOG classification
324 gpu_hog.detectMultiScale(gpu_img, found, hit_threshold, win_stride,
325 Size(0, 0), scale, gr_threshold);
328 // verify if GPU output same objects with CPU at 1st run
330 vector<Rect> ref_rst;
331 cvtColor(img, img, CV_BGRA2BGR);
332 cpu_hog.detectMultiScale(img, ref_rst, hit_threshold, win_stride,
333 Size(0, 0), scale, gr_threshold-2);
334 double accuracy = checkRectSimilarity(img.size(), ref_rst, found);
335 cout << "\naccuracy value: " << accuracy << endl;
338 else cpu_hog.detectMultiScale(img, found, hit_threshold, win_stride,
339 Size(0, 0), scale, gr_threshold);
342 // Draw positive classified windows
343 for (size_t i = 0; i < found.size(); i++)
346 rectangle(img_to_show, r.tl(), r.br(), CV_RGB(0, 255, 0), 3);
350 putText(img_to_show, "Mode: GPU", Point(5, 25), FONT_HERSHEY_SIMPLEX, 1., Scalar(255, 100, 0), 2);
352 putText(img_to_show, "Mode: CPU", Point(5, 25), FONT_HERSHEY_SIMPLEX, 1., Scalar(255, 100, 0), 2);
353 putText(img_to_show, "FPS (HOG only): " + hogWorkFps(), Point(5, 65), FONT_HERSHEY_SIMPLEX, 1., Scalar(255, 100, 0), 2);
354 putText(img_to_show, "FPS (total): " + workFps(), Point(5, 105), FONT_HERSHEY_SIMPLEX, 1., Scalar(255, 100, 0), 2);
355 imshow("opencv_gpu_hog", img_to_show);
357 if (args.src_is_video || args.src_is_camera) vc >> frame;
361 if (args.write_video)
363 if (!video_writer.isOpened())
365 video_writer.open(args.dst_video, CV_FOURCC('x','v','i','d'), args.dst_video_fps,
366 img_to_show.size(), true);
367 if (!video_writer.isOpened())
368 throw std::runtime_error("can't create video writer");
371 if (make_gray) cvtColor(img_to_show, img, CV_GRAY2BGR);
372 else cvtColor(img_to_show, img, CV_BGRA2BGR);
377 handleKey((char)waitKey(3));
383 void App::handleKey(char key)
393 cout << "Switched to " << (use_gpu ? "CUDA" : "CPU") << " mode\n";
397 make_gray = !make_gray;
398 cout << "Convert image to gray: " << (make_gray ? "YES" : "NO") << endl;
402 cout << "Scale: " << scale << endl;
407 cout << "Scale: " << scale << endl;
411 cout << "Levels number: " << nlevels << endl;
415 nlevels = max(nlevels - 1, 1);
416 cout << "Levels number: " << nlevels << endl;
420 cout << "Group threshold: " << gr_threshold << endl;
424 gr_threshold = max(0, gr_threshold - 1);
425 cout << "Group threshold: " << gr_threshold << endl;
429 cout << "Hit threshold: " << hit_threshold << endl;
433 hit_threshold = max(0.0, hit_threshold - 0.25);
434 cout << "Hit threshold: " << hit_threshold << endl;
438 gamma_corr = !gamma_corr;
439 cout << "Gamma correction: " << gamma_corr << endl;
445 inline void App::hogWorkBegin() { hog_work_begin = getTickCount(); }
447 inline void App::hogWorkEnd()
449 int64 delta = getTickCount() - hog_work_begin;
450 double freq = getTickFrequency();
451 hog_work_fps = freq / delta;
454 inline string App::hogWorkFps() const
462 inline void App::workBegin() { work_begin = getTickCount(); }
464 inline void App::workEnd()
466 int64 delta = getTickCount() - work_begin;
467 double freq = getTickFrequency();
468 work_fps = freq / delta;
471 inline string App::workFps() const
478 double App::checkRectSimilarity(Size sz,
479 std::vector<Rect>& ob1,
480 std::vector<Rect>& ob2)
482 double final_test_result = 0.0;
483 size_t sz1 = ob1.size();
484 size_t sz2 = ob2.size();
487 return sz1 > sz2 ? (double)(sz1 - sz2) : (double)(sz2 - sz1);
490 cv::Mat cpu_result(sz, CV_8UC1);
493 for(vector<Rect>::const_iterator r = ob1.begin(); r != ob1.end(); r++)
495 cv::Mat cpu_result_roi(cpu_result, *r);
496 cpu_result_roi.setTo(1);
497 cpu_result.copyTo(cpu_result);
499 int cpu_area = cv::countNonZero(cpu_result > 0);
501 cv::Mat gpu_result(sz, CV_8UC1);
503 for(vector<Rect>::const_iterator r2 = ob2.begin(); r2 != ob2.end(); r2++)
505 cv::Mat gpu_result_roi(gpu_result, *r2);
506 gpu_result_roi.setTo(1);
507 gpu_result.copyTo(gpu_result);
511 multiply(cpu_result, gpu_result, result_);
512 int result = cv::countNonZero(result_ > 0);
514 final_test_result = 1.0 - (double)result/(double)cpu_area;
516 return final_test_result;