opencv_visualisation.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. ////////////////////////////////////////////////////////////////////////////////////////
  2. //
  3. // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
  4. //
  5. // By downloading, copying, installing or using the software you agree to this license.
  6. // If you do not agree to this license, do not download, install,
  7. // copy or use the software.
  8. //
  9. //
  10. // License Agreement
  11. // For Open Source Computer Vision Library
  12. //
  13. // Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
  14. // Copyright (C) 2009, Willow Garage Inc., all rights reserved.
  15. // Copyright (C) 2013, OpenCV Foundation, all rights reserved.
  16. // Third party copyrights are property of their respective owners.
  17. //
  18. // Redistribution and use in source and binary forms, with or without modification,
  19. // are permitted provided that the following conditions are met:
  20. //
  21. // * Redistribution's of source code must retain the above copyright notice,
  22. // this list of conditions and the following disclaimer.
  23. //
  24. // * Redistribution's in binary form must reproduce the above copyright notice,
  25. // this list of conditions and the following disclaimer in the documentation
  26. // and/or other materials provided with the distribution.
  27. //
  28. // * The name of the copyright holders may not be used to endorse or promote products
  29. // derived from this software without specific prior written permission.
  30. //
  31. // This software is provided by the copyright holders and contributors "as is" and
  32. // any express or implied warranties, including, but not limited to, the implied
  33. // warranties of merchantability and fitness for a particular purpose are disclaimed.
  34. // In no event shall the Intel Corporation or contributors be liable for any direct,
  35. // indirect, incidental, special, exemplary, or consequential damages
  36. // (including, but not limited to, procurement of substitute goods or services;
  37. // loss of use, data, or profits; or business interruption) however caused
  38. // and on any theory of liability, whether in contract, strict liability,
  39. // or tort (including negligence or otherwise) arising in any way out of
  40. // the use of this software, even if advised of the possibility of such damage.
  41. //
  42. ////////////////////////////////////////////////////////////////////////////////////////
  43. /*****************************************************************************************************
  44. Software for visualising cascade classifier models trained by OpenCV and to get a better
  45. understanding of the used features.
  46. USAGE:
  47. ./opencv_visualisation --model=<model.xml> --image=<ref.png> --data=<video output folder>
  48. Created by: Puttemans Steven - April 2016
  49. *****************************************************************************************************/
  50. #include <opencv2/core.hpp>
  51. #include <opencv2/highgui.hpp>
  52. #include <opencv2/imgproc.hpp>
  53. #include <opencv2/imgcodecs.hpp>
  54. #include <opencv2/videoio.hpp>
  55. #include <fstream>
  56. #include <iostream>
  57. using namespace std;
  58. using namespace cv;
  59. struct rect_data{
  60. int x;
  61. int y;
  62. int w;
  63. int h;
  64. float weight;
  65. };
  66. static void printLimits(){
  67. cerr << "Limits of the current interface:" << endl;
  68. cerr << " - Only handles cascade classifier models, trained with the opencv_traincascade tool, containing stumps as decision trees [default settings]." << endl;
  69. cerr << " - The image provided needs to be a sample window with the original model dimensions, passed to the --image parameter." << endl;
  70. cerr << " - ONLY handles HAAR and LBP features." << endl;
  71. }
  72. int main( int argc, const char** argv )
  73. {
  74. CommandLineParser parser(argc, argv,
  75. "{ help h usage ? | | show this message }"
  76. "{ image i | | (required) path to reference image }"
  77. "{ model m | | (required) path to cascade xml file }"
  78. "{ data d | | (optional) path to video output folder }"
  79. );
  80. // Read in the input arguments
  81. if (parser.has("help")){
  82. parser.printMessage();
  83. printLimits();
  84. return 0;
  85. }
  86. string model(parser.get<string>("model"));
  87. string output_folder(parser.get<string>("data"));
  88. string image_ref = (parser.get<string>("image"));
  89. if (model.empty() || image_ref.empty()){
  90. parser.printMessage();
  91. printLimits();
  92. return -1;
  93. }
  94. // Value for timing
  95. // You can increase this to have a better visualisation during the generation
  96. int timing = 1;
  97. // Value for cols of storing elements
  98. int cols_prefered = 5;
  99. // Open the XML model
  100. FileStorage fs;
  101. bool model_ok = fs.open(model, FileStorage::READ);
  102. if (!model_ok){
  103. cerr << "the cascade file '" << model << "' could not be loaded." << endl;
  104. return -1;
  105. }
  106. // Get a the required information
  107. // First decide which feature type we are using
  108. FileNode cascade = fs["cascade"];
  109. string feature_type = cascade["featureType"];
  110. bool haar = false, lbp = false;
  111. if (feature_type.compare("HAAR") == 0){
  112. haar = true;
  113. }
  114. if (feature_type.compare("LBP") == 0){
  115. lbp = true;
  116. }
  117. if ( feature_type.compare("HAAR") != 0 && feature_type.compare("LBP")){
  118. cerr << "The model is not an HAAR or LBP feature based model!" << endl;
  119. cerr << "Please select a model that can be visualized by the software." << endl;
  120. return -1;
  121. }
  122. // We make a visualisation mask - which increases the window to make it at least a bit more visible
  123. int resize_factor = 10;
  124. int resize_storage_factor = 10;
  125. Mat reference_image = imread(image_ref, IMREAD_GRAYSCALE );
  126. if (reference_image.empty()){
  127. cerr << "the reference image '" << image_ref << "'' could not be loaded." << endl;
  128. return -1;
  129. }
  130. Mat visualization;
  131. resize(reference_image, visualization, Size(reference_image.cols * resize_factor, reference_image.rows * resize_factor), 0, 0, INTER_LINEAR_EXACT);
  132. // First recover for each stage the number of weak features and their index
  133. // Important since it is NOT sequential when using LBP features
  134. vector< vector<int> > stage_features;
  135. FileNode stages = cascade["stages"];
  136. FileNodeIterator it_stages = stages.begin(), it_stages_end = stages.end();
  137. int idx = 0;
  138. for( ; it_stages != it_stages_end; it_stages++, idx++ ){
  139. vector<int> current_feature_indexes;
  140. FileNode weak_classifiers = (*it_stages)["weakClassifiers"];
  141. FileNodeIterator it_weak = weak_classifiers.begin(), it_weak_end = weak_classifiers.end();
  142. vector<int> values;
  143. for(int idy = 0; it_weak != it_weak_end; it_weak++, idy++ ){
  144. (*it_weak)["internalNodes"] >> values;
  145. current_feature_indexes.push_back( (int)values[2] );
  146. }
  147. stage_features.push_back(current_feature_indexes);
  148. }
  149. // If the output option has been chosen than we will store a combined image plane for
  150. // each stage, containing all weak classifiers for that stage.
  151. bool draw_planes = false;
  152. stringstream output_video;
  153. output_video << output_folder << "model_visualization.avi";
  154. VideoWriter result_video;
  155. if( output_folder.compare("") != 0 ){
  156. draw_planes = true;
  157. result_video.open(output_video.str(), VideoWriter::fourcc('X','V','I','D'), 15, Size(reference_image.cols * resize_factor, reference_image.rows * resize_factor), false);
  158. }
  159. if(haar){
  160. // Grab the corresponding features dimensions and weights
  161. FileNode features = cascade["features"];
  162. vector< vector< rect_data > > feature_data;
  163. FileNodeIterator it_features = features.begin(), it_features_end = features.end();
  164. for(int idf = 0; it_features != it_features_end; it_features++, idf++ ){
  165. vector< rect_data > current_feature_rectangles;
  166. FileNode rectangles = (*it_features)["rects"];
  167. int nrects = (int)rectangles.size();
  168. for(int k = 0; k < nrects; k++){
  169. rect_data current_data;
  170. FileNode single_rect = rectangles[k];
  171. current_data.x = (int)single_rect[0];
  172. current_data.y = (int)single_rect[1];
  173. current_data.w = (int)single_rect[2];
  174. current_data.h = (int)single_rect[3];
  175. current_data.weight = (float)single_rect[4];
  176. current_feature_rectangles.push_back(current_data);
  177. }
  178. feature_data.push_back(current_feature_rectangles);
  179. }
  180. // Loop over each possible feature on its index, visualise on the mask and wait a bit,
  181. // then continue to the next feature.
  182. // If visualisations should be stored then do the in between calculations
  183. Mat image_plane;
  184. Mat metadata = Mat::zeros(150, 1000, CV_8UC1);
  185. vector< rect_data > current_rects;
  186. for(int sid = 0; sid < (int)stage_features.size(); sid ++){
  187. if(draw_planes){
  188. int features_nmbr = (int)stage_features[sid].size();
  189. int cols = cols_prefered;
  190. int rows = features_nmbr / cols;
  191. if( (features_nmbr % cols) > 0){
  192. rows++;
  193. }
  194. image_plane = Mat::zeros(reference_image.rows * resize_storage_factor * rows, reference_image.cols * resize_storage_factor * cols, CV_8UC1);
  195. }
  196. for(int fid = 0; fid < (int)stage_features[sid].size(); fid++){
  197. stringstream meta1, meta2;
  198. meta1 << "Stage " << sid << " / Feature " << fid;
  199. meta2 << "Rectangles: ";
  200. Mat temp_window = visualization.clone();
  201. Mat temp_metadata = metadata.clone();
  202. int current_feature_index = stage_features[sid][fid];
  203. current_rects = feature_data[current_feature_index];
  204. Mat single_feature = reference_image.clone();
  205. resize(single_feature, single_feature, Size(), resize_storage_factor, resize_storage_factor, INTER_LINEAR_EXACT);
  206. for(int i = 0; i < (int)current_rects.size(); i++){
  207. rect_data local = current_rects[i];
  208. if(draw_planes){
  209. if(local.weight >= 0){
  210. rectangle(single_feature, Rect(local.x * resize_storage_factor, local.y * resize_storage_factor, local.w * resize_storage_factor, local.h * resize_storage_factor), Scalar(0), FILLED);
  211. }else{
  212. rectangle(single_feature, Rect(local.x * resize_storage_factor, local.y * resize_storage_factor, local.w * resize_storage_factor, local.h * resize_storage_factor), Scalar(255), FILLED);
  213. }
  214. }
  215. Rect part(local.x * resize_factor, local.y * resize_factor, local.w * resize_factor, local.h * resize_factor);
  216. meta2 << part << " (w " << local.weight << ") ";
  217. if(local.weight >= 0){
  218. rectangle(temp_window, part, Scalar(0), FILLED);
  219. }else{
  220. rectangle(temp_window, part, Scalar(255), FILLED);
  221. }
  222. }
  223. imshow("features", temp_window);
  224. putText(temp_window, meta1.str(), Point(15,15), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255));
  225. result_video.write(temp_window);
  226. // Copy the feature image if needed
  227. if(draw_planes){
  228. single_feature.copyTo(image_plane(Rect(0 + (fid%cols_prefered)*single_feature.cols, 0 + (fid/cols_prefered) * single_feature.rows, single_feature.cols, single_feature.rows)));
  229. }
  230. putText(temp_metadata, meta1.str(), Point(15,15), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255));
  231. putText(temp_metadata, meta2.str(), Point(15,40), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255));
  232. imshow("metadata", temp_metadata);
  233. waitKey(timing);
  234. }
  235. //Store the stage image if needed
  236. if(draw_planes){
  237. stringstream save_location;
  238. save_location << output_folder << "stage_" << sid << ".png";
  239. imwrite(save_location.str(), image_plane);
  240. }
  241. }
  242. }
  243. if(lbp){
  244. // Grab the corresponding features dimensions and weights
  245. FileNode features = cascade["features"];
  246. vector<Rect> feature_data;
  247. FileNodeIterator it_features = features.begin(), it_features_end = features.end();
  248. for(int idf = 0; it_features != it_features_end; it_features++, idf++ ){
  249. FileNode rectangle = (*it_features)["rect"];
  250. Rect current_feature ((int)rectangle[0], (int)rectangle[1], (int)rectangle[2], (int)rectangle[3]);
  251. feature_data.push_back(current_feature);
  252. }
  253. // Loop over each possible feature on its index, visualise on the mask and wait a bit,
  254. // then continue to the next feature.
  255. Mat image_plane;
  256. Mat metadata = Mat::zeros(150, 1000, CV_8UC1);
  257. for(int sid = 0; sid < (int)stage_features.size(); sid ++){
  258. if(draw_planes){
  259. int features_nmbr = (int)stage_features[sid].size();
  260. int cols = cols_prefered;
  261. int rows = features_nmbr / cols;
  262. if( (features_nmbr % cols) > 0){
  263. rows++;
  264. }
  265. image_plane = Mat::zeros(reference_image.rows * resize_storage_factor * rows, reference_image.cols * resize_storage_factor * cols, CV_8UC1);
  266. }
  267. for(int fid = 0; fid < (int)stage_features[sid].size(); fid++){
  268. stringstream meta1, meta2;
  269. meta1 << "Stage " << sid << " / Feature " << fid;
  270. meta2 << "Rectangle: ";
  271. Mat temp_window = visualization.clone();
  272. Mat temp_metadata = metadata.clone();
  273. int current_feature_index = stage_features[sid][fid];
  274. Rect current_rect = feature_data[current_feature_index];
  275. Mat single_feature = reference_image.clone();
  276. resize(single_feature, single_feature, Size(), resize_storage_factor, resize_storage_factor, INTER_LINEAR_EXACT);
  277. // VISUALISATION
  278. // The rectangle is the top left one of a 3x3 block LBP constructor
  279. Rect resized(current_rect.x * resize_factor, current_rect.y * resize_factor, current_rect.width * resize_factor, current_rect.height * resize_factor);
  280. meta2 << resized;
  281. // Top left
  282. rectangle(temp_window, resized, Scalar(255), 1);
  283. // Top middle
  284. rectangle(temp_window, Rect(resized.x + resized.width, resized.y, resized.width, resized.height), Scalar(255), 1);
  285. // Top right
  286. rectangle(temp_window, Rect(resized.x + 2*resized.width, resized.y, resized.width, resized.height), Scalar(255), 1);
  287. // Middle left
  288. rectangle(temp_window, Rect(resized.x, resized.y + resized.height, resized.width, resized.height), Scalar(255), 1);
  289. // Middle middle
  290. rectangle(temp_window, Rect(resized.x + resized.width, resized.y + resized.height, resized.width, resized.height), Scalar(255), FILLED);
  291. // Middle right
  292. rectangle(temp_window, Rect(resized.x + 2*resized.width, resized.y + resized.height, resized.width, resized.height), Scalar(255), 1);
  293. // Bottom left
  294. rectangle(temp_window, Rect(resized.x, resized.y + 2*resized.height, resized.width, resized.height), Scalar(255), 1);
  295. // Bottom middle
  296. rectangle(temp_window, Rect(resized.x + resized.width, resized.y + 2*resized.height, resized.width, resized.height), Scalar(255), 1);
  297. // Bottom right
  298. rectangle(temp_window, Rect(resized.x + 2*resized.width, resized.y + 2*resized.height, resized.width, resized.height), Scalar(255), 1);
  299. if(draw_planes){
  300. Rect resized_inner(current_rect.x * resize_storage_factor, current_rect.y * resize_storage_factor, current_rect.width * resize_storage_factor, current_rect.height * resize_storage_factor);
  301. // Top left
  302. rectangle(single_feature, resized_inner, Scalar(255), 1);
  303. // Top middle
  304. rectangle(single_feature, Rect(resized_inner.x + resized_inner.width, resized_inner.y, resized_inner.width, resized_inner.height), Scalar(255), 1);
  305. // Top right
  306. rectangle(single_feature, Rect(resized_inner.x + 2*resized_inner.width, resized_inner.y, resized_inner.width, resized_inner.height), Scalar(255), 1);
  307. // Middle left
  308. rectangle(single_feature, Rect(resized_inner.x, resized_inner.y + resized_inner.height, resized_inner.width, resized_inner.height), Scalar(255), 1);
  309. // Middle middle
  310. rectangle(single_feature, Rect(resized_inner.x + resized_inner.width, resized_inner.y + resized_inner.height, resized_inner.width, resized_inner.height), Scalar(255), FILLED);
  311. // Middle right
  312. rectangle(single_feature, Rect(resized_inner.x + 2*resized_inner.width, resized_inner.y + resized_inner.height, resized_inner.width, resized_inner.height), Scalar(255), 1);
  313. // Bottom left
  314. rectangle(single_feature, Rect(resized_inner.x, resized_inner.y + 2*resized_inner.height, resized_inner.width, resized_inner.height), Scalar(255), 1);
  315. // Bottom middle
  316. rectangle(single_feature, Rect(resized_inner.x + resized_inner.width, resized_inner.y + 2*resized_inner.height, resized_inner.width, resized_inner.height), Scalar(255), 1);
  317. // Bottom right
  318. rectangle(single_feature, Rect(resized_inner.x + 2*resized_inner.width, resized_inner.y + 2*resized_inner.height, resized_inner.width, resized_inner.height), Scalar(255), 1);
  319. single_feature.copyTo(image_plane(Rect(0 + (fid%cols_prefered)*single_feature.cols, 0 + (fid/cols_prefered) * single_feature.rows, single_feature.cols, single_feature.rows)));
  320. }
  321. putText(temp_metadata, meta1.str(), Point(15,15), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255));
  322. putText(temp_metadata, meta2.str(), Point(15,40), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255));
  323. imshow("metadata", temp_metadata);
  324. imshow("features", temp_window);
  325. putText(temp_window, meta1.str(), Point(15,15), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255));
  326. result_video.write(temp_window);
  327. waitKey(timing);
  328. }
  329. //Store the stage image if needed
  330. if(draw_planes){
  331. stringstream save_location;
  332. save_location << output_folder << "stage_" << sid << ".png";
  333. imwrite(save_location.str(), image_plane);
  334. }
  335. }
  336. }
  337. return 0;
  338. }