SemSegContextTree3D.cpp 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864
  1. #include "SemSegContextTree3D.h"
  2. #include "SemSegTools.h"
  3. #include <core/basics/FileName.h>
  4. #include <core/basics/numerictools.h>
  5. #include <core/basics/quadruplet.h>
  6. #include <core/basics/StringTools.h>
  7. #include <core/basics/Timer.h>
  8. #include <core/basics/vectorio.h>
  9. #include <core/image/FilterT.h>
  10. #include <core/image/Morph.h>
  11. #include <core/imagedisplay/ImageDisplay.h>
  12. #include <vislearning/baselib/cc.h>
  13. #include <vislearning/baselib/Globals.h>
  14. #include <vislearning/baselib/ICETools.h>
  15. #include <vislearning/cbaselib/CachedExample.h>
  16. #include <vislearning/cbaselib/PascalResults.h>
  17. #include <segmentation/RSGraphBased.h>
  18. #include <segmentation/RSMeanShift.h>
  19. #include <segmentation/RSSlic.h>
  20. #include <omp.h>
  21. #include <time.h>
  22. #include <iostream>
  23. #define VERBOSE
  24. #undef DEBUG
  25. #undef VISUALIZE
  26. #undef WRITEREGIONS
  27. using namespace OBJREC;
  28. using namespace std;
  29. using namespace NICE;
  30. //###################### CONSTRUCTORS #########################//
  31. SemSegContextTree3D::SemSegContextTree3D () : SemanticSegmentation ()
  32. {
  33. this->firstiteration = true;
  34. this->run3Dseg = false;
  35. this->maxSamples = 2000;
  36. this->minFeats = 50;
  37. this->maxDepth = 10;
  38. this->windowSize = 15;
  39. this->featsPerSplit = 200;
  40. this->useShannonEntropy = true;
  41. this->nbTrees = 10;
  42. this->randomTests = 10;
  43. this->useAltTristimulus = false;
  44. this->useGradient = true;
  45. this->useAdditionalLayer = false;
  46. this->numAdditionalLayer = 0;
  47. this->useCategorization = false;
  48. this->cndir = "";
  49. this->fasthik = NULL;
  50. this->saveLoadData = false;
  51. this->fileLocation = "tmp.txt";
  52. this->pixelWiseLabeling = true;
  53. this->segmentation = NULL;
  54. this->useFeat0 = true;
  55. this->useFeat1 = false;
  56. this->useFeat2 = true;
  57. this->useFeat3 = true;
  58. this->useFeat4 = false;
  59. this->labelIncrement = 1;
  60. if (coarseMode)
  61. this->labelIncrement = 6;
  62. srand(time(NULL));
  63. }
  64. SemSegContextTree3D::SemSegContextTree3D (
  65. const Config *conf,
  66. const ClassNames *classNames )
  67. : SemanticSegmentation ( conf, classNames )
  68. {
  69. this->conf = conf;
  70. string section = "SSContextTree";
  71. string featsec = "Features";
  72. this->firstiteration = true;
  73. this->maxSamples = conf->gI ( section, "max_samples", 2000 );
  74. this->minFeats = conf->gI ( section, "min_feats", 50 );
  75. this->maxDepth = conf->gI ( section, "max_depth", 10 );
  76. this->windowSize = conf->gI ( section, "window_size", 15 );
  77. this->featsPerSplit = conf->gI ( section, "feats_per_split", 200 );
  78. this->useShannonEntropy = conf->gB ( section, "use_shannon_entropy", true );
  79. this->nbTrees = conf->gI ( section, "amount_trees", 10 );
  80. this->randomTests = conf->gI ( section, "random_tests", 10 );
  81. this->useAltTristimulus = conf->gB ( featsec, "use_alt_trist", false );
  82. this->useGradient = conf->gB ( featsec, "use_gradient", true );
  83. this->useAdditionalLayer = conf->gB ( featsec, "use_additional_layer", false );
  84. if (useAdditionalLayer)
  85. this->numAdditionalLayer = conf->gI ( featsec, "num_additional_layer", 1 );
  86. else
  87. this->numAdditionalLayer = 0;
  88. this->useCategorization = conf->gB ( section, "use_categorization", false );
  89. this->cndir = conf->gS ( "SSContextTree", "cndir", "" );
  90. this->saveLoadData = conf->gB ( "debug", "save_load_data", false );
  91. this->fileLocation = conf->gS ( "debug", "datafile", "tmp.txt" );
  92. this->pixelWiseLabeling = conf->gB ( section, "pixelWiseLabeling", false );
  93. if (coarseMode)
  94. this->labelIncrement = conf->gI ( section, "label_increment", 6 );
  95. else
  96. this->labelIncrement = 1;
  97. if ( useCategorization && cndir == "" )
  98. this->fasthik = new FPCGPHIK ( conf );
  99. else
  100. this->fasthik = NULL;
  101. this->classnames = (*classNames);
  102. string forbidden_classes_s = conf->gS ( "analysis", "forbidden_classes", "" );
  103. classnames.getSelection ( forbidden_classes_s, forbidden_classes );
  104. // feature types
  105. this->useFeat0 = conf->gB ( section, "use_feat_0", true); // pixel pair features
  106. this->useFeat1 = conf->gB ( section, "use_feat_1", false); // region feature
  107. this->useFeat2 = conf->gB ( section, "use_feat_2", true); // integral features
  108. this->useFeat3 = conf->gB ( section, "use_feat_3", true); // integral contex features
  109. this->useFeat4 = conf->gB ( section, "use_feat_4", false); // pixel pair context features
  110. string segmentationtype = conf->gS ( section, "segmentation_type", "none" );
  111. if ( segmentationtype == "meanshift" )
  112. this->segmentation = new RSMeanShift ( conf );
  113. else if ( segmentationtype == "felzenszwalb" )
  114. this->segmentation = new RSGraphBased ( conf );
  115. else if ( segmentationtype == "slic" )
  116. this->segmentation = new RSSlic ( conf );
  117. else if ( segmentationtype == "none" )
  118. {
  119. this->segmentation = NULL;
  120. this->pixelWiseLabeling = true;
  121. this->useFeat1 = false;
  122. }
  123. else
  124. throw ( "no valid segmenation_type\n please choose between none, meanshift, slic and felzenszwalb\n" );
  125. if ( useFeat0 )
  126. this->featTypes.push_back(0);
  127. if ( useFeat1 )
  128. this->featTypes.push_back(1);
  129. if ( useFeat2 )
  130. this->featTypes.push_back(2);
  131. if ( useFeat3 )
  132. this->featTypes.push_back(3);
  133. if ( useFeat4 )
  134. this->featTypes.push_back(4);
  135. srand(time(NULL));
  136. this->initOperations();
  137. }
  138. //###################### DESTRUCTORS ##########################//
  139. SemSegContextTree3D::~SemSegContextTree3D()
  140. {
  141. }
  142. //#################### MEMBER FUNCTIONS #######################//
  143. void SemSegContextTree3D::initOperations()
  144. {
  145. this->ops.push_back ( new SimpleOperationPool ( conf ) );
  146. this->ops.push_back ( new RegionOperationPool ( conf ) );
  147. this->ops.push_back ( new RectangleOperationPool ( conf ) );
  148. this->ops.push_back ( new RectangleOperationPool ( conf, true ) );
  149. this->ops.push_back ( new SimpleOperationPool ( conf, true ) );
  150. for ( unsigned short i = 0; i < ops.size(); i++ )
  151. ops[i]->getOperations();
  152. }
  153. double SemSegContextTree3D::getBestSplit (
  154. std::vector<NICE::MultiChannelImage3DT<double> > &feats,
  155. std::vector<NICE::MultiChannelImage3DT<unsigned short int> > &nodeIndices,
  156. const std::vector<NICE::MultiChannelImageT<int> > &labels,
  157. int node,
  158. Operation3D *&splitop,
  159. double &splitval,
  160. const int &tree,
  161. vector<vector<vector<double> > > &regionProbs )
  162. {
  163. Timer t;
  164. t.start();
  165. int imgCount = 0;
  166. try
  167. {
  168. imgCount = ( int ) feats.size();
  169. }
  170. catch ( Exception )
  171. {
  172. cerr << "no features computed?" << endl;
  173. }
  174. double bestig = -numeric_limits< double >::max();
  175. splitop = NULL;
  176. splitval = -1.0;
  177. vector<quadruplet<int,int,int,int> > selFeats;
  178. map<int, int> e;
  179. int featcounter = forest[tree][node].featcounter;
  180. if ( featcounter < minFeats )
  181. {
  182. return 0.0;
  183. }
  184. vector<double> fraction ( a.size(), 0.0 );
  185. for ( uint i = 0; i < fraction.size(); i++ )
  186. {
  187. if ( forbidden_classes.find ( labelmapback[i] ) != forbidden_classes.end() )
  188. fraction[i] = 0;
  189. else
  190. fraction[i] = ( ( double ) maxSamples ) / ( ( double ) featcounter * a[i] * a.size() );
  191. }
  192. featcounter = 0;
  193. for ( int iCounter = 0; iCounter < imgCount; iCounter++ )
  194. {
  195. int xsize = ( int ) nodeIndices[iCounter].width();
  196. int ysize = ( int ) nodeIndices[iCounter].height();
  197. int zsize = ( int ) nodeIndices[iCounter].depth();
  198. for ( int x = 0; x < xsize; x++ )
  199. for ( int y = 0; y < ysize; y++ )
  200. for ( int z = 0; z < zsize; z++ )
  201. {
  202. if ( nodeIndices[iCounter].get ( x, y, z, tree ) == node )
  203. {
  204. int cn = labels[iCounter].get ( x, y, ( uint ) z );
  205. double randD = ( double ) rand() / ( double ) RAND_MAX;
  206. if ( labelmap.find ( cn ) == labelmap.end() )
  207. continue;
  208. if ( randD < fraction[labelmap[cn]] )
  209. {
  210. quadruplet<int,int,int,int> quad( iCounter, x, y, z );
  211. featcounter++;
  212. selFeats.push_back ( quad );
  213. e[cn]++;
  214. }
  215. }
  216. }
  217. }
  218. // global entropy
  219. double globent = 0.0;
  220. for ( map<int, int>::iterator mapit = e.begin() ; mapit != e.end(); mapit++ )
  221. {
  222. double p = ( double ) ( *mapit ).second / ( double ) featcounter;
  223. globent += p * log2 ( p );
  224. }
  225. globent = -globent;
  226. if ( globent < 0.5 )
  227. return 0.0;
  228. for ( int f = 0; f < featsPerSplit; f++ )
  229. {
  230. int x1, x2, y1, y2, z1, z2, ft;
  231. do
  232. {
  233. ft = featTypes[ (int)(rand() % featTypes.size()) ];
  234. }
  235. while ( channelsPerType[ft].size() == 0 );
  236. /* random window positions */
  237. x1 = ( int ) ( rand() % windowSize ) - windowSize / 2 ;
  238. x2 = ( int ) ( rand() % windowSize ) - windowSize / 2 ;
  239. y1 = ( int ) ( rand() % windowSize ) - windowSize / 2 ;
  240. y2 = ( int ) ( rand() % windowSize ) - windowSize / 2 ;
  241. z1 = ( int ) ( rand() % windowSize ) - windowSize / 2 ;
  242. z2 = ( int ) ( rand() % windowSize ) - windowSize / 2 ;
  243. /* random feature maps (channels) */
  244. int f1, f2;
  245. f1 = ( int ) ( rand() % channelsPerType[ft].size() );
  246. f1 = channelsPerType[ft][f1];
  247. f2 = ( int ) ( rand() % classNames->numClasses() );
  248. /* random extraction method (operation) */
  249. int o = ( int ) ( rand() % ops[ft]->pool.size() );
  250. Operation3D *op = ops[ft]->pool[o]->clone();
  251. op->set ( x1, y1, z1, x2, y2, z2, f1, f2, ft );
  252. op->setWSize( windowSize );
  253. /* do actual split tests */
  254. double l_bestig = -numeric_limits< double >::max();
  255. double l_splitval = -1.0;
  256. vector<double> vals;
  257. double maxval = -numeric_limits<double>::max();
  258. double minval = numeric_limits<double>::max();
  259. int counter = 0;
  260. for ( vector<quadruplet<int,int,int,int> >::const_iterator it = selFeats.begin();
  261. it != selFeats.end(); it++ )
  262. {
  263. Features feat;
  264. feat.feats = &feats[ ( *it ).first ];
  265. feat.rProbs = &regionProbs[ ( *it ).first ];
  266. assert ( forest.size() > ( uint ) tree );
  267. assert ( forest[tree][0].dist.size() > 0 );
  268. double val = 0.0;
  269. val = op->getVal ( feat, ( *it ).second, ( *it ).third, ( *it ).fourth );
  270. if ( !isfinite ( val ) )
  271. {
  272. #ifdef DEBUG
  273. cerr << "feat " << feat.feats->width() << " " << feat.feats->height() << " " << feat.feats->depth() << endl;
  274. cerr << "non finite value " << val << " for " << op->writeInfos() << endl << (*it).second << " " << (*it).third << " " << (*it).fourth << endl;
  275. #endif
  276. val = 0.0;
  277. }
  278. vals.push_back ( val );
  279. maxval = std::max ( val, maxval );
  280. minval = std::min ( val, minval );
  281. }
  282. if ( minval == maxval )
  283. continue;
  284. // split values
  285. for ( int run = 0 ; run < randomTests; run++ )
  286. {
  287. // choose threshold randomly
  288. double sval = 0.0;
  289. sval = ( (double) rand() / (double) RAND_MAX*(maxval-minval) ) + minval;
  290. map<int, int> eL, eR;
  291. int counterL = 0, counterR = 0;
  292. counter = 0;
  293. for ( vector<quadruplet<int,int,int,int> >::const_iterator it2 = selFeats.begin();
  294. it2 != selFeats.end(); it2++, counter++ )
  295. {
  296. int cn = labels[ ( *it2 ).first ].get ( ( *it2 ).second, ( *it2 ).third, ( *it2 ).fourth );
  297. //cout << "vals[counter2] " << vals[counter2] << " val: " << val << endl;
  298. if ( vals[counter] < sval )
  299. {
  300. //left entropie:
  301. eL[cn] = eL[cn] + 1;
  302. counterL++;
  303. }
  304. else
  305. {
  306. //right entropie:
  307. eR[cn] = eR[cn] + 1;
  308. counterR++;
  309. }
  310. }
  311. double leftent = 0.0;
  312. for ( map<int, int>::iterator mapit = eL.begin() ; mapit != eL.end(); mapit++ )
  313. {
  314. double p = ( double ) ( *mapit ).second / ( double ) counterL;
  315. leftent -= p * log2 ( p );
  316. }
  317. double rightent = 0.0;
  318. for ( map<int, int>::iterator mapit = eR.begin() ; mapit != eR.end(); mapit++ )
  319. {
  320. double p = ( double ) ( *mapit ).second / ( double ) counterR;
  321. rightent -= p * log2 ( p );
  322. }
  323. //cout << "rightent: " << rightent << " leftent: " << leftent << endl;
  324. double pl = ( double ) counterL / ( double ) ( counterL + counterR );
  325. //information gain
  326. double ig = globent - ( 1.0 - pl ) * rightent - pl * leftent;
  327. //double ig = globent - rightent - leftent;
  328. if ( useShannonEntropy )
  329. {
  330. double esplit = - ( pl * log ( pl ) + ( 1 - pl ) * log ( 1 - pl ) );
  331. ig = 2 * ig / ( globent + esplit );
  332. }
  333. if ( ig > l_bestig )
  334. {
  335. l_bestig = ig;
  336. l_splitval = sval;
  337. }
  338. }
  339. if ( l_bestig > bestig )
  340. {
  341. bestig = l_bestig;
  342. splitop = op;
  343. splitval = l_splitval;
  344. }
  345. }
  346. #ifdef DEBUG
  347. cout << "globent: " << globent << " bestig " << bestig << " splitval: " << splitval << endl;
  348. #endif
  349. return bestig;
  350. }
  351. inline double SemSegContextTree3D::getMeanProb (
  352. const int &x,
  353. const int &y,
  354. const int &z,
  355. const int &channel,
  356. const MultiChannelImage3DT<unsigned short int> &nodeIndices )
  357. {
  358. double val = 0.0;
  359. for ( int tree = 0; tree < nbTrees; tree++ )
  360. {
  361. val += forest[tree][nodeIndices.get ( x,y,z,tree ) ].dist[channel];
  362. }
  363. return val / ( double ) nbTrees;
  364. }
  365. void SemSegContextTree3D::updateProbabilityMaps (
  366. const NICE::MultiChannelImage3DT<unsigned short int> &nodeIndices,
  367. NICE::MultiChannelImage3DT<double> &feats,
  368. int firstChannel )
  369. {
  370. int xsize = feats.width();
  371. int ysize = feats.height();
  372. int zsize = feats.depth();
  373. int classes = ( int ) labelmap.size();
  374. // integral images for context channels (probability maps for each class)
  375. #pragma omp parallel for
  376. for ( int c = 0; c < classes; c++ )
  377. {
  378. for ( int z = 0; z < zsize; z++ )
  379. for ( int y = 0; y < ysize; y++ )
  380. for ( int x = 0; x < xsize; x++ )
  381. {
  382. double val = getMeanProb ( x, y, z, c, nodeIndices );
  383. if (useFeat3 || useFeat4)
  384. feats ( x, y, z, firstChannel + c ) = val;
  385. }
  386. feats.calcIntegral ( firstChannel + c );
  387. }
  388. }
  389. inline double computeWeight ( const int &d, const int &dim )
  390. {
  391. if (d == 0)
  392. return 0.0;
  393. else
  394. return 1.0 / ( pow ( 2, ( double ) ( dim - d + 1 ) ) );
  395. }
  396. void SemSegContextTree3D::train ( const MultiDataset *md )
  397. {
  398. const LabeledSet *trainp = ( *md ) ["train"];
  399. if ( saveLoadData )
  400. {
  401. if ( FileMgt::fileExists ( fileLocation ) )
  402. read ( fileLocation );
  403. else
  404. {
  405. train ( trainp );
  406. write ( fileLocation );
  407. }
  408. }
  409. else
  410. {
  411. train ( trainp );
  412. }
  413. }
  414. void SemSegContextTree3D::train ( const LabeledSet * trainp )
  415. {
  416. int shortsize = numeric_limits<short>::max();
  417. Timer timer;
  418. timer.start();
  419. vector<int> zsizeVec;
  420. SemSegTools::getDepthVector ( trainp, zsizeVec, run3Dseg );
  421. //FIXME: memory usage
  422. vector<MultiChannelImage3DT<double> > allfeats; // Feature Werte
  423. vector<MultiChannelImage3DT<unsigned short int> > nodeIndices; // Zuordnung Knoten/Baum für jeden Pixel
  424. vector<MultiChannelImageT<int> > labels;
  425. // für externen Klassifikator
  426. vector<SparseVector*> globalCategorFeats;
  427. vector<map<int,int> > classesPerImage;
  428. vector<vector<int> > rSize; // anzahl der pixel je region
  429. vector<int> amountRegionpI; // ANZAHL der regionen pro bild (von unsupervised segmentation)
  430. int imgCounter = 0;
  431. int amountPixels = 0;
  432. // How many channels of non-integral type do we have?
  433. if ( imagetype == IMAGETYPE_RGB )
  434. rawChannels = 3;
  435. else
  436. rawChannels = 1;
  437. if ( useGradient )
  438. {
  439. if ( run3Dseg )
  440. rawChannels *= 4; // gx, gy, gz
  441. else
  442. rawChannels *= 3; // gx, gy
  443. }
  444. if ( useAdditionalLayer ) // beliebige Merkmale in extra Bilddateien
  445. rawChannels += numAdditionalLayer;
  446. ///////////////////////////// read input data /////////////////////////////////
  447. ///////////////////////////////////////////////////////////////////////////////
  448. int depthCount = 0;
  449. vector< string > filelist;
  450. NICE::MultiChannelImageT<int> pixelLabels;
  451. std::map<int, bool> labelExist;
  452. for (LabeledSet::const_iterator it = trainp->begin(); it != trainp->end(); it++)
  453. {
  454. for (std::vector<ImageInfo *>::const_iterator jt = it->second.begin();
  455. jt != it->second.end(); jt++)
  456. {
  457. int classno = it->first;
  458. ImageInfo & info = *(*jt);
  459. std::string file = info.img();
  460. filelist.push_back ( file );
  461. depthCount++;
  462. const LocalizationResult *locResult = info.localization();
  463. // getting groundtruth
  464. NICE::ImageT<int> pL;
  465. pL.resize ( locResult->xsize, locResult->ysize );
  466. pL.set ( 0 );
  467. locResult->calcLabeledImage ( pL, ( *classNames ).getBackgroundClass() );
  468. pixelLabels.addChannel ( pL );
  469. if ( locResult->size() <= 0 )
  470. {
  471. fprintf ( stderr, "WARNING: NO ground truth polygons found for %s !\n",
  472. file.c_str() );
  473. continue;
  474. }
  475. fprintf ( stderr, "SSContext: Collecting pixel examples from localization info: %s\n", file.c_str() );
  476. int depthBoundary = 0;
  477. if ( run3Dseg )
  478. {
  479. depthBoundary = zsizeVec[imgCounter];
  480. }
  481. if ( depthCount < depthBoundary ) continue;
  482. // all image slices collected -> make a 3d image
  483. NICE::MultiChannelImage3DT<double> imgData;
  484. make3DImage ( filelist, imgData );
  485. int xsize = imgData.width();
  486. int ysize = imgData.height();
  487. int zsize = imgData.depth();
  488. amountPixels += xsize * ysize * zsize;
  489. MultiChannelImageT<int> tmpMat ( xsize, ysize, ( uint ) zsize );
  490. labels.push_back ( tmpMat );
  491. nodeIndices.push_back ( MultiChannelImage3DT<unsigned short int> ( xsize, ysize, zsize, nbTrees ) );
  492. nodeIndices[imgCounter].setAll ( 0 );
  493. int amountRegions;
  494. // convert color to L*a*b, add selected feature channels
  495. addFeatureMaps ( imgData, filelist, amountRegions );
  496. allfeats.push_back(imgData);
  497. if ( useFeat1 )
  498. {
  499. amountRegionpI.push_back ( amountRegions );
  500. rSize.push_back ( vector<int> ( amountRegions, 0 ) );
  501. }
  502. if ( useCategorization )
  503. {
  504. globalCategorFeats.push_back ( new SparseVector() );
  505. classesPerImage.push_back ( map<int,int>() );
  506. }
  507. for ( int x = 0; x < xsize; x++ )
  508. for ( int y = 0; y < ysize; y++ )
  509. for ( int z = 0; z < zsize; z++ )
  510. {
  511. if ( useFeat1 )
  512. rSize[imgCounter][allfeats[imgCounter] ( x, y, z, rawChannels ) ]++;
  513. if ( run3Dseg )
  514. classno = pixelLabels ( x, y, ( uint ) z );
  515. else
  516. classno = pL.getPixelQuick ( x,y );
  517. labels[imgCounter].set ( x, y, classno, ( uint ) z );
  518. if ( forbidden_classes.find ( classno ) != forbidden_classes.end() )
  519. continue;
  520. labelExist[classno] = true;
  521. if ( useCategorization )
  522. classesPerImage[imgCounter][classno] = 1;
  523. }
  524. filelist.clear();
  525. pixelLabels.reInit ( 0,0,0 );
  526. depthCount = 0;
  527. imgCounter++;
  528. }
  529. }
  530. int classes = 0;
  531. for ( map<int, bool>::const_iterator mapit = labelExist.begin();
  532. mapit != labelExist.end(); mapit++ )
  533. {
  534. labelmap[mapit->first] = classes;
  535. labelmapback[classes] = mapit->first;
  536. classes++;
  537. }
  538. ////////////////////////// channel type configuration /////////////////////////
  539. ///////////////////////////////////////////////////////////////////////////////
  540. unsigned char shift = 0;
  541. std::vector<int> rawChannelsIdx, numClassesIdx;
  542. int idx = 0;
  543. for ( int i = 0; i < rawChannels; i++, idx++ )
  544. rawChannelsIdx.push_back ( idx );
  545. for ( int i = 0; i < classes; i++, idx++ )
  546. numClassesIdx.push_back ( idx );
  547. /** Type 0: single pixel & pixel-comparison features on gray value channels */
  548. // actual values derived from integral values
  549. channelsPerType.push_back ( rawChannelsIdx );
  550. /** Type 1: region channel with unsupervised segmentation */
  551. if ( useFeat1 )
  552. {
  553. channelsPerType.push_back ( vector<int>(1, rawChannels) );
  554. shift = 1;
  555. }
  556. else
  557. channelsPerType.push_back ( vector<int>() );
  558. /** Type 2: rectangular and Haar-like features on gray value integral channels */
  559. if ( useFeat2 )
  560. channelsPerType.push_back ( rawChannelsIdx );
  561. else
  562. channelsPerType.push_back ( vector<int>() );
  563. /** Type 3: type 2 features on integral probability channels (context) */
  564. if ( useFeat3 )
  565. channelsPerType.push_back ( numClassesIdx );
  566. else
  567. channelsPerType.push_back ( vector<int>() );
  568. /** Type 4: type 0 features on probability channels (context) */
  569. // Type 4 channels are now INTEGRAL
  570. // This remains for compatibility reasons.
  571. if ( useFeat4 )
  572. channelsPerType.push_back ( numClassesIdx );
  573. else
  574. channelsPerType.push_back ( vector<int>() );
  575. ///////////////////////////////////////////////////////////////////////////////
  576. ///////////////////////////////////////////////////////////////////////////////
  577. vector<vector<vector<double> > > regionProbs;
  578. if ( useFeat1 )
  579. {
  580. for ( int i = 0; i < imgCounter; i++ )
  581. {
  582. regionProbs.push_back ( vector<vector<double> > ( amountRegionpI[i], vector<double> ( classes, 0.0 ) ) );
  583. }
  584. }
  585. //balancing
  586. a = vector<double> ( classes, 0.0 );
  587. int selectionCounter = 0;
  588. for ( int iCounter = 0; iCounter < imgCounter; iCounter++ )
  589. {
  590. int xsize = ( int ) nodeIndices[iCounter].width();
  591. int ysize = ( int ) nodeIndices[iCounter].height();
  592. int zsize = ( int ) nodeIndices[iCounter].depth();
  593. for ( int x = 0; x < xsize; x++ )
  594. for ( int y = 0; y < ysize; y++ )
  595. for ( int z = 0; z < zsize; z++ )
  596. {
  597. int cn = labels[iCounter] ( x, y, ( uint ) z );
  598. if ( labelmap.find ( cn ) == labelmap.end() )
  599. continue;
  600. a[labelmap[cn]] ++;
  601. selectionCounter++;
  602. }
  603. }
  604. for ( int i = 0; i < ( int ) a.size(); i++ )
  605. a[i] /= ( double ) selectionCounter;
  606. #ifdef VERBOSE
  607. cout << "\nDistribution:" << endl;
  608. for ( int i = 0; i < ( int ) a.size(); i++ )
  609. cout << "class '" << classNames->code(labelmapback[i]) << "': "
  610. << a[i] << endl;
  611. #endif
  612. depth = 0;
  613. uniquenumber = 0;
  614. //initialize random forest
  615. for ( int t = 0; t < nbTrees; t++ )
  616. {
  617. vector<TreeNode> singletree;
  618. singletree.push_back ( TreeNode() );
  619. singletree[0].dist = vector<double> ( classes, 0.0 );
  620. singletree[0].depth = depth;
  621. singletree[0].featcounter = amountPixels;
  622. singletree[0].nodeNumber = uniquenumber;
  623. uniquenumber++;
  624. forest.push_back ( singletree );
  625. }
  626. vector<int> startnode ( nbTrees, 0 );
  627. bool noNewSplit = false;
  628. timer.stop();
  629. cout << "\nTime for Pre-Processing: " << timer.getLastAbsolute() << " seconds\n" << endl;
  630. //////////////////////////// train the classifier ///////////////////////////
  631. /////////////////////////////////////////////////////////////////////////////
  632. timer.start();
  633. while ( !noNewSplit && (depth < maxDepth) )
  634. {
  635. depth++;
  636. #ifdef DEBUG
  637. cout << "depth: " << depth << endl;
  638. #endif
  639. noNewSplit = true;
  640. vector<MultiChannelImage3DT<unsigned short int> > lastNodeIndices = nodeIndices;
  641. vector<vector<vector<double> > > lastRegionProbs = regionProbs;
  642. if ( useFeat1 )
  643. for ( int i = 0; i < imgCounter; i++ )
  644. {
  645. int numRegions = (int) regionProbs[i].size();
  646. for ( int r = 0; r < numRegions; r++ )
  647. for ( int c = 0; c < classes; c++ )
  648. regionProbs[i][r][c] = 0.0;
  649. }
  650. // initialize & update context channels
  651. for ( int i = 0; i < imgCounter; i++)
  652. if ( useFeat3 || useFeat4 )
  653. this->updateProbabilityMaps ( nodeIndices[i], allfeats[i], rawChannels + shift );
  654. #ifdef VERBOSE
  655. Timer timerDepth;
  656. timerDepth.start();
  657. #endif
  658. double weight = computeWeight ( depth, maxDepth )
  659. - computeWeight ( depth - 1, maxDepth );
  660. #pragma omp parallel for
  661. // for each tree
  662. for ( int tree = 0; tree < nbTrees; tree++ )
  663. {
  664. const int t = ( int ) forest[tree].size();
  665. const int s = startnode[tree];
  666. startnode[tree] = t;
  667. double bestig;
  668. // for each node
  669. for ( int node = s; node < t; node++ )
  670. {
  671. if ( !forest[tree][node].isleaf && forest[tree][node].left < 0 )
  672. {
  673. // find best split
  674. Operation3D *splitfeat = NULL;
  675. double splitval;
  676. bestig = getBestSplit ( allfeats, lastNodeIndices, labels, node,
  677. splitfeat, splitval, tree, lastRegionProbs );
  678. forest[tree][node].feat = splitfeat;
  679. forest[tree][node].decision = splitval;
  680. // split the node
  681. if ( splitfeat != NULL )
  682. {
  683. noNewSplit = false;
  684. int left;
  685. #pragma omp critical
  686. {
  687. left = forest[tree].size();
  688. forest[tree].push_back ( TreeNode() );
  689. forest[tree].push_back ( TreeNode() );
  690. }
  691. int right = left + 1;
  692. forest[tree][node].left = left;
  693. forest[tree][node].right = right;
  694. forest[tree][left].init( depth, classes, uniquenumber);
  695. int leftu = uniquenumber;
  696. uniquenumber++;
  697. forest[tree][right].init( depth, classes, uniquenumber);
  698. int rightu = uniquenumber;
  699. uniquenumber++;
  700. #pragma omp parallel for
  701. for ( int i = 0; i < imgCounter; i++ )
  702. {
  703. int xsize = nodeIndices[i].width();
  704. int ysize = nodeIndices[i].height();
  705. int zsize = nodeIndices[i].depth();
  706. for ( int x = 0; x < xsize; x++ )
  707. {
  708. for ( int y = 0; y < ysize; y++ )
  709. {
  710. for ( int z = 0; z < zsize; z++ )
  711. {
  712. if ( nodeIndices[i].get ( x, y, z, tree ) == node )
  713. {
  714. // get feature value
  715. Features feat;
  716. feat.feats = &allfeats[i];
  717. feat.rProbs = &lastRegionProbs[i];
  718. double val = 0.0;
  719. val = splitfeat->getVal ( feat, x, y, z );
  720. if ( !isfinite ( val ) ) val = 0.0;
  721. #pragma omp critical
  722. {
  723. int curLabel = labels[i] ( x, y, ( uint ) z );
  724. // traverse to left child
  725. if ( val < splitval )
  726. {
  727. nodeIndices[i].set ( x, y, z, left, tree );
  728. if ( labelmap.find ( curLabel ) != labelmap.end() )
  729. forest[tree][left].dist[labelmap[curLabel]]++;
  730. forest[tree][left].featcounter++;
  731. if ( useCategorization && leftu < shortsize )
  732. ( *globalCategorFeats[i] ) [leftu]+=weight;
  733. }
  734. // traverse to right child
  735. else
  736. {
  737. nodeIndices[i].set ( x, y, z, right, tree );
  738. if ( labelmap.find ( curLabel ) != labelmap.end() )
  739. forest[tree][right].dist[labelmap[curLabel]]++;
  740. forest[tree][right].featcounter++;
  741. if ( useCategorization && rightu < shortsize )
  742. ( *globalCategorFeats[i] ) [rightu]+=weight;
  743. }
  744. }
  745. }
  746. }
  747. }
  748. }
  749. }
  750. // normalize distributions in child leaves
  751. double lcounter = 0.0, rcounter = 0.0;
  752. for ( int c = 0; c < (int)forest[tree][left].dist.size(); c++ )
  753. {
  754. if ( forbidden_classes.find ( labelmapback[c] ) != forbidden_classes.end() )
  755. {
  756. forest[tree][left].dist[c] = 0;
  757. forest[tree][right].dist[c] = 0;
  758. }
  759. else
  760. {
  761. forest[tree][left].dist[c] /= a[c];
  762. lcounter += forest[tree][left].dist[c];
  763. forest[tree][right].dist[c] /= a[c];
  764. rcounter += forest[tree][right].dist[c];
  765. }
  766. }
  767. assert ( lcounter > 0 && rcounter > 0 );
  768. for ( int c = 0; c < classes; c++ )
  769. {
  770. forest[tree][left].dist[c] /= lcounter;
  771. forest[tree][right].dist[c] /= rcounter;
  772. }
  773. }
  774. else
  775. {
  776. forest[tree][node].isleaf = true;
  777. }
  778. }
  779. }
  780. }
  781. if ( useFeat1 )
  782. {
  783. for ( int i = 0; i < imgCounter; i++ )
  784. {
  785. int xsize = nodeIndices[i].width();
  786. int ysize = nodeIndices[i].height();
  787. int zsize = nodeIndices[i].depth();
  788. #pragma omp parallel for
  789. // set region probability distribution
  790. for ( int x = 0; x < xsize; x++ )
  791. {
  792. for ( int y = 0; y < ysize; y++ )
  793. {
  794. for ( int z = 0; z < zsize; z++ )
  795. {
  796. for ( int tree = 0; tree < nbTrees; tree++ )
  797. {
  798. int node = nodeIndices[i].get ( x, y, z, tree );
  799. for ( int c = 0; c < classes; c++ )
  800. {
  801. int r = (int) ( allfeats[i] ( x, y, z, rawChannels ) );
  802. regionProbs[i][r][c] += forest[tree][node].dist[c];
  803. }
  804. }
  805. }
  806. }
  807. }
  808. // normalize distribution
  809. int numRegions = (int) regionProbs[i].size();
  810. for ( int r = 0; r < numRegions; r++ )
  811. {
  812. for ( int c = 0; c < classes; c++ )
  813. {
  814. regionProbs[i][r][c] /= ( double ) ( rSize[i][r] );
  815. }
  816. }
  817. }
  818. }
  819. if ( firstiteration ) firstiteration = false;
  820. #ifdef VERBOSE
  821. timerDepth.stop();
  822. cout << "Depth " << depth << ": " << timerDepth.getLastAbsolute() << " seconds" <<endl;
  823. #endif
  824. lastNodeIndices.clear();
  825. lastRegionProbs.clear();
  826. }
  827. timer.stop();
  828. cout << "Time for Learning: " << timer.getLastAbsolute() << " seconds\n" << endl;
  829. //////////////////////// classification using HIK ///////////////////////////
  830. /////////////////////////////////////////////////////////////////////////////
  831. if ( useCategorization && fasthik != NULL )
  832. {
  833. timer.start();
  834. uniquenumber = std::min ( shortsize, uniquenumber );
  835. for ( uint i = 0; i < globalCategorFeats.size(); i++ )
  836. {
  837. globalCategorFeats[i]->setDim ( uniquenumber );
  838. globalCategorFeats[i]->normalize();
  839. }
  840. std::map< uint, NICE::Vector > ys;
  841. uint cCounter = 0;
  842. for ( std::map<int,int>::const_iterator it = labelmap.begin();
  843. it != labelmap.end(); it++, cCounter++ )
  844. {
  845. ys[cCounter] = NICE::Vector ( globalCategorFeats.size() );
  846. for ( int i = 0; i < imgCounter; i++ )
  847. {
  848. if ( classesPerImage[i].find ( it->first ) != classesPerImage[i].end() )
  849. {
  850. ys[cCounter][i] = 1;
  851. }
  852. else
  853. {
  854. ys[cCounter][i] = -1;
  855. }
  856. }
  857. }
  858. fasthik->train( reinterpret_cast<vector<const NICE::SparseVector *>&>(globalCategorFeats), ys);
  859. timer.stop();
  860. cerr << "Time for Categorization: " << timer.getLastAbsolute() << " seconds\n" << endl;
  861. }
  862. #ifdef VERBOSE
  863. cout << "\nFEATURE USAGE" << endl;
  864. cout << "#############\n" << endl;
  865. // amount of used features per feature type
  866. std::map<int, int> featTypeCounter;
  867. for ( int tree = 0; tree < nbTrees; tree++ )
  868. {
  869. int t = ( int ) forest[tree].size();
  870. for ( int node = 0; node < t; node++ )
  871. {
  872. if ( !forest[tree][node].isleaf && forest[tree][node].left != -1 )
  873. {
  874. featTypeCounter[ forest[tree][node].feat->getFeatType() ] += 1;
  875. }
  876. }
  877. }
  878. cout << "Types:" << endl;
  879. for ( map<int, int>::const_iterator it = featTypeCounter.begin(); it != featTypeCounter.end(); it++ )
  880. cout << it->first << ": " << it->second << endl;
  881. cout << "\nOperations - All:" << endl;
  882. // used operations
  883. vector<int> opOverview ( NBOPERATIONS, 0 );
  884. // relative use of context vs raw features per tree level
  885. vector<vector<double> > contextOverview ( maxDepth, vector<double> ( 2, 0.0 ) );
  886. for ( int tree = 0; tree < nbTrees; tree++ )
  887. {
  888. int t = ( int ) forest[tree].size();
  889. for ( int node = 0; node < t; node++ )
  890. {
  891. #ifdef DEBUG
  892. printf ( "tree[%i]: left: %i, right: %i", node, forest[tree][node].left, forest[tree][node].right );
  893. #endif
  894. if ( !forest[tree][node].isleaf && forest[tree][node].left != -1 )
  895. {
  896. #ifdef DEBUG
  897. cout << forest[tree][node].feat->writeInfos() << endl;
  898. #endif
  899. opOverview[ forest[tree][node].feat->getOps() ]++;
  900. contextOverview[forest[tree][node].depth][ ( int ) forest[tree][node].feat->getContext() ]++;
  901. }
  902. #ifdef DEBUG
  903. for ( int d = 0; d < ( int ) forest[tree][node].dist.size(); d++ )
  904. cout << " " << forest[tree][node].dist[d];
  905. cout << endl;
  906. #endif
  907. }
  908. }
  909. // amount of used features per operation type
  910. cout << "\nOperations - Summary:" << endl;
  911. for ( int t = 0; t < ( int ) opOverview.size(); t++ )
  912. {
  913. cout << "Ops " << t << ": " << opOverview[ t ] << endl;
  914. }
  915. // ratio of used context features per depth level
  916. cout << "\nContext-Ratio:" << endl;
  917. for ( int d = 0; d < maxDepth; d++ )
  918. {
  919. double sum = contextOverview[d][0] + contextOverview[d][1];
  920. if ( sum == 0 )
  921. sum = 1;
  922. contextOverview[d][0] /= sum;
  923. contextOverview[d][1] /= sum;
  924. cout << "Depth [" << d+1 << "] Normal: " << contextOverview[d][0] << " Context: " << contextOverview[d][1] << endl;
  925. }
  926. #endif
  927. }
  928. void SemSegContextTree3D::addFeatureMaps (
  929. NICE::MultiChannelImage3DT<double> &imgData,
  930. const vector<string> &filelist,
  931. int &amountRegions )
  932. {
  933. int xsize = imgData.width();
  934. int ysize = imgData.height();
  935. int zsize = imgData.depth();
  936. amountRegions = 0;
  937. // RGB to Lab
  938. if ( imagetype == IMAGETYPE_RGB )
  939. {
  940. for ( int z = 0; z < zsize; z++ )
  941. for ( int y = 0; y < ysize; y++ )
  942. for ( int x = 0; x < xsize; x++ )
  943. {
  944. double R, G, B, X, Y, Z, L, a, b;
  945. R = ( double )imgData.get( x, y, z, 0 ) / 255.0;
  946. G = ( double )imgData.get( x, y, z, 1 ) / 255.0;
  947. B = ( double )imgData.get( x, y, z, 2 ) / 255.0;
  948. if ( useAltTristimulus )
  949. {
  950. ColorConversion::ccRGBtoXYZ( R, G, B, &X, &Y, &Z, 4 );
  951. ColorConversion::ccXYZtoCIE_Lab( X, Y, Z, &L, &a, &b, 4 );
  952. }
  953. else
  954. {
  955. ColorConversion::ccRGBtoXYZ( R, G, B, &X, &Y, &Z, 0 );
  956. ColorConversion::ccXYZtoCIE_Lab( X, Y, Z, &L, &a, &b, 0 );
  957. }
  958. imgData.set( x, y, z, L, 0 );
  959. imgData.set( x, y, z, a, 1 );
  960. imgData.set( x, y, z, b, 2 );
  961. }
  962. }
  963. else
  964. // normalize gray values to [0,1]
  965. {
  966. for ( int z = 0; z < zsize; z++ )
  967. for ( int y = 0; y < ysize; y++ )
  968. for ( int x = 0; x < xsize; x++ )
  969. {
  970. double val = imgData.get( x, y, z, 0 ) / 255.0;
  971. imgData.set( x, y, z, val, 0 );
  972. }
  973. }
  974. // Gradient layers
  975. if ( useGradient )
  976. {
  977. int currentsize = imgData.channels();
  978. imgData.addChannel ( 2*currentsize );
  979. // gradients for X and Y
  980. for ( int z = 0; z < zsize; z++ )
  981. for ( int c = 0; c < currentsize; c++ )
  982. {
  983. ImageT<double> tmp = imgData.getChannelT(z, c);
  984. ImageT<double> sobX( xsize, ysize );
  985. ImageT<double> sobY( xsize, ysize );
  986. NICE::FilterT<double, double, double>::sobelX ( tmp, sobX );
  987. NICE::FilterT<double, double, double>::sobelY ( tmp, sobY );
  988. for ( int y = 0; y < ysize; y++ )
  989. for ( int x = 0; x < xsize; x++ )
  990. {
  991. imgData.set( x, y, z, sobX.getPixelQuick(x,y), c+currentsize );
  992. imgData.set( x, y, z, sobY.getPixelQuick(x,y), c+(currentsize*2) );
  993. }
  994. }
  995. // gradients for Z
  996. if ( run3Dseg )
  997. {
  998. imgData.addChannel ( currentsize );
  999. for ( int x = 0; x < xsize; x++ )
  1000. for ( int c = 0; c < currentsize; c++ )
  1001. {
  1002. ImageT<double> tmp = imgData.getXSlice(x, c);
  1003. ImageT<double> sobZ( zsize, ysize );
  1004. NICE::FilterT<double, double, double>::sobelX ( tmp, sobZ );
  1005. for ( int y = 0; y < ysize; y++ )
  1006. for ( int z = 0; z < zsize; z++ )
  1007. imgData.set( x, y, z, sobZ.getPixelQuick(z,y), c+(currentsize*3) );
  1008. }
  1009. }
  1010. }
  1011. // arbitrary amount of additional layers as feature maps
  1012. if ( useAdditionalLayer )
  1013. {
  1014. for ( int a = 0; a < numAdditionalLayer; a++ )
  1015. {
  1016. ostringstream convert;
  1017. convert << a;
  1018. #ifdef DEBUG
  1019. cout << "Using additional layer #" << a << endl;
  1020. #endif
  1021. int currentsize = imgData.channels();
  1022. imgData.addChannel ( 1 );
  1023. for ( int z = 0; z < zsize; z++ )
  1024. {
  1025. vector<string> list;
  1026. StringTools::split ( filelist[z], '/', list );
  1027. string layerPath = StringTools::trim ( filelist[z], list.back() )
  1028. + "addlayer" + convert.str() + "/" + list.back();
  1029. NICE::Image layer ( layerPath );
  1030. for ( int y = 0; y < ysize; y++ )
  1031. for ( int x = 0; x < xsize; x++ )
  1032. imgData.set(x, y, z, layer.getPixelQuick(x,y), currentsize);
  1033. }
  1034. }
  1035. }
  1036. // region feature (unsupervised segmentation)
  1037. int shift = 0;
  1038. if ( useFeat1 )
  1039. {
  1040. shift = 1;
  1041. MultiChannelImageT<int> regions;
  1042. regions.reInit( xsize, ysize, zsize );
  1043. amountRegions = segmentation->segRegions ( imgData, regions, imagetype );
  1044. int currentsize = imgData.channels();
  1045. imgData.addChannel ( 1 );
  1046. for ( int z = 0; z < ( int ) regions.channels(); z++ )
  1047. for ( int y = 0; y < regions.height(); y++ )
  1048. for ( int x = 0; x < regions.width(); x++ )
  1049. imgData.set ( x, y, z, regions ( x, y, ( uint ) z ), currentsize );
  1050. }
  1051. // convert raw channels to intergal channels
  1052. #pragma omp parallel for
  1053. for ( int i = 0; i < rawChannels; i++ )
  1054. imgData.calcIntegral ( i );
  1055. int classes = classNames->numClasses() - forbidden_classes.size();
  1056. if ( useFeat3 || useFeat4 )
  1057. imgData.addChannel ( classes );
  1058. }
  1059. void SemSegContextTree3D::classify (
  1060. const std::vector<std::string> & filelist,
  1061. NICE::MultiChannelImageT<int> & segresult,
  1062. NICE::MultiChannelImage3DT<double> & probabilities )
  1063. {
  1064. ///////////////////////// build MCI3DT from files ///////////////////////////
  1065. /////////////////////////////////////////////////////////////////////////////
  1066. NICE::MultiChannelImage3DT<double> imgData;
  1067. this->make3DImage( filelist, imgData );
  1068. int xsize = imgData.width();
  1069. int ysize = imgData.height();
  1070. int zsize = imgData.depth();
  1071. ////////////////////////// initialize variables /////////////////////////////
  1072. /////////////////////////////////////////////////////////////////////////////
  1073. firstiteration = true;
  1074. depth = 0;
  1075. // anytime classification ability
  1076. int classificationDepth = conf->gI( "SSContextTree", "classification_depth", maxDepth );
  1077. if (classificationDepth > maxDepth || classificationDepth < 1 )
  1078. classificationDepth = maxDepth;
  1079. Timer timer;
  1080. timer.start();
  1081. // classes occurred during training step
  1082. int classes = labelmapback.size();
  1083. // classes defined in config file
  1084. int numClasses = classNames->numClasses();
  1085. // class probabilities by pixel
  1086. probabilities.reInit ( xsize, ysize, zsize, numClasses );
  1087. probabilities.setAll ( 0 );
  1088. // class probabilities by region
  1089. vector<vector<double> > regionProbs;
  1090. // affiliation: pixel <-> (tree,node)
  1091. MultiChannelImage3DT<unsigned short int> nodeIndices ( xsize, ysize, zsize, nbTrees );
  1092. nodeIndices.setAll ( 0 );
  1093. // for categorization
  1094. SparseVector *globalCategorFeat;
  1095. globalCategorFeat = new SparseVector();
  1096. /////////////////////////// get feature values //////////////////////////////
  1097. /////////////////////////////////////////////////////////////////////////////
  1098. // Basic Features
  1099. int amountRegions;
  1100. addFeatureMaps ( imgData, filelist, amountRegions );
  1101. vector<int> rSize;
  1102. int shift = 0;
  1103. if ( useFeat1 )
  1104. {
  1105. shift = 1;
  1106. regionProbs = vector<vector<double> > ( amountRegions, vector<double> ( classes, 0.0 ) );
  1107. rSize = vector<int> ( amountRegions, 0 );
  1108. for ( int z = 0; z < zsize; z++ )
  1109. {
  1110. for ( int y = 0; y < ysize; y++ )
  1111. {
  1112. for ( int x = 0; x < xsize; x++ )
  1113. {
  1114. rSize[imgData ( x, y, z, rawChannels ) ]++;
  1115. }
  1116. }
  1117. }
  1118. }
  1119. ////////////////// traverse image example through trees /////////////////////
  1120. /////////////////////////////////////////////////////////////////////////////
  1121. bool noNewSplit = false;
  1122. for ( int d = 0; d < classificationDepth && !noNewSplit; d++ )
  1123. {
  1124. depth++;
  1125. vector<vector<double> > lastRegionProbs = regionProbs;
  1126. if ( useFeat1 )
  1127. {
  1128. int numRegions = ( int ) regionProbs.size();
  1129. for ( int r = 0; r < numRegions; r++ )
  1130. for ( int c = 0; c < classes; c++ )
  1131. regionProbs[r][c] = 0.0;
  1132. }
  1133. if ( depth < classificationDepth )
  1134. {
  1135. int firstChannel = rawChannels + shift;
  1136. if ( useFeat3 || useFeat4 )
  1137. this->updateProbabilityMaps ( nodeIndices, imgData, firstChannel );
  1138. }
  1139. double weight = computeWeight ( depth, maxDepth )
  1140. - computeWeight ( depth - 1, maxDepth );
  1141. noNewSplit = true;
  1142. int tree;
  1143. #pragma omp parallel for private(tree)
  1144. for ( tree = 0; tree < nbTrees; tree++ )
  1145. for ( int x = 0; x < xsize; x=x+labelIncrement )
  1146. for ( int y = 0; y < ysize; y=y+labelIncrement )
  1147. for ( int z = 0; z < zsize; z++ )
  1148. {
  1149. int node = nodeIndices.get ( x, y, z, tree );
  1150. if ( forest[tree][node].left > 0 )
  1151. {
  1152. noNewSplit = false;
  1153. Features feat;
  1154. feat.feats = &imgData;
  1155. feat.rProbs = &lastRegionProbs;
  1156. double val = forest[tree][node].feat->getVal ( feat, x, y, z );
  1157. if ( !isfinite ( val ) ) val = 0.0;
  1158. // traverse to left child
  1159. if ( val < forest[tree][node].decision )
  1160. {
  1161. int left = forest[tree][node].left;
  1162. for ( int n = 0; n < labelIncrement; n++ )
  1163. for ( int m = 0; m < labelIncrement; m++ )
  1164. if (x+m < xsize && y+n < ysize)
  1165. nodeIndices.set ( x+m, y+n, z, left, tree );
  1166. #pragma omp critical
  1167. {
  1168. if ( fasthik != NULL
  1169. && useCategorization
  1170. && forest[tree][left].nodeNumber < uniquenumber )
  1171. ( *globalCategorFeat ) [forest[tree][left].nodeNumber] += weight;
  1172. }
  1173. }
  1174. // traverse to right child
  1175. else
  1176. {
  1177. int right = forest[tree][node].right;
  1178. for ( int n = 0; n < labelIncrement; n++ )
  1179. for ( int m = 0; m < labelIncrement; m++ )
  1180. if (x+m < xsize && y+n < ysize)
  1181. nodeIndices.set ( x+m, y+n, z, right, tree );
  1182. #pragma omp critical
  1183. {
  1184. if ( fasthik != NULL
  1185. && useCategorization
  1186. && forest[tree][right].nodeNumber < uniquenumber )
  1187. ( *globalCategorFeat ) [forest[tree][right].nodeNumber] += weight;
  1188. }
  1189. }
  1190. }
  1191. }
  1192. if ( useFeat1 )
  1193. {
  1194. int xsize = nodeIndices.width();
  1195. int ysize = nodeIndices.height();
  1196. int zsize = nodeIndices.depth();
  1197. #pragma omp parallel for
  1198. for ( int x = 0; x < xsize; x++ )
  1199. for ( int y = 0; y < ysize; y++ )
  1200. for ( int z = 0; z < zsize; z++ )
  1201. for ( int tree = 0; tree < nbTrees; tree++ )
  1202. {
  1203. int node = nodeIndices.get ( x, y, z, tree );
  1204. for ( uint c = 0; c < forest[tree][node].dist.size(); c++ )
  1205. {
  1206. int r = (int) imgData ( x, y, z, rawChannels );
  1207. regionProbs[r][c] += forest[tree][node].dist[c];
  1208. }
  1209. }
  1210. int numRegions = (int) regionProbs.size();
  1211. for ( int r = 0; r < numRegions; r++ )
  1212. for ( int c = 0; c < (int) classes; c++ )
  1213. regionProbs[r][c] /= ( double ) ( rSize[r] );
  1214. }
  1215. if ( (depth < classificationDepth) && firstiteration ) firstiteration = false;
  1216. }
  1217. vector<int> classesInImg;
  1218. if ( useCategorization )
  1219. {
  1220. if ( cndir != "" )
  1221. {
  1222. for ( int z = 0; z < zsize; z++ )
  1223. {
  1224. vector< string > list;
  1225. StringTools::split ( filelist[z], '/', list );
  1226. string orgname = list.back();
  1227. ifstream infile ( ( cndir + "/" + orgname + ".dat" ).c_str() );
  1228. while ( !infile.eof() && infile.good() )
  1229. {
  1230. int tmp;
  1231. infile >> tmp;
  1232. assert ( tmp >= 0 && tmp < numClasses );
  1233. classesInImg.push_back ( tmp );
  1234. }
  1235. }
  1236. }
  1237. else
  1238. {
  1239. globalCategorFeat->setDim ( uniquenumber );
  1240. globalCategorFeat->normalize();
  1241. ClassificationResult cr = fasthik->classify( globalCategorFeat);
  1242. for ( uint i = 0; i < ( uint ) classes; i++ )
  1243. {
  1244. cerr << cr.scores[i] << " ";
  1245. if ( cr.scores[i] > 0.0/*-0.3*/ )
  1246. {
  1247. classesInImg.push_back ( i );
  1248. }
  1249. }
  1250. }
  1251. cerr << "amount of classes: " << classes << " used classes: " << classesInImg.size() << endl;
  1252. }
  1253. if ( classesInImg.size() == 0 )
  1254. {
  1255. for ( uint i = 0; i < ( uint ) classes; i++ )
  1256. {
  1257. classesInImg.push_back ( i );
  1258. }
  1259. }
  1260. // final labeling step
  1261. if ( pixelWiseLabeling )
  1262. {
  1263. for ( int x = 0; x < xsize; x++ )
  1264. for ( int y = 0; y < ysize; y++ )
  1265. for ( int z = 0; z < zsize; z++ )
  1266. {
  1267. double maxProb = - numeric_limits<double>::max();
  1268. int maxClass = 0;
  1269. for ( uint c = 0; c < classesInImg.size(); c++ )
  1270. {
  1271. int i = classesInImg[c];
  1272. double curProb = getMeanProb ( x, y, z, i, nodeIndices );
  1273. probabilities.set ( x, y, z, curProb, labelmapback[i] );
  1274. if ( curProb > maxProb )
  1275. {
  1276. maxProb = curProb;
  1277. maxClass = labelmapback[i];
  1278. }
  1279. }
  1280. assert(maxProb <= 1);
  1281. // copy pixel labeling into segresults (output)
  1282. segresult.set ( x, y, maxClass, ( uint ) z );
  1283. }
  1284. #ifdef VISUALIZE
  1285. saveProbabilityMapAsImage( probabilities );
  1286. #endif
  1287. }
  1288. else
  1289. {
  1290. // labeling by region
  1291. NICE::MultiChannelImageT<int> regions;
  1292. int xsize = imgData.width();
  1293. int ysize = imgData.height();
  1294. int zsize = imgData.depth();
  1295. regions.reInit ( xsize, ysize, zsize );
  1296. if ( useFeat1 )
  1297. {
  1298. for ( int z = 0; z < zsize; z++ )
  1299. for ( int y = 0; y < ysize; y++ )
  1300. for ( int x = 0; x < xsize; x++ )
  1301. regions.set ( x, y, imgData ( x, y, z, rawChannels ), ( uint ) z );
  1302. }
  1303. else
  1304. {
  1305. amountRegions = segmentation->segRegions ( imgData, regions, imagetype );
  1306. #ifdef DEBUG
  1307. for ( unsigned int z = 0; z < ( uint ) zsize; z++ )
  1308. {
  1309. NICE::Matrix regmask;
  1310. NICE::ColorImage colorimg ( xsize, ysize );
  1311. NICE::ColorImage marked ( xsize, ysize );
  1312. regmask.resize ( xsize, ysize );
  1313. for ( int y = 0; y < ysize; y++ )
  1314. {
  1315. for ( int x = 0; x < xsize; x++ )
  1316. {
  1317. regmask ( x,y ) = regions ( x,y,z );
  1318. colorimg.setPixelQuick ( x, y, 0, imgData.get ( x,y,z,0 ) );
  1319. colorimg.setPixelQuick ( x, y, 1, imgData.get ( x,y,z,0 ) );
  1320. colorimg.setPixelQuick ( x, y, 2, imgData.get ( x,y,z,0 ) );
  1321. }
  1322. }
  1323. vector<int> colorvals;
  1324. colorvals.push_back ( 255 );
  1325. colorvals.push_back ( 0 );
  1326. colorvals.push_back ( 0 );
  1327. segmentation->markContours ( colorimg, regmask, colorvals, marked );
  1328. std::vector<string> list;
  1329. StringTools::split ( filelist[z], '/', list );
  1330. string savePath = StringTools::trim ( filelist[z], list.back() ) + "marked/" + list.back();
  1331. marked.write ( savePath );
  1332. }
  1333. #endif
  1334. }
  1335. regionProbs.clear();
  1336. regionProbs = vector<vector<double> > ( amountRegions, vector<double> ( classes, 0.0 ) );
  1337. vector<vector<double> > regionProbsCount ( amountRegions, vector<double> ( classes, 0.0 ) );
  1338. vector<int> bestlabels ( amountRegions, labelmapback[classesInImg[0]] );
  1339. for ( int z = 0; z < zsize; z++ )
  1340. {
  1341. for ( int y = 0; y < ysize; y++ )
  1342. {
  1343. for ( int x = 0; x < xsize; x++ )
  1344. {
  1345. int r = regions ( x, y, ( uint ) z );
  1346. for ( uint i = 0; i < classesInImg.size(); i++ )
  1347. {
  1348. int c = classesInImg[i];
  1349. // get mean voting of all trees
  1350. regionProbs[r][c] += getMeanProb ( x, y, z, c, nodeIndices );
  1351. regionProbsCount[r][c]++;
  1352. }
  1353. }
  1354. }
  1355. }
  1356. for ( int r = 0; r < amountRegions; r++ )
  1357. for ( int c = 0; c < classes; c++ )
  1358. regionProbs[r][c] /= regionProbsCount[r][c];
  1359. for ( int r = 0; r < amountRegions; r++ )
  1360. {
  1361. double maxProb = regionProbs[r][classesInImg[0]];
  1362. bestlabels[r] = classesInImg[0];
  1363. for ( int c = 1; c < classes; c++ )
  1364. if ( maxProb < regionProbs[r][c] )
  1365. {
  1366. maxProb = regionProbs[r][c];
  1367. bestlabels[r] = c;
  1368. }
  1369. bestlabels[r] = labelmapback[bestlabels[r]];
  1370. }
  1371. // copy region labeling into segresults (output)
  1372. for ( int z = 0; z < zsize; z++ )
  1373. for ( int y = 0; y < ysize; y++ )
  1374. for ( int x = 0; x < xsize; x++ )
  1375. {
  1376. int r = regions ( x,y, (uint) z );
  1377. int l = bestlabels[ r ];
  1378. segresult.set ( x, y, l, (uint) z );
  1379. for ( int c = 0; c < classes; c++ )
  1380. {
  1381. double curProb = regionProbs[r][c];
  1382. probabilities.set( x, y, z, curProb, c );
  1383. }
  1384. }
  1385. #ifdef WRITEREGIONS
  1386. for ( int z = 0; z < zsize; z++ )
  1387. {
  1388. RegionGraph rg;
  1389. NICE::ColorImage img ( xsize,ysize );
  1390. if ( imagetype == IMAGETYPE_RGB )
  1391. {
  1392. img = imgData.getColor ( z );
  1393. }
  1394. else
  1395. {
  1396. NICE::Image gray = imgData.getChannel ( z );
  1397. for ( int y = 0; y < ysize; y++ )
  1398. {
  1399. for ( int x = 0; x < xsize; x++ )
  1400. {
  1401. int val = gray.getPixelQuick ( x,y );
  1402. img.setPixelQuick ( x, y, val, val, val );
  1403. }
  1404. }
  1405. }
  1406. Matrix regions_tmp ( xsize,ysize );
  1407. for ( int y = 0; y < ysize; y++ )
  1408. {
  1409. for ( int x = 0; x < xsize; x++ )
  1410. {
  1411. regions_tmp ( x,y ) = regions ( x,y, ( uint ) z );
  1412. }
  1413. }
  1414. segmentation->getGraphRepresentation ( img, regions_tmp, rg );
  1415. for ( uint pos = 0; pos < regionProbs.size(); pos++ )
  1416. {
  1417. rg[pos]->setProbs ( regionProbs[pos] );
  1418. }
  1419. std::string s;
  1420. std::stringstream out;
  1421. std::vector< std::string > list;
  1422. StringTools::split ( filelist[z], '/', list );
  1423. out << "rgout/" << list.back() << ".graph";
  1424. string writefile = out.str();
  1425. rg.write ( writefile );
  1426. }
  1427. #endif
  1428. }
  1429. timer.stop();
  1430. cout << "\nTime for Classification: " << timer.getLastAbsolute() << endl;
  1431. // CLEANING UP
  1432. // TODO: operations in "forest"
  1433. while( !ops.empty() )
  1434. {
  1435. OperationPool* op = ops.back();
  1436. op->clear();
  1437. ops.pop_back();
  1438. }
  1439. delete globalCategorFeat;
  1440. }
  1441. void SemSegContextTree3D::store ( std::ostream & os, int format ) const
  1442. {
  1443. os.precision ( numeric_limits<double>::digits10 + 1 );
  1444. os << nbTrees << endl;
  1445. classnames.store ( os );
  1446. map<int, int>::const_iterator it;
  1447. os << labelmap.size() << endl;
  1448. for ( it = labelmap.begin() ; it != labelmap.end(); it++ )
  1449. os << ( *it ).first << " " << ( *it ).second << endl;
  1450. os << labelmapback.size() << endl;
  1451. for ( it = labelmapback.begin() ; it != labelmapback.end(); it++ )
  1452. os << ( *it ).first << " " << ( *it ).second << endl;
  1453. int trees = forest.size();
  1454. os << trees << endl;
  1455. for ( int t = 0; t < trees; t++ )
  1456. {
  1457. int nodes = forest[t].size();
  1458. os << nodes << endl;
  1459. for ( int n = 0; n < nodes; n++ )
  1460. {
  1461. os << forest[t][n].left << " " << forest[t][n].right << " " << forest[t][n].decision << " " << forest[t][n].isleaf << " " << forest[t][n].depth << " " << forest[t][n].featcounter << " " << forest[t][n].nodeNumber << endl;
  1462. os << forest[t][n].dist << endl;
  1463. if ( forest[t][n].feat == NULL )
  1464. os << -1 << endl;
  1465. else
  1466. {
  1467. os << forest[t][n].feat->getOps() << endl;
  1468. forest[t][n].feat->store ( os );
  1469. }
  1470. }
  1471. }
  1472. vector<int> channelType;
  1473. if ( useFeat0 )
  1474. channelType.push_back(0);
  1475. if ( useFeat1 )
  1476. channelType.push_back(1);
  1477. if ( useFeat2 )
  1478. channelType.push_back(2);
  1479. if ( useFeat3 )
  1480. channelType.push_back(3);
  1481. if ( useFeat4 )
  1482. channelType.push_back(4);
  1483. os << channelType.size() << endl;
  1484. for ( int i = 0; i < ( int ) channelType.size(); i++ )
  1485. {
  1486. os << channelType[i] << " ";
  1487. }
  1488. os << endl;
  1489. os << rawChannels << endl;
  1490. os << uniquenumber << endl;
  1491. }
  1492. void SemSegContextTree3D::restore ( std::istream & is, int format )
  1493. {
  1494. is >> nbTrees;
  1495. classnames.restore ( is );
  1496. int lsize;
  1497. is >> lsize;
  1498. labelmap.clear();
  1499. for ( int l = 0; l < lsize; l++ )
  1500. {
  1501. int first, second;
  1502. is >> first;
  1503. is >> second;
  1504. labelmap[first] = second;
  1505. }
  1506. is >> lsize;
  1507. labelmapback.clear();
  1508. for ( int l = 0; l < lsize; l++ )
  1509. {
  1510. int first, second;
  1511. is >> first;
  1512. is >> second;
  1513. labelmapback[first] = second;
  1514. }
  1515. int trees;
  1516. is >> trees;
  1517. forest.clear();
  1518. for ( int t = 0; t < trees; t++ )
  1519. {
  1520. vector<TreeNode> tmptree;
  1521. forest.push_back ( tmptree );
  1522. int nodes;
  1523. is >> nodes;
  1524. for ( int n = 0; n < nodes; n++ )
  1525. {
  1526. TreeNode tmpnode;
  1527. forest[t].push_back ( tmpnode );
  1528. is >> forest[t][n].left;
  1529. is >> forest[t][n].right;
  1530. is >> forest[t][n].decision;
  1531. is >> forest[t][n].isleaf;
  1532. is >> forest[t][n].depth;
  1533. is >> forest[t][n].featcounter;
  1534. is >> forest[t][n].nodeNumber;
  1535. is >> forest[t][n].dist;
  1536. int feattype;
  1537. is >> feattype;
  1538. assert ( feattype < NBOPERATIONS );
  1539. forest[t][n].feat = NULL;
  1540. if ( feattype >= 0 )
  1541. {
  1542. for ( uint o = 0; o < ops.size(); o++ )
  1543. {
  1544. for ( uint o2 = 0; o2 < ops[o]->pool.size(); o2++ )
  1545. {
  1546. if ( forest[t][n].feat == NULL )
  1547. {
  1548. if ( ops[o]->pool[o2]->getOps() == feattype )
  1549. {
  1550. forest[t][n].feat = ops[o]->pool[o2]->clone();
  1551. break;
  1552. }
  1553. }
  1554. }
  1555. }
  1556. assert ( forest[t][n].feat != NULL );
  1557. forest[t][n].feat->restore ( is );
  1558. forest[t][n].feat->setWSize ( windowSize );
  1559. }
  1560. }
  1561. }
  1562. // channel type configuration
  1563. int ctsize;
  1564. is >> ctsize;
  1565. for ( int i = 0; i < ctsize; i++ )
  1566. {
  1567. int tmp;
  1568. is >> tmp;
  1569. switch (tmp)
  1570. {
  1571. case 0: useFeat0 = true; break;
  1572. case 1: useFeat1 = true; break;
  1573. case 2: useFeat2 = true; break;
  1574. case 3: useFeat3 = true; break;
  1575. case 4: useFeat4 = true; break;
  1576. }
  1577. }
  1578. is >> rawChannels;
  1579. is >> uniquenumber;
  1580. }