hog.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4. #include <sstream>
  5. #include <iomanip>
  6. #include <stdexcept>
  7. #include <opencv2/core/utility.hpp>
  8. #include "opencv2/cudaobjdetect.hpp"
  9. #include "opencv2/highgui.hpp"
  10. #include "opencv2/objdetect.hpp"
  11. #include "opencv2/imgproc.hpp"
  12. using namespace std;
  13. using namespace cv;
  14. bool help_showed = false;
  15. class Args
  16. {
  17. public:
  18. Args();
  19. static Args read(int argc, char** argv);
  20. string src;
  21. bool src_is_folder;
  22. bool src_is_video;
  23. bool src_is_camera;
  24. int camera_id;
  25. bool svm_load;
  26. string svm;
  27. bool write_video;
  28. string dst_video;
  29. double dst_video_fps;
  30. bool make_gray;
  31. bool resize_src;
  32. int width, height;
  33. double scale;
  34. int nlevels;
  35. int gr_threshold;
  36. double hit_threshold;
  37. bool hit_threshold_auto;
  38. int win_width;
  39. int win_stride_width, win_stride_height;
  40. int block_width;
  41. int block_stride_width, block_stride_height;
  42. int cell_width;
  43. int nbins;
  44. bool gamma_corr;
  45. };
  46. class App
  47. {
  48. public:
  49. App(const Args& s);
  50. void run();
  51. void handleKey(char key);
  52. void hogWorkBegin();
  53. void hogWorkEnd();
  54. string hogWorkFps() const;
  55. void workBegin();
  56. void workEnd();
  57. string workFps() const;
  58. string message() const;
  59. private:
  60. App operator=(App&);
  61. Args args;
  62. bool running;
  63. bool use_gpu;
  64. bool make_gray;
  65. double scale;
  66. int gr_threshold;
  67. int nlevels;
  68. double hit_threshold;
  69. bool gamma_corr;
  70. int64 hog_work_begin;
  71. double hog_work_fps;
  72. int64 work_begin;
  73. double work_fps;
  74. };
  75. static void printHelp()
  76. {
  77. cout << "Histogram of Oriented Gradients descriptor and detector sample.\n"
  78. << "\nUsage: hog\n"
  79. << " (<image>|--video <vide>|--camera <camera_id>) # frames source\n"
  80. << " or"
  81. << " (--folder <folder_path>) # load images from folder\n"
  82. << " [--svm <file> # load svm file"
  83. << " [--make_gray <true/false>] # convert image to gray one or not\n"
  84. << " [--resize_src <true/false>] # do resize of the source image or not\n"
  85. << " [--width <int>] # resized image width\n"
  86. << " [--height <int>] # resized image height\n"
  87. << " [--hit_threshold <double>] # classifying plane distance threshold (0.0 usually)\n"
  88. << " [--scale <double>] # HOG window scale factor\n"
  89. << " [--nlevels <int>] # max number of HOG window scales\n"
  90. << " [--win_width <int>] # width of the window\n"
  91. << " [--win_stride_width <int>] # distance by OX axis between neighbour wins\n"
  92. << " [--win_stride_height <int>] # distance by OY axis between neighbour wins\n"
  93. << " [--block_width <int>] # width of the block\n"
  94. << " [--block_stride_width <int>] # distance by 0X axis between neighbour blocks\n"
  95. << " [--block_stride_height <int>] # distance by 0Y axis between neighbour blocks\n"
  96. << " [--cell_width <int>] # width of the cell\n"
  97. << " [--nbins <int>] # number of bins\n"
  98. << " [--gr_threshold <int>] # merging similar rects constant\n"
  99. << " [--gamma_correct <int>] # do gamma correction or not\n"
  100. << " [--write_video <bool>] # write video or not\n"
  101. << " [--dst_video <path>] # output video path\n"
  102. << " [--dst_video_fps <double>] # output video fps\n";
  103. help_showed = true;
  104. }
  105. int main(int argc, char** argv)
  106. {
  107. try
  108. {
  109. Args args;
  110. if (argc < 2)
  111. {
  112. printHelp();
  113. args.camera_id = 0;
  114. args.src_is_camera = true;
  115. }
  116. else
  117. {
  118. args = Args::read(argc, argv);
  119. if (help_showed)
  120. return -1;
  121. }
  122. App app(args);
  123. app.run();
  124. }
  125. catch (const Exception& e) { return cout << "error: " << e.what() << endl, 1; }
  126. catch (const exception& e) { return cout << "error: " << e.what() << endl, 1; }
  127. catch(...) { return cout << "unknown exception" << endl, 1; }
  128. return 0;
  129. }
  130. Args::Args()
  131. {
  132. src_is_video = false;
  133. src_is_camera = false;
  134. src_is_folder = false;
  135. svm_load = false;
  136. camera_id = 0;
  137. write_video = false;
  138. dst_video_fps = 24.;
  139. make_gray = false;
  140. resize_src = false;
  141. width = 640;
  142. height = 480;
  143. scale = 1.05;
  144. nlevels = 13;
  145. gr_threshold = 8;
  146. hit_threshold = 1.4;
  147. hit_threshold_auto = true;
  148. win_width = 48;
  149. win_stride_width = 8;
  150. win_stride_height = 8;
  151. block_width = 16;
  152. block_stride_width = 8;
  153. block_stride_height = 8;
  154. cell_width = 8;
  155. nbins = 9;
  156. gamma_corr = true;
  157. }
  158. Args Args::read(int argc, char** argv)
  159. {
  160. Args args;
  161. for (int i = 1; i < argc; i++)
  162. {
  163. if (string(argv[i]) == "--make_gray") args.make_gray = (string(argv[++i]) == "true");
  164. else if (string(argv[i]) == "--resize_src") args.resize_src = (string(argv[++i]) == "true");
  165. else if (string(argv[i]) == "--width") args.width = atoi(argv[++i]);
  166. else if (string(argv[i]) == "--height") args.height = atoi(argv[++i]);
  167. else if (string(argv[i]) == "--hit_threshold")
  168. {
  169. args.hit_threshold = atof(argv[++i]);
  170. args.hit_threshold_auto = false;
  171. }
  172. else if (string(argv[i]) == "--scale") args.scale = atof(argv[++i]);
  173. else if (string(argv[i]) == "--nlevels") args.nlevels = atoi(argv[++i]);
  174. else if (string(argv[i]) == "--win_width") args.win_width = atoi(argv[++i]);
  175. else if (string(argv[i]) == "--win_stride_width") args.win_stride_width = atoi(argv[++i]);
  176. else if (string(argv[i]) == "--win_stride_height") args.win_stride_height = atoi(argv[++i]);
  177. else if (string(argv[i]) == "--block_width") args.block_width = atoi(argv[++i]);
  178. else if (string(argv[i]) == "--block_stride_width") args.block_stride_width = atoi(argv[++i]);
  179. else if (string(argv[i]) == "--block_stride_height") args.block_stride_height = atoi(argv[++i]);
  180. else if (string(argv[i]) == "--cell_width") args.cell_width = atoi(argv[++i]);
  181. else if (string(argv[i]) == "--nbins") args.nbins = atoi(argv[++i]);
  182. else if (string(argv[i]) == "--gr_threshold") args.gr_threshold = atoi(argv[++i]);
  183. else if (string(argv[i]) == "--gamma_correct") args.gamma_corr = (string(argv[++i]) == "true");
  184. else if (string(argv[i]) == "--write_video") args.write_video = (string(argv[++i]) == "true");
  185. else if (string(argv[i]) == "--dst_video") args.dst_video = argv[++i];
  186. else if (string(argv[i]) == "--dst_video_fps") args.dst_video_fps = atof(argv[++i]);
  187. else if (string(argv[i]) == "--help") printHelp();
  188. else if (string(argv[i]) == "--video") { args.src = argv[++i]; args.src_is_video = true; }
  189. else if (string(argv[i]) == "--camera") { args.camera_id = atoi(argv[++i]); args.src_is_camera = true; }
  190. else if (string(argv[i]) == "--folder") { args.src = argv[++i]; args.src_is_folder = true;}
  191. else if (string(argv[i]) == "--svm") { args.svm = argv[++i]; args.svm_load = true;}
  192. else if (args.src.empty()) args.src = argv[i];
  193. else throw runtime_error((string("unknown key: ") + argv[i]));
  194. }
  195. return args;
  196. }
  197. App::App(const Args& s)
  198. {
  199. cv::cuda::printShortCudaDeviceInfo(cv::cuda::getDevice());
  200. args = s;
  201. cout << "\nControls:\n"
  202. << "\tESC - exit\n"
  203. << "\tm - change mode GPU <-> CPU\n"
  204. << "\tg - convert image to gray or not\n"
  205. << "\t1/q - increase/decrease HOG scale\n"
  206. << "\t2/w - increase/decrease levels count\n"
  207. << "\t3/e - increase/decrease HOG group threshold\n"
  208. << "\t4/r - increase/decrease hit threshold\n"
  209. << endl;
  210. use_gpu = true;
  211. make_gray = args.make_gray;
  212. scale = args.scale;
  213. gr_threshold = args.gr_threshold;
  214. nlevels = args.nlevels;
  215. if (args.hit_threshold_auto)
  216. args.hit_threshold = args.win_width == 48 ? 1.4 : 0.;
  217. hit_threshold = args.hit_threshold;
  218. gamma_corr = args.gamma_corr;
  219. cout << "Scale: " << scale << endl;
  220. if (args.resize_src)
  221. cout << "Resized source: (" << args.width << ", " << args.height << ")\n";
  222. cout << "Group threshold: " << gr_threshold << endl;
  223. cout << "Levels number: " << nlevels << endl;
  224. cout << "Win size: (" << args.win_width << ", " << args.win_width*2 << ")\n";
  225. cout << "Win stride: (" << args.win_stride_width << ", " << args.win_stride_height << ")\n";
  226. cout << "Block size: (" << args.block_width << ", " << args.block_width << ")\n";
  227. cout << "Block stride: (" << args.block_stride_width << ", " << args.block_stride_height << ")\n";
  228. cout << "Cell size: (" << args.cell_width << ", " << args.cell_width << ")\n";
  229. cout << "Bins number: " << args.nbins << endl;
  230. cout << "Hit threshold: " << hit_threshold << endl;
  231. cout << "Gamma correction: " << gamma_corr << endl;
  232. cout << endl;
  233. }
  234. void App::run()
  235. {
  236. running = true;
  237. cv::VideoWriter video_writer;
  238. Size win_stride(args.win_stride_width, args.win_stride_height);
  239. Size win_size(args.win_width, args.win_width * 2);
  240. Size block_size(args.block_width, args.block_width);
  241. Size block_stride(args.block_stride_width, args.block_stride_height);
  242. Size cell_size(args.cell_width, args.cell_width);
  243. cv::Ptr<cv::cuda::HOG> gpu_hog = cv::cuda::HOG::create(win_size, block_size, block_stride, cell_size, args.nbins);
  244. cv::HOGDescriptor cpu_hog(win_size, block_size, block_stride, cell_size, args.nbins);
  245. if(args.svm_load) {
  246. std::vector<float> svm_model;
  247. const std::string model_file_name = args.svm;
  248. FileStorage ifs(model_file_name, FileStorage::READ);
  249. if (ifs.isOpened()) {
  250. ifs["svm_detector"] >> svm_model;
  251. } else {
  252. const std::string what =
  253. "could not load model for hog classifier from file: "
  254. + model_file_name;
  255. throw std::runtime_error(what);
  256. }
  257. // check if the variables are initialized
  258. if (svm_model.empty()) {
  259. const std::string what =
  260. "HoG classifier: svm model could not be loaded from file"
  261. + model_file_name;
  262. throw std::runtime_error(what);
  263. }
  264. gpu_hog->setSVMDetector(svm_model);
  265. cpu_hog.setSVMDetector(svm_model);
  266. } else {
  267. // Create HOG descriptors and detectors here
  268. Mat detector = gpu_hog->getDefaultPeopleDetector();
  269. gpu_hog->setSVMDetector(detector);
  270. cpu_hog.setSVMDetector(detector);
  271. }
  272. cout << "gpusvmDescriptorSize : " << gpu_hog->getDescriptorSize()
  273. << endl;
  274. cout << "cpusvmDescriptorSize : " << cpu_hog.getDescriptorSize()
  275. << endl;
  276. while (running)
  277. {
  278. VideoCapture vc;
  279. Mat frame;
  280. vector<String> filenames;
  281. unsigned int count = 1;
  282. if (args.src_is_video)
  283. {
  284. vc.open(args.src.c_str());
  285. if (!vc.isOpened())
  286. throw runtime_error(string("can't open video file: " + args.src));
  287. vc >> frame;
  288. }
  289. else if (args.src_is_folder) {
  290. String folder = args.src;
  291. cout << folder << endl;
  292. glob(folder, filenames);
  293. frame = imread(filenames[count]); // 0 --> .gitignore
  294. if (!frame.data)
  295. cerr << "Problem loading image from folder!!!" << endl;
  296. }
  297. else if (args.src_is_camera)
  298. {
  299. vc.open(args.camera_id);
  300. if (!vc.isOpened())
  301. {
  302. stringstream msg;
  303. msg << "can't open camera: " << args.camera_id;
  304. throw runtime_error(msg.str());
  305. }
  306. vc >> frame;
  307. }
  308. else
  309. {
  310. frame = imread(args.src);
  311. if (frame.empty())
  312. throw runtime_error(string("can't open image file: " + args.src));
  313. }
  314. Mat img_aux, img, img_to_show;
  315. cuda::GpuMat gpu_img;
  316. // Iterate over all frames
  317. while (running && !frame.empty())
  318. {
  319. workBegin();
  320. // Change format of the image
  321. if (make_gray) cvtColor(frame, img_aux, COLOR_BGR2GRAY);
  322. else if (use_gpu) cvtColor(frame, img_aux, COLOR_BGR2BGRA);
  323. else frame.copyTo(img_aux);
  324. // Resize image
  325. if (args.resize_src) resize(img_aux, img, Size(args.width, args.height));
  326. else img = img_aux;
  327. img_to_show = img;
  328. vector<Rect> found;
  329. // Perform HOG classification
  330. hogWorkBegin();
  331. if (use_gpu)
  332. {
  333. gpu_img.upload(img);
  334. gpu_hog->setNumLevels(nlevels);
  335. gpu_hog->setHitThreshold(hit_threshold);
  336. gpu_hog->setWinStride(win_stride);
  337. gpu_hog->setScaleFactor(scale);
  338. gpu_hog->setGroupThreshold(gr_threshold);
  339. gpu_hog->detectMultiScale(gpu_img, found);
  340. }
  341. else
  342. {
  343. cpu_hog.nlevels = nlevels;
  344. cpu_hog.detectMultiScale(img, found, hit_threshold, win_stride,
  345. Size(0, 0), scale, gr_threshold);
  346. }
  347. hogWorkEnd();
  348. // Draw positive classified windows
  349. for (size_t i = 0; i < found.size(); i++)
  350. {
  351. Rect r = found[i];
  352. rectangle(img_to_show, r.tl(), r.br(), Scalar(0, 255, 0), 3);
  353. }
  354. if (use_gpu)
  355. putText(img_to_show, "Mode: GPU", Point(5, 25), FONT_HERSHEY_SIMPLEX, 1., Scalar(255, 100, 0), 2);
  356. else
  357. putText(img_to_show, "Mode: CPU", Point(5, 25), FONT_HERSHEY_SIMPLEX, 1., Scalar(255, 100, 0), 2);
  358. putText(img_to_show, "FPS HOG: " + hogWorkFps(), Point(5, 65), FONT_HERSHEY_SIMPLEX, 1., Scalar(255, 100, 0), 2);
  359. putText(img_to_show, "FPS total: " + workFps(), Point(5, 105), FONT_HERSHEY_SIMPLEX, 1., Scalar(255, 100, 0), 2);
  360. imshow("opencv_gpu_hog", img_to_show);
  361. if (args.src_is_video || args.src_is_camera) vc >> frame;
  362. if (args.src_is_folder) {
  363. count++;
  364. if (count < filenames.size()) {
  365. frame = imread(filenames[count]);
  366. } else {
  367. Mat empty;
  368. frame = empty;
  369. }
  370. }
  371. workEnd();
  372. if (args.write_video)
  373. {
  374. if (!video_writer.isOpened())
  375. {
  376. video_writer.open(args.dst_video, VideoWriter::fourcc('x','v','i','d'), args.dst_video_fps,
  377. img_to_show.size(), true);
  378. if (!video_writer.isOpened())
  379. throw std::runtime_error("can't create video writer");
  380. }
  381. if (make_gray) cvtColor(img_to_show, img, COLOR_GRAY2BGR);
  382. else cvtColor(img_to_show, img, COLOR_BGRA2BGR);
  383. video_writer << img;
  384. }
  385. handleKey((char)waitKey(3));
  386. }
  387. }
  388. }
  389. void App::handleKey(char key)
  390. {
  391. switch (key)
  392. {
  393. case 27:
  394. running = false;
  395. break;
  396. case 'm':
  397. case 'M':
  398. use_gpu = !use_gpu;
  399. cout << "Switched to " << (use_gpu ? "CUDA" : "CPU") << " mode\n";
  400. break;
  401. case 'g':
  402. case 'G':
  403. make_gray = !make_gray;
  404. cout << "Convert image to gray: " << (make_gray ? "YES" : "NO") << endl;
  405. break;
  406. case '1':
  407. scale *= 1.05;
  408. cout << "Scale: " << scale << endl;
  409. break;
  410. case 'q':
  411. case 'Q':
  412. scale /= 1.05;
  413. cout << "Scale: " << scale << endl;
  414. break;
  415. case '2':
  416. nlevels++;
  417. cout << "Levels number: " << nlevels << endl;
  418. break;
  419. case 'w':
  420. case 'W':
  421. nlevels = max(nlevels - 1, 1);
  422. cout << "Levels number: " << nlevels << endl;
  423. break;
  424. case '3':
  425. gr_threshold++;
  426. cout << "Group threshold: " << gr_threshold << endl;
  427. break;
  428. case 'e':
  429. case 'E':
  430. gr_threshold = max(0, gr_threshold - 1);
  431. cout << "Group threshold: " << gr_threshold << endl;
  432. break;
  433. case '4':
  434. hit_threshold+=0.25;
  435. cout << "Hit threshold: " << hit_threshold << endl;
  436. break;
  437. case 'r':
  438. case 'R':
  439. hit_threshold = max(0.0, hit_threshold - 0.25);
  440. cout << "Hit threshold: " << hit_threshold << endl;
  441. break;
  442. case 'c':
  443. case 'C':
  444. gamma_corr = !gamma_corr;
  445. cout << "Gamma correction: " << gamma_corr << endl;
  446. break;
  447. }
  448. }
  449. inline void App::hogWorkBegin() { hog_work_begin = getTickCount(); }
  450. inline void App::hogWorkEnd()
  451. {
  452. int64 delta = getTickCount() - hog_work_begin;
  453. double freq = getTickFrequency();
  454. hog_work_fps = freq / delta;
  455. }
  456. inline string App::hogWorkFps() const
  457. {
  458. stringstream ss;
  459. ss << hog_work_fps;
  460. return ss.str();
  461. }
  462. inline void App::workBegin() { work_begin = getTickCount(); }
  463. inline void App::workEnd()
  464. {
  465. int64 delta = getTickCount() - work_begin;
  466. double freq = getTickFrequency();
  467. work_fps = freq / delta;
  468. }
  469. inline string App::workFps() const
  470. {
  471. stringstream ss;
  472. ss << work_fps;
  473. return ss.str();
  474. }