SemSegContextTree3D.cpp 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871
  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. #ifdef VERBOSE
  414. printFeatureStatistics();
  415. #endif
  416. }
  417. void SemSegContextTree3D::train ( const LabeledSet * trainp )
  418. {
  419. int shortsize = numeric_limits<short>::max();
  420. Timer timer;
  421. timer.start();
  422. vector<int> zsizeVec;
  423. SemSegTools::getDepthVector ( trainp, zsizeVec, run3Dseg );
  424. //FIXME: memory usage
  425. vector<MultiChannelImage3DT<double> > allfeats; // Feature Werte
  426. vector<MultiChannelImage3DT<unsigned short int> > nodeIndices; // Zuordnung Knoten/Baum für jeden Pixel
  427. vector<MultiChannelImageT<int> > labels;
  428. // für externen Klassifikator
  429. vector<SparseVector*> globalCategorFeats;
  430. vector<map<int,int> > classesPerImage;
  431. vector<vector<int> > rSize; // anzahl der pixel je region
  432. vector<int> amountRegionpI; // ANZAHL der regionen pro bild (von unsupervised segmentation)
  433. int imgCounter = 0;
  434. int amountPixels = 0;
  435. // How many channels of non-integral type do we have?
  436. if ( imagetype == IMAGETYPE_RGB )
  437. rawChannels = 3;
  438. else
  439. rawChannels = 1;
  440. if ( useGradient )
  441. {
  442. if ( run3Dseg )
  443. rawChannels *= 4; // gx, gy, gz
  444. else
  445. rawChannels *= 3; // gx, gy
  446. }
  447. if ( useAdditionalLayer ) // beliebige Merkmale in extra Bilddateien
  448. rawChannels += numAdditionalLayer;
  449. ///////////////////////////// read input data /////////////////////////////////
  450. ///////////////////////////////////////////////////////////////////////////////
  451. int depthCount = 0;
  452. vector< string > filelist;
  453. NICE::MultiChannelImageT<int> pixelLabels;
  454. std::map<int, bool> labelExist;
  455. for (LabeledSet::const_iterator it = trainp->begin(); it != trainp->end(); it++)
  456. {
  457. for (std::vector<ImageInfo *>::const_iterator jt = it->second.begin();
  458. jt != it->second.end(); jt++)
  459. {
  460. int classno = it->first;
  461. ImageInfo & info = *(*jt);
  462. std::string file = info.img();
  463. filelist.push_back ( file );
  464. depthCount++;
  465. const LocalizationResult *locResult = info.localization();
  466. // getting groundtruth
  467. NICE::ImageT<int> pL;
  468. pL.resize ( locResult->xsize, locResult->ysize );
  469. pL.set ( 0 );
  470. locResult->calcLabeledImage ( pL, ( *classNames ).getBackgroundClass() );
  471. pixelLabels.addChannel ( pL );
  472. if ( locResult->size() <= 0 )
  473. {
  474. fprintf ( stderr, "WARNING: NO ground truth polygons found for %s !\n",
  475. file.c_str() );
  476. continue;
  477. }
  478. fprintf ( stderr, "SSContext: Collecting pixel examples from localization info: %s\n", file.c_str() );
  479. int depthBoundary = 0;
  480. if ( run3Dseg )
  481. {
  482. depthBoundary = zsizeVec[imgCounter];
  483. }
  484. if ( depthCount < depthBoundary ) continue;
  485. // all image slices collected -> make a 3d image
  486. NICE::MultiChannelImage3DT<double> imgData;
  487. make3DImage ( filelist, imgData );
  488. int xsize = imgData.width();
  489. int ysize = imgData.height();
  490. int zsize = imgData.depth();
  491. amountPixels += xsize * ysize * zsize;
  492. MultiChannelImageT<int> tmpMat ( xsize, ysize, ( uint ) zsize );
  493. labels.push_back ( tmpMat );
  494. nodeIndices.push_back ( MultiChannelImage3DT<unsigned short int> ( xsize, ysize, zsize, nbTrees ) );
  495. nodeIndices[imgCounter].setAll ( 0 );
  496. int amountRegions;
  497. // convert color to L*a*b, add selected feature channels
  498. addFeatureMaps ( imgData, filelist, amountRegions );
  499. allfeats.push_back(imgData);
  500. if ( useFeat1 )
  501. {
  502. amountRegionpI.push_back ( amountRegions );
  503. rSize.push_back ( vector<int> ( amountRegions, 0 ) );
  504. }
  505. if ( useCategorization )
  506. {
  507. globalCategorFeats.push_back ( new SparseVector() );
  508. classesPerImage.push_back ( map<int,int>() );
  509. }
  510. for ( int x = 0; x < xsize; x++ )
  511. for ( int y = 0; y < ysize; y++ )
  512. for ( int z = 0; z < zsize; z++ )
  513. {
  514. if ( useFeat1 )
  515. rSize[imgCounter][allfeats[imgCounter] ( x, y, z, rawChannels ) ]++;
  516. if ( run3Dseg )
  517. classno = pixelLabels ( x, y, ( uint ) z );
  518. else
  519. classno = pL.getPixelQuick ( x,y );
  520. labels[imgCounter].set ( x, y, classno, ( uint ) z );
  521. if ( forbidden_classes.find ( classno ) != forbidden_classes.end() )
  522. continue;
  523. labelExist[classno] = true;
  524. if ( useCategorization )
  525. classesPerImage[imgCounter][classno] = 1;
  526. }
  527. filelist.clear();
  528. pixelLabels.reInit ( 0,0,0 );
  529. depthCount = 0;
  530. imgCounter++;
  531. }
  532. }
  533. int classes = 0;
  534. for ( map<int, bool>::const_iterator mapit = labelExist.begin();
  535. mapit != labelExist.end(); mapit++ )
  536. {
  537. labelmap[mapit->first] = classes;
  538. labelmapback[classes] = mapit->first;
  539. classes++;
  540. }
  541. ////////////////////////// channel type configuration /////////////////////////
  542. ///////////////////////////////////////////////////////////////////////////////
  543. unsigned char shift = 0;
  544. std::vector<int> rawChannelsIdx, numClassesIdx;
  545. int idx = 0;
  546. for ( int i = 0; i < rawChannels; i++, idx++ )
  547. rawChannelsIdx.push_back ( idx );
  548. for ( int i = 0; i < classes; i++, idx++ )
  549. numClassesIdx.push_back ( idx );
  550. /** Type 0: single pixel & pixel-comparison features on gray value channels */
  551. // actual values derived from integral values
  552. channelsPerType.push_back ( rawChannelsIdx );
  553. /** Type 1: region channel with unsupervised segmentation */
  554. if ( useFeat1 )
  555. {
  556. channelsPerType.push_back ( vector<int>(1, rawChannels) );
  557. shift = 1;
  558. }
  559. else
  560. channelsPerType.push_back ( vector<int>() );
  561. /** Type 2: rectangular and Haar-like features on gray value integral channels */
  562. if ( useFeat2 )
  563. channelsPerType.push_back ( rawChannelsIdx );
  564. else
  565. channelsPerType.push_back ( vector<int>() );
  566. /** Type 3: type 2 features on integral probability channels (context) */
  567. if ( useFeat3 )
  568. channelsPerType.push_back ( numClassesIdx );
  569. else
  570. channelsPerType.push_back ( vector<int>() );
  571. /** Type 4: type 0 features on probability channels (context) */
  572. // Type 4 channels are now INTEGRAL
  573. // This remains for compatibility reasons.
  574. if ( useFeat4 )
  575. channelsPerType.push_back ( numClassesIdx );
  576. else
  577. channelsPerType.push_back ( vector<int>() );
  578. ///////////////////////////////////////////////////////////////////////////////
  579. ///////////////////////////////////////////////////////////////////////////////
  580. vector<vector<vector<double> > > regionProbs;
  581. if ( useFeat1 )
  582. {
  583. for ( int i = 0; i < imgCounter; i++ )
  584. {
  585. regionProbs.push_back ( vector<vector<double> > ( amountRegionpI[i], vector<double> ( classes, 0.0 ) ) );
  586. }
  587. }
  588. //balancing
  589. a = vector<double> ( classes, 0.0 );
  590. int selectionCounter = 0;
  591. for ( int iCounter = 0; iCounter < imgCounter; iCounter++ )
  592. {
  593. int xsize = ( int ) nodeIndices[iCounter].width();
  594. int ysize = ( int ) nodeIndices[iCounter].height();
  595. int zsize = ( int ) nodeIndices[iCounter].depth();
  596. for ( int x = 0; x < xsize; x++ )
  597. for ( int y = 0; y < ysize; y++ )
  598. for ( int z = 0; z < zsize; z++ )
  599. {
  600. int cn = labels[iCounter] ( x, y, ( uint ) z );
  601. if ( labelmap.find ( cn ) == labelmap.end() )
  602. continue;
  603. a[labelmap[cn]] ++;
  604. selectionCounter++;
  605. }
  606. }
  607. for ( int i = 0; i < ( int ) a.size(); i++ )
  608. a[i] /= ( double ) selectionCounter;
  609. #ifdef VERBOSE
  610. cout << "\nDistribution:" << endl;
  611. for ( int i = 0; i < ( int ) a.size(); i++ )
  612. cout << "class '" << classNames->code(labelmapback[i]) << "': "
  613. << a[i] << endl;
  614. #endif
  615. depth = 0;
  616. uniquenumber = 0;
  617. //initialize random forest
  618. for ( int t = 0; t < nbTrees; t++ )
  619. {
  620. vector<TreeNode> singletree;
  621. singletree.push_back ( TreeNode() );
  622. singletree[0].dist = vector<double> ( classes, 0.0 );
  623. singletree[0].depth = depth;
  624. singletree[0].featcounter = amountPixels;
  625. singletree[0].nodeNumber = uniquenumber;
  626. uniquenumber++;
  627. forest.push_back ( singletree );
  628. }
  629. vector<int> startnode ( nbTrees, 0 );
  630. bool noNewSplit = false;
  631. timer.stop();
  632. cout << "\nTime for Pre-Processing: " << timer.getLastAbsolute() << " seconds\n" << endl;
  633. //////////////////////////// train the classifier ///////////////////////////
  634. /////////////////////////////////////////////////////////////////////////////
  635. timer.start();
  636. while ( !noNewSplit && (depth < maxDepth) )
  637. {
  638. depth++;
  639. #ifdef DEBUG
  640. cout << "depth: " << depth << endl;
  641. #endif
  642. noNewSplit = true;
  643. vector<MultiChannelImage3DT<unsigned short int> > lastNodeIndices = nodeIndices;
  644. vector<vector<vector<double> > > lastRegionProbs = regionProbs;
  645. if ( useFeat1 )
  646. for ( int i = 0; i < imgCounter; i++ )
  647. {
  648. int numRegions = (int) regionProbs[i].size();
  649. for ( int r = 0; r < numRegions; r++ )
  650. for ( int c = 0; c < classes; c++ )
  651. regionProbs[i][r][c] = 0.0;
  652. }
  653. // initialize & update context channels
  654. for ( int i = 0; i < imgCounter; i++)
  655. if ( useFeat3 || useFeat4 )
  656. this->updateProbabilityMaps ( nodeIndices[i], allfeats[i], rawChannels + shift );
  657. #ifdef VERBOSE
  658. Timer timerDepth;
  659. timerDepth.start();
  660. #endif
  661. double weight = computeWeight ( depth, maxDepth )
  662. - computeWeight ( depth - 1, maxDepth );
  663. #pragma omp parallel for
  664. // for each tree
  665. for ( int tree = 0; tree < nbTrees; tree++ )
  666. {
  667. const int t = ( int ) forest[tree].size();
  668. const int s = startnode[tree];
  669. startnode[tree] = t;
  670. double bestig;
  671. // for each node
  672. for ( int node = s; node < t; node++ )
  673. {
  674. if ( !forest[tree][node].isleaf && forest[tree][node].left < 0 )
  675. {
  676. // find best split
  677. Operation3D *splitfeat = NULL;
  678. double splitval;
  679. bestig = getBestSplit ( allfeats, lastNodeIndices, labels, node,
  680. splitfeat, splitval, tree, lastRegionProbs );
  681. forest[tree][node].feat = splitfeat;
  682. forest[tree][node].decision = splitval;
  683. // split the node
  684. if ( splitfeat != NULL )
  685. {
  686. noNewSplit = false;
  687. int left;
  688. #pragma omp critical
  689. {
  690. left = forest[tree].size();
  691. forest[tree].push_back ( TreeNode() );
  692. forest[tree].push_back ( TreeNode() );
  693. }
  694. int right = left + 1;
  695. forest[tree][node].left = left;
  696. forest[tree][node].right = right;
  697. forest[tree][left].init( depth, classes, uniquenumber);
  698. int leftu = uniquenumber;
  699. uniquenumber++;
  700. forest[tree][right].init( depth, classes, uniquenumber);
  701. int rightu = uniquenumber;
  702. uniquenumber++;
  703. #pragma omp parallel for
  704. for ( int i = 0; i < imgCounter; i++ )
  705. {
  706. int xsize = nodeIndices[i].width();
  707. int ysize = nodeIndices[i].height();
  708. int zsize = nodeIndices[i].depth();
  709. for ( int x = 0; x < xsize; x++ )
  710. {
  711. for ( int y = 0; y < ysize; y++ )
  712. {
  713. for ( int z = 0; z < zsize; z++ )
  714. {
  715. if ( nodeIndices[i].get ( x, y, z, tree ) == node )
  716. {
  717. // get feature value
  718. Features feat;
  719. feat.feats = &allfeats[i];
  720. feat.rProbs = &lastRegionProbs[i];
  721. double val = 0.0;
  722. val = splitfeat->getVal ( feat, x, y, z );
  723. if ( !isfinite ( val ) ) val = 0.0;
  724. #pragma omp critical
  725. {
  726. int curLabel = labels[i] ( x, y, ( uint ) z );
  727. // traverse to left child
  728. if ( val < splitval )
  729. {
  730. nodeIndices[i].set ( x, y, z, left, tree );
  731. if ( labelmap.find ( curLabel ) != labelmap.end() )
  732. forest[tree][left].dist[labelmap[curLabel]]++;
  733. forest[tree][left].featcounter++;
  734. if ( useCategorization && leftu < shortsize )
  735. ( *globalCategorFeats[i] ) [leftu]+=weight;
  736. }
  737. // traverse to right child
  738. else
  739. {
  740. nodeIndices[i].set ( x, y, z, right, tree );
  741. if ( labelmap.find ( curLabel ) != labelmap.end() )
  742. forest[tree][right].dist[labelmap[curLabel]]++;
  743. forest[tree][right].featcounter++;
  744. if ( useCategorization && rightu < shortsize )
  745. ( *globalCategorFeats[i] ) [rightu]+=weight;
  746. }
  747. }
  748. }
  749. }
  750. }
  751. }
  752. }
  753. // normalize distributions in child leaves
  754. double lcounter = 0.0, rcounter = 0.0;
  755. for ( int c = 0; c < (int)forest[tree][left].dist.size(); c++ )
  756. {
  757. if ( forbidden_classes.find ( labelmapback[c] ) != forbidden_classes.end() )
  758. {
  759. forest[tree][left].dist[c] = 0;
  760. forest[tree][right].dist[c] = 0;
  761. }
  762. else
  763. {
  764. forest[tree][left].dist[c] /= a[c];
  765. lcounter += forest[tree][left].dist[c];
  766. forest[tree][right].dist[c] /= a[c];
  767. rcounter += forest[tree][right].dist[c];
  768. }
  769. }
  770. assert ( lcounter > 0 && rcounter > 0 );
  771. for ( int c = 0; c < classes; c++ )
  772. {
  773. forest[tree][left].dist[c] /= lcounter;
  774. forest[tree][right].dist[c] /= rcounter;
  775. }
  776. }
  777. else
  778. {
  779. forest[tree][node].isleaf = true;
  780. }
  781. }
  782. }
  783. }
  784. if ( useFeat1 )
  785. {
  786. for ( int i = 0; i < imgCounter; i++ )
  787. {
  788. int xsize = nodeIndices[i].width();
  789. int ysize = nodeIndices[i].height();
  790. int zsize = nodeIndices[i].depth();
  791. #pragma omp parallel for
  792. // set region probability distribution
  793. for ( int x = 0; x < xsize; x++ )
  794. {
  795. for ( int y = 0; y < ysize; y++ )
  796. {
  797. for ( int z = 0; z < zsize; z++ )
  798. {
  799. for ( int tree = 0; tree < nbTrees; tree++ )
  800. {
  801. int node = nodeIndices[i].get ( x, y, z, tree );
  802. for ( int c = 0; c < classes; c++ )
  803. {
  804. int r = (int) ( allfeats[i] ( x, y, z, rawChannels ) );
  805. regionProbs[i][r][c] += forest[tree][node].dist[c];
  806. }
  807. }
  808. }
  809. }
  810. }
  811. // normalize distribution
  812. int numRegions = (int) regionProbs[i].size();
  813. for ( int r = 0; r < numRegions; r++ )
  814. {
  815. for ( int c = 0; c < classes; c++ )
  816. {
  817. regionProbs[i][r][c] /= ( double ) ( rSize[i][r] );
  818. }
  819. }
  820. }
  821. }
  822. if ( firstiteration ) firstiteration = false;
  823. #ifdef VERBOSE
  824. timerDepth.stop();
  825. cout << "Depth " << depth << ": " << timerDepth.getLastAbsolute() << " seconds" <<endl;
  826. #endif
  827. lastNodeIndices.clear();
  828. lastRegionProbs.clear();
  829. }
  830. timer.stop();
  831. cout << "Time for Learning: " << timer.getLastAbsolute() << " seconds\n" << endl;
  832. //////////////////////// classification using HIK ///////////////////////////
  833. /////////////////////////////////////////////////////////////////////////////
  834. if ( useCategorization && fasthik != NULL )
  835. {
  836. timer.start();
  837. uniquenumber = std::min ( shortsize, uniquenumber );
  838. for ( uint i = 0; i < globalCategorFeats.size(); i++ )
  839. {
  840. globalCategorFeats[i]->setDim ( uniquenumber );
  841. globalCategorFeats[i]->normalize();
  842. }
  843. std::map< uint, NICE::Vector > ys;
  844. uint cCounter = 0;
  845. for ( std::map<int,int>::const_iterator it = labelmap.begin();
  846. it != labelmap.end(); it++, cCounter++ )
  847. {
  848. ys[cCounter] = NICE::Vector ( globalCategorFeats.size() );
  849. for ( int i = 0; i < imgCounter; i++ )
  850. {
  851. if ( classesPerImage[i].find ( it->first ) != classesPerImage[i].end() )
  852. {
  853. ys[cCounter][i] = 1;
  854. }
  855. else
  856. {
  857. ys[cCounter][i] = -1;
  858. }
  859. }
  860. }
  861. fasthik->train( reinterpret_cast<vector<const NICE::SparseVector *>&>(globalCategorFeats), ys);
  862. timer.stop();
  863. cerr << "Time for Categorization: " << timer.getLastAbsolute() << " seconds\n" << endl;
  864. }
  865. }
  866. void SemSegContextTree3D::printFeatureStatistics ()
  867. {
  868. cout << "\nFEATURE USAGE" << endl;
  869. cout << "#############\n" << endl;
  870. // amount of used features per feature type
  871. std::map<int, int> featTypeCounter;
  872. for ( int tree = 0; tree < nbTrees; tree++ )
  873. {
  874. int t = ( int ) forest[tree].size();
  875. for ( int node = 0; node < t; node++ )
  876. {
  877. if ( !forest[tree][node].isleaf && forest[tree][node].left != -1 )
  878. {
  879. featTypeCounter[ forest[tree][node].feat->getFeatType() ] += 1;
  880. }
  881. }
  882. }
  883. cout << "Types:" << endl;
  884. for ( map<int, int>::const_iterator it = featTypeCounter.begin(); it != featTypeCounter.end(); it++ )
  885. cout << it->first << ": " << it->second << endl;
  886. cout << "\nOperations - All:" << endl;
  887. // used operations
  888. vector<int> opOverview ( NBOPERATIONS, 0 );
  889. // relative use of context vs raw features per tree level
  890. vector<vector<double> > contextOverview ( maxDepth, vector<double> ( 2, 0.0 ) );
  891. for ( int tree = 0; tree < nbTrees; tree++ )
  892. {
  893. int t = ( int ) forest[tree].size();
  894. for ( int node = 0; node < t; node++ )
  895. {
  896. #ifdef DEBUG
  897. printf ( "tree[%i]: left: %i, right: %i", node, forest[tree][node].left, forest[tree][node].right );
  898. #endif
  899. if ( !forest[tree][node].isleaf && forest[tree][node].left != -1 )
  900. {
  901. #ifdef DEBUG
  902. cout << forest[tree][node].feat->writeInfos() << endl;
  903. #endif
  904. opOverview[ forest[tree][node].feat->getOps() ]++;
  905. contextOverview[forest[tree][node].depth][ ( int ) forest[tree][node].feat->getContext() ]++;
  906. }
  907. #ifdef DEBUG
  908. for ( int d = 0; d < ( int ) forest[tree][node].dist.size(); d++ )
  909. cout << " " << forest[tree][node].dist[d];
  910. cout << endl;
  911. #endif
  912. }
  913. }
  914. // amount of used features per operation type
  915. cout << "\nOperations - Summary:" << endl;
  916. for ( int t = 0; t < ( int ) opOverview.size(); t++ )
  917. {
  918. cout << "Ops " << t << ": " << opOverview[ t ] << endl;
  919. }
  920. // ratio of used context features per depth level
  921. cout << "\nContext-Ratio:" << endl;
  922. for ( int d = 0; d < maxDepth; d++ )
  923. {
  924. double sum = contextOverview[d][0] + contextOverview[d][1];
  925. if ( sum == 0 )
  926. sum = 1;
  927. contextOverview[d][0] /= sum;
  928. contextOverview[d][1] /= sum;
  929. cout << "Depth [" << d+1 << "] Normal: " << contextOverview[d][0] << " Context: " << contextOverview[d][1] << endl;
  930. }
  931. }
  932. void SemSegContextTree3D::addFeatureMaps (
  933. NICE::MultiChannelImage3DT<double> &imgData,
  934. const vector<string> &filelist,
  935. int &amountRegions )
  936. {
  937. int xsize = imgData.width();
  938. int ysize = imgData.height();
  939. int zsize = imgData.depth();
  940. amountRegions = 0;
  941. // RGB to Lab
  942. if ( imagetype == IMAGETYPE_RGB )
  943. {
  944. for ( int z = 0; z < zsize; z++ )
  945. for ( int y = 0; y < ysize; y++ )
  946. for ( int x = 0; x < xsize; x++ )
  947. {
  948. double R, G, B, X, Y, Z, L, a, b;
  949. R = ( double )imgData.get( x, y, z, 0 ) / 255.0;
  950. G = ( double )imgData.get( x, y, z, 1 ) / 255.0;
  951. B = ( double )imgData.get( x, y, z, 2 ) / 255.0;
  952. if ( useAltTristimulus )
  953. {
  954. ColorConversion::ccRGBtoXYZ( R, G, B, &X, &Y, &Z, 4 );
  955. ColorConversion::ccXYZtoCIE_Lab( X, Y, Z, &L, &a, &b, 4 );
  956. }
  957. else
  958. {
  959. ColorConversion::ccRGBtoXYZ( R, G, B, &X, &Y, &Z, 0 );
  960. ColorConversion::ccXYZtoCIE_Lab( X, Y, Z, &L, &a, &b, 0 );
  961. }
  962. imgData.set( x, y, z, L, 0 );
  963. imgData.set( x, y, z, a, 1 );
  964. imgData.set( x, y, z, b, 2 );
  965. }
  966. }
  967. else
  968. // normalize gray values to [0,1]
  969. {
  970. for ( int z = 0; z < zsize; z++ )
  971. for ( int y = 0; y < ysize; y++ )
  972. for ( int x = 0; x < xsize; x++ )
  973. {
  974. double val = imgData.get( x, y, z, 0 ) / 255.0;
  975. imgData.set( x, y, z, val, 0 );
  976. }
  977. }
  978. // Gradient layers
  979. if ( useGradient )
  980. {
  981. int currentsize = imgData.channels();
  982. imgData.addChannel ( 2*currentsize );
  983. // gradients for X and Y
  984. for ( int z = 0; z < zsize; z++ )
  985. for ( int c = 0; c < currentsize; c++ )
  986. {
  987. ImageT<double> tmp = imgData.getChannelT(z, c);
  988. ImageT<double> sobX( xsize, ysize );
  989. ImageT<double> sobY( xsize, ysize );
  990. NICE::FilterT<double, double, double>::sobelX ( tmp, sobX );
  991. NICE::FilterT<double, double, double>::sobelY ( tmp, sobY );
  992. for ( int y = 0; y < ysize; y++ )
  993. for ( int x = 0; x < xsize; x++ )
  994. {
  995. imgData.set( x, y, z, sobX.getPixelQuick(x,y), c+currentsize );
  996. imgData.set( x, y, z, sobY.getPixelQuick(x,y), c+(currentsize*2) );
  997. }
  998. }
  999. // gradients for Z
  1000. if ( run3Dseg )
  1001. {
  1002. imgData.addChannel ( currentsize );
  1003. for ( int x = 0; x < xsize; x++ )
  1004. for ( int c = 0; c < currentsize; c++ )
  1005. {
  1006. ImageT<double> tmp = imgData.getXSlice(x, c);
  1007. ImageT<double> sobZ( zsize, ysize );
  1008. NICE::FilterT<double, double, double>::sobelX ( tmp, sobZ );
  1009. for ( int y = 0; y < ysize; y++ )
  1010. for ( int z = 0; z < zsize; z++ )
  1011. imgData.set( x, y, z, sobZ.getPixelQuick(z,y), c+(currentsize*3) );
  1012. }
  1013. }
  1014. }
  1015. // arbitrary amount of additional layers as feature maps
  1016. if ( useAdditionalLayer )
  1017. {
  1018. for ( int a = 0; a < numAdditionalLayer; a++ )
  1019. {
  1020. ostringstream convert;
  1021. convert << a;
  1022. #ifdef DEBUG
  1023. cout << "Using additional layer #" << a << endl;
  1024. #endif
  1025. int currentsize = imgData.channels();
  1026. imgData.addChannel ( 1 );
  1027. for ( int z = 0; z < zsize; z++ )
  1028. {
  1029. vector<string> list;
  1030. StringTools::split ( filelist[z], '/', list );
  1031. string layerPath = StringTools::trim ( filelist[z], list.back() )
  1032. + "addlayer" + convert.str() + "/" + list.back();
  1033. NICE::Image layer ( layerPath );
  1034. for ( int y = 0; y < ysize; y++ )
  1035. for ( int x = 0; x < xsize; x++ )
  1036. imgData.set(x, y, z, layer.getPixelQuick(x,y), currentsize);
  1037. }
  1038. }
  1039. }
  1040. // region feature (unsupervised segmentation)
  1041. int shift = 0;
  1042. if ( useFeat1 )
  1043. {
  1044. shift = 1;
  1045. MultiChannelImageT<int> regions;
  1046. regions.reInit( xsize, ysize, zsize );
  1047. amountRegions = segmentation->segRegions ( imgData, regions, imagetype );
  1048. int currentsize = imgData.channels();
  1049. imgData.addChannel ( 1 );
  1050. for ( int z = 0; z < ( int ) regions.channels(); z++ )
  1051. for ( int y = 0; y < regions.height(); y++ )
  1052. for ( int x = 0; x < regions.width(); x++ )
  1053. imgData.set ( x, y, z, regions ( x, y, ( uint ) z ), currentsize );
  1054. }
  1055. // convert raw channels to intergal channels
  1056. #pragma omp parallel for
  1057. for ( int i = 0; i < rawChannels; i++ )
  1058. imgData.calcIntegral ( i );
  1059. int classes = classNames->numClasses() - forbidden_classes.size();
  1060. if ( useFeat3 || useFeat4 )
  1061. imgData.addChannel ( classes );
  1062. }
  1063. void SemSegContextTree3D::classify (
  1064. const std::vector<std::string> & filelist,
  1065. NICE::MultiChannelImageT<int> & segresult,
  1066. NICE::MultiChannelImage3DT<double> & probabilities )
  1067. {
  1068. ///////////////////////// build MCI3DT from files ///////////////////////////
  1069. /////////////////////////////////////////////////////////////////////////////
  1070. NICE::MultiChannelImage3DT<double> imgData;
  1071. this->make3DImage( filelist, imgData );
  1072. int xsize = imgData.width();
  1073. int ysize = imgData.height();
  1074. int zsize = imgData.depth();
  1075. ////////////////////////// initialize variables /////////////////////////////
  1076. /////////////////////////////////////////////////////////////////////////////
  1077. firstiteration = true;
  1078. depth = 0;
  1079. // anytime classification ability
  1080. int classificationDepth = conf->gI( "SSContextTree", "classification_depth", maxDepth );
  1081. if (classificationDepth > maxDepth || classificationDepth < 1 )
  1082. classificationDepth = maxDepth;
  1083. Timer timer;
  1084. timer.start();
  1085. // classes occurred during training step
  1086. int classes = labelmapback.size();
  1087. // classes defined in config file
  1088. int numClasses = classNames->numClasses();
  1089. // class probabilities by pixel
  1090. probabilities.reInit ( xsize, ysize, zsize, numClasses );
  1091. probabilities.setAll ( 0 );
  1092. // class probabilities by region
  1093. vector<vector<double> > regionProbs;
  1094. // affiliation: pixel <-> (tree,node)
  1095. MultiChannelImage3DT<unsigned short int> nodeIndices ( xsize, ysize, zsize, nbTrees );
  1096. nodeIndices.setAll ( 0 );
  1097. // for categorization
  1098. SparseVector *globalCategorFeat;
  1099. globalCategorFeat = new SparseVector();
  1100. /////////////////////////// get feature values //////////////////////////////
  1101. /////////////////////////////////////////////////////////////////////////////
  1102. // Basic Features
  1103. int amountRegions;
  1104. addFeatureMaps ( imgData, filelist, amountRegions );
  1105. vector<int> rSize;
  1106. int shift = 0;
  1107. if ( useFeat1 )
  1108. {
  1109. shift = 1;
  1110. regionProbs = vector<vector<double> > ( amountRegions, vector<double> ( classes, 0.0 ) );
  1111. rSize = vector<int> ( amountRegions, 0 );
  1112. for ( int z = 0; z < zsize; z++ )
  1113. {
  1114. for ( int y = 0; y < ysize; y++ )
  1115. {
  1116. for ( int x = 0; x < xsize; x++ )
  1117. {
  1118. rSize[imgData ( x, y, z, rawChannels ) ]++;
  1119. }
  1120. }
  1121. }
  1122. }
  1123. ////////////////// traverse image example through trees /////////////////////
  1124. /////////////////////////////////////////////////////////////////////////////
  1125. bool noNewSplit = false;
  1126. for ( int d = 0; d < classificationDepth && !noNewSplit; d++ )
  1127. {
  1128. depth++;
  1129. vector<vector<double> > lastRegionProbs = regionProbs;
  1130. if ( useFeat1 )
  1131. {
  1132. int numRegions = ( int ) regionProbs.size();
  1133. for ( int r = 0; r < numRegions; r++ )
  1134. for ( int c = 0; c < classes; c++ )
  1135. regionProbs[r][c] = 0.0;
  1136. }
  1137. if ( depth < classificationDepth )
  1138. {
  1139. int firstChannel = rawChannels + shift;
  1140. if ( useFeat3 || useFeat4 )
  1141. this->updateProbabilityMaps ( nodeIndices, imgData, firstChannel );
  1142. }
  1143. double weight = computeWeight ( depth, maxDepth )
  1144. - computeWeight ( depth - 1, maxDepth );
  1145. noNewSplit = true;
  1146. int tree;
  1147. #pragma omp parallel for private(tree)
  1148. for ( tree = 0; tree < nbTrees; tree++ )
  1149. for ( int x = 0; x < xsize; x=x+labelIncrement )
  1150. for ( int y = 0; y < ysize; y=y+labelIncrement )
  1151. for ( int z = 0; z < zsize; z++ )
  1152. {
  1153. int node = nodeIndices.get ( x, y, z, tree );
  1154. if ( forest[tree][node].left > 0 )
  1155. {
  1156. noNewSplit = false;
  1157. Features feat;
  1158. feat.feats = &imgData;
  1159. feat.rProbs = &lastRegionProbs;
  1160. double val = forest[tree][node].feat->getVal ( feat, x, y, z );
  1161. if ( !isfinite ( val ) ) val = 0.0;
  1162. // traverse to left child
  1163. if ( val < forest[tree][node].decision )
  1164. {
  1165. int left = forest[tree][node].left;
  1166. for ( int n = 0; n < labelIncrement; n++ )
  1167. for ( int m = 0; m < labelIncrement; m++ )
  1168. if (x+m < xsize && y+n < ysize)
  1169. nodeIndices.set ( x+m, y+n, z, left, tree );
  1170. #pragma omp critical
  1171. {
  1172. if ( fasthik != NULL
  1173. && useCategorization
  1174. && forest[tree][left].nodeNumber < uniquenumber )
  1175. ( *globalCategorFeat ) [forest[tree][left].nodeNumber] += weight;
  1176. }
  1177. }
  1178. // traverse to right child
  1179. else
  1180. {
  1181. int right = forest[tree][node].right;
  1182. for ( int n = 0; n < labelIncrement; n++ )
  1183. for ( int m = 0; m < labelIncrement; m++ )
  1184. if (x+m < xsize && y+n < ysize)
  1185. nodeIndices.set ( x+m, y+n, z, right, tree );
  1186. #pragma omp critical
  1187. {
  1188. if ( fasthik != NULL
  1189. && useCategorization
  1190. && forest[tree][right].nodeNumber < uniquenumber )
  1191. ( *globalCategorFeat ) [forest[tree][right].nodeNumber] += weight;
  1192. }
  1193. }
  1194. }
  1195. }
  1196. if ( useFeat1 )
  1197. {
  1198. int xsize = nodeIndices.width();
  1199. int ysize = nodeIndices.height();
  1200. int zsize = nodeIndices.depth();
  1201. #pragma omp parallel for
  1202. for ( int x = 0; x < xsize; x++ )
  1203. for ( int y = 0; y < ysize; y++ )
  1204. for ( int z = 0; z < zsize; z++ )
  1205. for ( int tree = 0; tree < nbTrees; tree++ )
  1206. {
  1207. int node = nodeIndices.get ( x, y, z, tree );
  1208. for ( uint c = 0; c < forest[tree][node].dist.size(); c++ )
  1209. {
  1210. int r = (int) imgData ( x, y, z, rawChannels );
  1211. regionProbs[r][c] += forest[tree][node].dist[c];
  1212. }
  1213. }
  1214. int numRegions = (int) regionProbs.size();
  1215. for ( int r = 0; r < numRegions; r++ )
  1216. for ( int c = 0; c < (int) classes; c++ )
  1217. regionProbs[r][c] /= ( double ) ( rSize[r] );
  1218. }
  1219. if ( (depth < classificationDepth) && firstiteration ) firstiteration = false;
  1220. }
  1221. vector<int> classesInImg;
  1222. if ( useCategorization )
  1223. {
  1224. if ( cndir != "" )
  1225. {
  1226. for ( int z = 0; z < zsize; z++ )
  1227. {
  1228. vector< string > list;
  1229. StringTools::split ( filelist[z], '/', list );
  1230. string orgname = list.back();
  1231. ifstream infile ( ( cndir + "/" + orgname + ".dat" ).c_str() );
  1232. while ( !infile.eof() && infile.good() )
  1233. {
  1234. int tmp;
  1235. infile >> tmp;
  1236. assert ( tmp >= 0 && tmp < numClasses );
  1237. classesInImg.push_back ( tmp );
  1238. }
  1239. }
  1240. }
  1241. else
  1242. {
  1243. globalCategorFeat->setDim ( uniquenumber );
  1244. globalCategorFeat->normalize();
  1245. ClassificationResult cr = fasthik->classify( globalCategorFeat);
  1246. for ( uint i = 0; i < ( uint ) classes; i++ )
  1247. {
  1248. cerr << cr.scores[i] << " ";
  1249. if ( cr.scores[i] > 0.0/*-0.3*/ )
  1250. {
  1251. classesInImg.push_back ( i );
  1252. }
  1253. }
  1254. }
  1255. cerr << "amount of classes: " << classes << " used classes: " << classesInImg.size() << endl;
  1256. }
  1257. if ( classesInImg.size() == 0 )
  1258. {
  1259. for ( uint i = 0; i < ( uint ) classes; i++ )
  1260. {
  1261. classesInImg.push_back ( i );
  1262. }
  1263. }
  1264. // final labeling step
  1265. if ( pixelWiseLabeling )
  1266. {
  1267. for ( int x = 0; x < xsize; x++ )
  1268. for ( int y = 0; y < ysize; y++ )
  1269. for ( int z = 0; z < zsize; z++ )
  1270. {
  1271. double maxProb = - numeric_limits<double>::max();
  1272. int maxClass = 0;
  1273. for ( uint c = 0; c < classesInImg.size(); c++ )
  1274. {
  1275. int i = classesInImg[c];
  1276. double curProb = getMeanProb ( x, y, z, i, nodeIndices );
  1277. probabilities.set ( x, y, z, curProb, labelmapback[i] );
  1278. if ( curProb > maxProb )
  1279. {
  1280. maxProb = curProb;
  1281. maxClass = labelmapback[i];
  1282. }
  1283. }
  1284. assert(maxProb <= 1);
  1285. // copy pixel labeling into segresults (output)
  1286. segresult.set ( x, y, maxClass, ( uint ) z );
  1287. }
  1288. #ifdef VISUALIZE
  1289. saveProbabilityMapAsImage( probabilities );
  1290. #endif
  1291. }
  1292. else
  1293. {
  1294. // labeling by region
  1295. NICE::MultiChannelImageT<int> regions;
  1296. int xsize = imgData.width();
  1297. int ysize = imgData.height();
  1298. int zsize = imgData.depth();
  1299. regions.reInit ( xsize, ysize, zsize );
  1300. if ( useFeat1 )
  1301. {
  1302. for ( int z = 0; z < zsize; z++ )
  1303. for ( int y = 0; y < ysize; y++ )
  1304. for ( int x = 0; x < xsize; x++ )
  1305. regions.set ( x, y, imgData ( x, y, z, rawChannels ), ( uint ) z );
  1306. }
  1307. else
  1308. {
  1309. amountRegions = segmentation->segRegions ( imgData, regions, imagetype );
  1310. #ifdef DEBUG
  1311. for ( unsigned int z = 0; z < ( uint ) zsize; z++ )
  1312. {
  1313. NICE::Matrix regmask;
  1314. NICE::ColorImage colorimg ( xsize, ysize );
  1315. NICE::ColorImage marked ( xsize, ysize );
  1316. regmask.resize ( xsize, ysize );
  1317. for ( int y = 0; y < ysize; y++ )
  1318. {
  1319. for ( int x = 0; x < xsize; x++ )
  1320. {
  1321. regmask ( x,y ) = regions ( x,y,z );
  1322. colorimg.setPixelQuick ( x, y, 0, imgData.get ( x,y,z,0 ) );
  1323. colorimg.setPixelQuick ( x, y, 1, imgData.get ( x,y,z,0 ) );
  1324. colorimg.setPixelQuick ( x, y, 2, imgData.get ( x,y,z,0 ) );
  1325. }
  1326. }
  1327. vector<int> colorvals;
  1328. colorvals.push_back ( 255 );
  1329. colorvals.push_back ( 0 );
  1330. colorvals.push_back ( 0 );
  1331. segmentation->markContours ( colorimg, regmask, colorvals, marked );
  1332. std::vector<string> list;
  1333. StringTools::split ( filelist[z], '/', list );
  1334. string savePath = StringTools::trim ( filelist[z], list.back() ) + "marked/" + list.back();
  1335. marked.write ( savePath );
  1336. }
  1337. #endif
  1338. }
  1339. regionProbs.clear();
  1340. regionProbs = vector<vector<double> > ( amountRegions, vector<double> ( classes, 0.0 ) );
  1341. vector<vector<double> > regionProbsCount ( amountRegions, vector<double> ( classes, 0.0 ) );
  1342. vector<int> bestlabels ( amountRegions, labelmapback[classesInImg[0]] );
  1343. for ( int z = 0; z < zsize; z++ )
  1344. {
  1345. for ( int y = 0; y < ysize; y++ )
  1346. {
  1347. for ( int x = 0; x < xsize; x++ )
  1348. {
  1349. int r = regions ( x, y, ( uint ) z );
  1350. for ( uint i = 0; i < classesInImg.size(); i++ )
  1351. {
  1352. int c = classesInImg[i];
  1353. // get mean voting of all trees
  1354. regionProbs[r][c] += getMeanProb ( x, y, z, c, nodeIndices );
  1355. regionProbsCount[r][c]++;
  1356. }
  1357. }
  1358. }
  1359. }
  1360. for ( int r = 0; r < amountRegions; r++ )
  1361. for ( int c = 0; c < classes; c++ )
  1362. regionProbs[r][c] /= regionProbsCount[r][c];
  1363. for ( int r = 0; r < amountRegions; r++ )
  1364. {
  1365. double maxProb = regionProbs[r][classesInImg[0]];
  1366. bestlabels[r] = classesInImg[0];
  1367. for ( int c = 1; c < classes; c++ )
  1368. if ( maxProb < regionProbs[r][c] )
  1369. {
  1370. maxProb = regionProbs[r][c];
  1371. bestlabels[r] = c;
  1372. }
  1373. bestlabels[r] = labelmapback[bestlabels[r]];
  1374. }
  1375. // copy region labeling into segresults (output)
  1376. for ( int z = 0; z < zsize; z++ )
  1377. for ( int y = 0; y < ysize; y++ )
  1378. for ( int x = 0; x < xsize; x++ )
  1379. {
  1380. int r = regions ( x,y, (uint) z );
  1381. int l = bestlabels[ r ];
  1382. segresult.set ( x, y, l, (uint) z );
  1383. for ( int c = 0; c < classes; c++ )
  1384. {
  1385. double curProb = regionProbs[r][c];
  1386. probabilities.set( x, y, z, curProb, c );
  1387. }
  1388. }
  1389. #ifdef WRITEREGIONS
  1390. for ( int z = 0; z < zsize; z++ )
  1391. {
  1392. RegionGraph rg;
  1393. NICE::ColorImage img ( xsize,ysize );
  1394. if ( imagetype == IMAGETYPE_RGB )
  1395. {
  1396. img = imgData.getColor ( z );
  1397. }
  1398. else
  1399. {
  1400. NICE::Image gray = imgData.getChannel ( z );
  1401. for ( int y = 0; y < ysize; y++ )
  1402. {
  1403. for ( int x = 0; x < xsize; x++ )
  1404. {
  1405. int val = gray.getPixelQuick ( x,y );
  1406. img.setPixelQuick ( x, y, val, val, val );
  1407. }
  1408. }
  1409. }
  1410. Matrix regions_tmp ( xsize,ysize );
  1411. for ( int y = 0; y < ysize; y++ )
  1412. {
  1413. for ( int x = 0; x < xsize; x++ )
  1414. {
  1415. regions_tmp ( x,y ) = regions ( x,y, ( uint ) z );
  1416. }
  1417. }
  1418. segmentation->getGraphRepresentation ( img, regions_tmp, rg );
  1419. for ( uint pos = 0; pos < regionProbs.size(); pos++ )
  1420. {
  1421. rg[pos]->setProbs ( regionProbs[pos] );
  1422. }
  1423. std::string s;
  1424. std::stringstream out;
  1425. std::vector< std::string > list;
  1426. StringTools::split ( filelist[z], '/', list );
  1427. out << "rgout/" << list.back() << ".graph";
  1428. string writefile = out.str();
  1429. rg.write ( writefile );
  1430. }
  1431. #endif
  1432. }
  1433. timer.stop();
  1434. cout << "\nTime for Classification: " << timer.getLastAbsolute() << endl;
  1435. // CLEANING UP
  1436. // TODO: operations in "forest"
  1437. while( !ops.empty() )
  1438. {
  1439. OperationPool* op = ops.back();
  1440. op->clear();
  1441. ops.pop_back();
  1442. }
  1443. delete globalCategorFeat;
  1444. }
  1445. void SemSegContextTree3D::store ( std::ostream & os, int format ) const
  1446. {
  1447. os.precision ( numeric_limits<double>::digits10 + 1 );
  1448. os << nbTrees << endl;
  1449. classnames.store ( os );
  1450. map<int, int>::const_iterator it;
  1451. os << labelmap.size() << endl;
  1452. for ( it = labelmap.begin() ; it != labelmap.end(); it++ )
  1453. os << ( *it ).first << " " << ( *it ).second << endl;
  1454. os << labelmapback.size() << endl;
  1455. for ( it = labelmapback.begin() ; it != labelmapback.end(); it++ )
  1456. os << ( *it ).first << " " << ( *it ).second << endl;
  1457. int trees = forest.size();
  1458. os << trees << endl;
  1459. for ( int t = 0; t < trees; t++ )
  1460. {
  1461. int nodes = forest[t].size();
  1462. os << nodes << endl;
  1463. for ( int n = 0; n < nodes; n++ )
  1464. {
  1465. 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;
  1466. os << forest[t][n].dist << endl;
  1467. if ( forest[t][n].feat == NULL )
  1468. os << -1 << endl;
  1469. else
  1470. {
  1471. os << forest[t][n].feat->getOps() << endl;
  1472. forest[t][n].feat->store ( os );
  1473. }
  1474. }
  1475. }
  1476. vector<int> channelType;
  1477. if ( useFeat0 )
  1478. channelType.push_back(0);
  1479. if ( useFeat1 )
  1480. channelType.push_back(1);
  1481. if ( useFeat2 )
  1482. channelType.push_back(2);
  1483. if ( useFeat3 )
  1484. channelType.push_back(3);
  1485. if ( useFeat4 )
  1486. channelType.push_back(4);
  1487. os << channelType.size() << endl;
  1488. for ( int i = 0; i < ( int ) channelType.size(); i++ )
  1489. {
  1490. os << channelType[i] << " ";
  1491. }
  1492. os << endl;
  1493. os << rawChannels << endl;
  1494. os << uniquenumber << endl;
  1495. }
  1496. void SemSegContextTree3D::restore ( std::istream & is, int format )
  1497. {
  1498. is >> nbTrees;
  1499. classnames.restore ( is );
  1500. int lsize;
  1501. is >> lsize;
  1502. labelmap.clear();
  1503. for ( int l = 0; l < lsize; l++ )
  1504. {
  1505. int first, second;
  1506. is >> first;
  1507. is >> second;
  1508. labelmap[first] = second;
  1509. }
  1510. is >> lsize;
  1511. labelmapback.clear();
  1512. for ( int l = 0; l < lsize; l++ )
  1513. {
  1514. int first, second;
  1515. is >> first;
  1516. is >> second;
  1517. labelmapback[first] = second;
  1518. }
  1519. int trees;
  1520. is >> trees;
  1521. forest.clear();
  1522. for ( int t = 0; t < trees; t++ )
  1523. {
  1524. vector<TreeNode> tmptree;
  1525. forest.push_back ( tmptree );
  1526. int nodes;
  1527. is >> nodes;
  1528. for ( int n = 0; n < nodes; n++ )
  1529. {
  1530. TreeNode tmpnode;
  1531. forest[t].push_back ( tmpnode );
  1532. is >> forest[t][n].left;
  1533. is >> forest[t][n].right;
  1534. is >> forest[t][n].decision;
  1535. is >> forest[t][n].isleaf;
  1536. is >> forest[t][n].depth;
  1537. is >> forest[t][n].featcounter;
  1538. is >> forest[t][n].nodeNumber;
  1539. is >> forest[t][n].dist;
  1540. int feattype;
  1541. is >> feattype;
  1542. assert ( feattype < NBOPERATIONS );
  1543. forest[t][n].feat = NULL;
  1544. if ( feattype >= 0 )
  1545. {
  1546. for ( uint o = 0; o < ops.size(); o++ )
  1547. {
  1548. for ( uint o2 = 0; o2 < ops[o]->pool.size(); o2++ )
  1549. {
  1550. if ( forest[t][n].feat == NULL )
  1551. {
  1552. if ( ops[o]->pool[o2]->getOps() == feattype )
  1553. {
  1554. forest[t][n].feat = ops[o]->pool[o2]->clone();
  1555. break;
  1556. }
  1557. }
  1558. }
  1559. }
  1560. assert ( forest[t][n].feat != NULL );
  1561. forest[t][n].feat->restore ( is );
  1562. forest[t][n].feat->setWSize ( windowSize );
  1563. }
  1564. }
  1565. }
  1566. // channel type configuration
  1567. int ctsize;
  1568. is >> ctsize;
  1569. for ( int i = 0; i < ctsize; i++ )
  1570. {
  1571. int tmp;
  1572. is >> tmp;
  1573. switch (tmp)
  1574. {
  1575. case 0: useFeat0 = true; break;
  1576. case 1: useFeat1 = true; break;
  1577. case 2: useFeat2 = true; break;
  1578. case 3: useFeat3 = true; break;
  1579. case 4: useFeat4 = true; break;
  1580. }
  1581. }
  1582. is >> rawChannels;
  1583. is >> uniquenumber;
  1584. }