SemSegTools.cpp 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. /**
  2. * @file SemSegTools.cpp
  3. * @brief tools for semantic segmentation
  4. * @author Erik Rodner, Sven Sickert
  5. * @date 03/19/2009
  6. */
  7. #include <iostream>
  8. #include "SemSegTools.h"
  9. using namespace OBJREC;
  10. using namespace std;
  11. using namespace NICE;
  12. #undef DEBUG_LOCALIZATION
  13. #undef DEBUG
  14. void SemSegTools::segmentToOverlay (
  15. const NICE::Image *orig,
  16. const NICE::ColorImage & segment,
  17. NICE::ColorImage & result )
  18. {
  19. int xsize = orig->width();
  20. int ysize = orig->height();
  21. result.resize( xsize, ysize );
  22. std::vector< NICE::MatrixT<double> > channelMat;
  23. double alpha = .5;
  24. for (int c = 0; c < 3; c++)
  25. {
  26. NICE::MatrixT<double> chan ( xsize, ysize );
  27. channelMat.push_back( chan );
  28. }
  29. for (int y = 0; y < ysize; y++)
  30. {
  31. for (int x = 0; x < xsize; x++)
  32. {
  33. uchar val = orig->getPixelQuick(x,y);
  34. for (int c = 0; c < 3; c++)
  35. channelMat[c](x,y) = (double)val + alpha*(double)segment.getPixel( x, y, c );
  36. }
  37. }
  38. for (int c = 0; c < 3; c++)
  39. {
  40. channelMat[c] /= channelMat[c].Max();
  41. channelMat[c] *= 255;
  42. }
  43. for (int y = 0; y < ysize; y++)
  44. {
  45. for (int x = 0; x < xsize; x++)
  46. {
  47. for (int c = 0; c < 3; c++)
  48. {
  49. int val = channelMat[c](x,y);
  50. result.setPixel( x, y, c, (uchar)val);
  51. }
  52. }
  53. }
  54. }
  55. void SemSegTools::updateConfusionMatrix(
  56. const Image &img,
  57. const Image &gt,
  58. Matrix &M,
  59. const std::set<int> &forbiddenClasses )
  60. {
  61. double subsamplex = gt.width() / ( double ) img.width();
  62. double subsampley = gt.height() / ( double ) img.height();
  63. for ( int y = 0 ; y < gt.height() ; y++ )
  64. for ( int x = 0 ; x < gt.width() ; x++ )
  65. {
  66. int xx = ( int ) ( x / subsamplex );
  67. int yy = ( int ) ( y / subsampley );
  68. if ( xx < 0 ) xx = 0;
  69. if ( yy < 0 ) yy = 0;
  70. if ( xx > img.width() - 1 ) xx = img.width() - 1;
  71. if ( yy > img.height() - 1 ) yy = img.height() - 1;
  72. int cimg = img.getPixel ( xx, yy );
  73. int gimg = gt.getPixel ( x, y );
  74. if ( forbiddenClasses.find ( gimg ) == forbiddenClasses.end() )
  75. {
  76. M ( gimg, cimg ) ++;
  77. }
  78. }
  79. }
  80. void SemSegTools::computeClassificationStatistics(
  81. Matrix &confMat,
  82. const ClassNames &classNames,
  83. const std::set<int> &forbiddenClasses )
  84. {
  85. double overallTrue = 0.0;
  86. double sumAll = 0.0;
  87. // print confusion matrix & get overall recognition rate
  88. std::cout << "Confusion Matrix:" << std::endl;
  89. for ( int r = 0; r < (int) confMat.rows(); r++ )
  90. {
  91. for ( int c = 0; c < (int) confMat.cols(); c++ )
  92. {
  93. if ( r == c )
  94. overallTrue += confMat( r, c );
  95. sumAll += confMat( r, c );
  96. std::cout << confMat( r, c ) << " ";
  97. }
  98. std::cout << std::endl;
  99. }
  100. overallTrue /= sumAll;
  101. // binary classification metrics
  102. double precision, recall, f1score = -1.0;
  103. if ( confMat.rows() == 2 )
  104. {
  105. precision = (double)confMat(1,1) / (double)(confMat(1,1)+confMat(0,1));
  106. recall = (double)confMat(1,1) / (double)(confMat(1,1)+confMat(1,0));
  107. f1score = 2.0*(precision*recall)/(precision+recall);
  108. }
  109. // normalizing confMat using rows
  110. for ( int r = 0 ; r < (int) confMat.rows() ; r++ )
  111. {
  112. double sum = 0.0;
  113. for ( int c = 0 ; c < (int) confMat.cols() ; c++ )
  114. sum += confMat ( r, c );
  115. if ( std::fabs ( sum ) > 1e-4 )
  116. for ( int c = 0 ; c < (int) confMat.cols() ; c++ )
  117. confMat ( r, c ) /= sum;
  118. }
  119. // get average recognition rate
  120. double avgTrue = 0.0;
  121. int classesTrained = 0;
  122. for ( int r = 0 ; r < (int) confMat.rows() ; r++ )
  123. {
  124. if ( classNames.existsClassno ( r )
  125. && ( forbiddenClasses.find ( r ) == forbiddenClasses.end() ) )
  126. {
  127. avgTrue += confMat ( r, r );
  128. double lsum = 0.0;
  129. for ( int r2 = 0; r2 < ( int ) confMat.rows(); r2++ )
  130. lsum += confMat ( r,r2 );
  131. if ( lsum != 0.0 )
  132. classesTrained++;
  133. }
  134. }
  135. // print classification statistics
  136. std::cout << "\nOverall Recogntion Rate: " << overallTrue;
  137. std::cout << "\nAverage Recogntion Rate: " << avgTrue / ( classesTrained );
  138. std::cout << "\nLower Bound: " << 1.0 /(double)classesTrained;
  139. std::cout << "\nPrecision: " << precision;
  140. std::cout << "\nRecall: " << recall;
  141. std::cout << "\nF1Score: " << f1score;
  142. std::cout <<"\n\nClasses:" << std::endl;
  143. for ( int r = 0 ; r < (int) confMat.rows() ; r++ )
  144. {
  145. if ( classNames.existsClassno ( r )
  146. && ( forbiddenClasses.find ( r ) == forbiddenClasses.end() ) )
  147. {
  148. std::string cname = classNames.text ( r );
  149. std::cout << cname.c_str() << ": " << confMat ( r, r ) << std::endl;
  150. }
  151. }
  152. }
  153. void SemSegTools::saveResultsToImageFile(
  154. const Config *conf,
  155. const string &section,
  156. const ColorImage &orig,
  157. const ColorImage &gtruth,
  158. const ColorImage &segment,
  159. const string &file )
  160. {
  161. std::string resultDir = conf->gS ( section, "resultdir", "." );
  162. std::string outputType = conf->gS ( section, "output_type", "ppm" );
  163. std::string outputPostfix = conf->gS ( section, "output_postfix", "" );
  164. NICE::ColorImage overlaySegment, overlayGTruth;
  165. segmentToOverlay( orig.getChannel(1), segment, overlaySegment );
  166. segmentToOverlay( orig.getChannel(1), gtruth, overlayGTruth );
  167. std::stringstream out;
  168. out << resultDir << "/" << file << outputPostfix;
  169. #ifdef DEBUG
  170. std::cout << "Writing to file " << out.str() << "_*." << outputType << std::endl;
  171. #endif
  172. orig.write ( out.str() + "_orig." + outputType );
  173. segment.write ( out.str() + "_result." + outputType );
  174. gtruth.write ( out.str() + "_groundtruth." + outputType );
  175. overlaySegment.write ( out.str() + "_overlay_res." + outputType );
  176. overlayGTruth.write ( out.str() + "_overlay_gt." + outputType );
  177. }
  178. void SemSegTools::collectTrainingExamples (
  179. const Config * conf,
  180. const std::string & section,
  181. const LabeledSet & train,
  182. const ClassNames & cn,
  183. Examples & examples,
  184. vector<CachedExample *> & imgexamples )
  185. {
  186. assert ( train.count() > 0 );
  187. examples.clear();
  188. imgexamples.clear();
  189. int grid_size_x = conf->gI(section, "grid_size_x", 5 );
  190. int grid_size_y = conf->gI(section, "grid_size_y", 5 );
  191. int grid_border_x = conf->gI(section, "grid_border_x", 20 );
  192. int grid_border_y = conf->gI(section, "grid_border_y", 20 );
  193. std::string selection = conf->gS(section, "train_selection" );
  194. set<int> classnoSelection;
  195. cn.getSelection ( selection, classnoSelection );
  196. bool useExcludedAsBG = conf->gB(section, "use_excluded_as_background", false );
  197. int backgroundClassNo = 0;
  198. if ( useExcludedAsBG )
  199. {
  200. backgroundClassNo = cn.classno("various");
  201. assert ( backgroundClassNo >= 0 );
  202. }
  203. LOOP_ALL_S (train)
  204. {
  205. EACH_INFO(image_classno,imgInfo);
  206. std::string imgfn = imgInfo.img();
  207. if ( ! imgInfo.hasLocalizationInfo() ) {
  208. std::cerr << "WARNING: NO localization info found for "
  209. << imgfn << " !" << std::endl;
  210. continue;
  211. }
  212. int xsize, ysize;
  213. CachedExample *ce = new CachedExample ( imgfn );
  214. ce->getImageSize ( xsize, ysize );
  215. imgexamples.push_back ( ce );
  216. const LocalizationResult *locResult = imgInfo.localization();
  217. if ( locResult->size() <= 0 ) {
  218. std::cerr << "WARNING: NO ground truth polygons found for "
  219. << imgfn << " !" << std::endl;
  220. continue;
  221. }
  222. std::cerr << "SemSegTools: Collecting pixel examples from localization info: "
  223. << imgfn << std::endl;
  224. NICE::Image pixelLabels (xsize, ysize);
  225. pixelLabels.set(0);
  226. locResult->calcLabeledImage ( pixelLabels, cn.getBackgroundClass() );
  227. #ifdef DEBUG_LOCALIZATION
  228. NICE::Image img (imgfn);
  229. showImage(img);
  230. showImage(pixelLabels);
  231. #endif
  232. Example pce ( ce, 0, 0 );
  233. for ( int x = 0 ; x < xsize ; x += grid_size_x )
  234. for ( int y = 0 ; y < ysize ; y += grid_size_y )
  235. {
  236. if ( (x >= grid_border_x) &&
  237. ( y >= grid_border_y ) && ( x < xsize - grid_border_x ) &&
  238. ( y < ysize - grid_border_x ) )
  239. {
  240. pce.x = x; pce.y = y;
  241. int classno = pixelLabels.getPixel(x,y);
  242. if ( classnoSelection.find(classno) != classnoSelection.end() ) {
  243. examples.push_back ( pair<int, Example> (
  244. classno,
  245. pce // FIXME: offset handling
  246. ) );
  247. } else if ( useExcludedAsBG ) {
  248. examples.push_back ( pair<int, Example> (
  249. backgroundClassNo,
  250. pce // FIXME: offset handling
  251. ) );
  252. }
  253. }
  254. }
  255. }
  256. std::cerr << "total number of examples: " << (int)examples.size() << std::endl;
  257. }