SemSegContextTree.cpp 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278
  1. #include "SemSegContextTree.h"
  2. #include "vislearning/baselib/Globals.h"
  3. #include "vislearning/baselib/ProgressBar.h"
  4. #include "core/basics/StringTools.h"
  5. #include "core/imagedisplay/ImageDisplay.h"
  6. #include "vislearning/cbaselib/CachedExample.h"
  7. #include "vislearning/cbaselib/PascalResults.h"
  8. #include "vislearning/baselib/ColorSpace.h"
  9. #include "segmentation/RSMeanShift.h"
  10. #include "segmentation/RSGraphBased.h"
  11. #include "segmentation/RSSlic.h"
  12. #include "core/basics/numerictools.h"
  13. #include "core/basics/StringTools.h"
  14. #include "core/basics/FileName.h"
  15. #include "vislearning/baselib/ICETools.h"
  16. #include "core/basics/Timer.h"
  17. #include "core/basics/vectorio.h"
  18. #include "core/image/FilterT.h"
  19. #include <omp.h>
  20. #include <iostream>
  21. //#define DEBUG
  22. using namespace OBJREC;
  23. using namespace std;
  24. using namespace NICE;
  25. SemSegContextTree::SemSegContextTree ( const Config *conf, const MultiDataset *md )
  26. : SemanticSegmentation ( conf, & ( md->getClassNames ( "train" ) ) )
  27. {
  28. this->conf = conf;
  29. string section = "SSContextTree";
  30. lfcw = new LFColorWeijer ( conf );
  31. firstiteration = true;
  32. maxSamples = conf->gI ( section, "max_samples", 2000 );
  33. minFeats = conf->gI ( section, "min_feats", 50 );
  34. maxDepth = conf->gI ( section, "max_depth", 10 );
  35. windowSize = conf->gI ( section, "window_size", 16 );
  36. featsPerSplit = conf->gI ( section, "feats_per_split", 200 );
  37. useShannonEntropy = conf->gB ( section, "use_shannon_entropy", true );
  38. nbTrees = conf->gI ( section, "amount_trees", 1 );
  39. string segmentationtype = conf->gS ( section, "segmentation_type", "slic" );
  40. useCategorization = conf->gB ( section, "use_categorization", false );
  41. cndir = conf->gS ( "SSContextTree", "cndir", "" );
  42. if ( useCategorization && cndir == "" )
  43. {
  44. fasthik = new GPHIKClassifierNICE ( conf );
  45. }
  46. else
  47. {
  48. fasthik = NULL;
  49. }
  50. randomTests = conf->gI ( section, "random_tests", 10 );
  51. bool saveLoadData = conf->gB ( "debug", "save_load_data", false );
  52. string fileLocation = conf->gS ( "debug", "datafile", "tmp.txt" );
  53. pixelWiseLabeling = false;
  54. useRegionFeature = conf->gB ( section, "use_region_feat", false );
  55. if ( segmentationtype == "meanshift" )
  56. segmentation = new RSMeanShift ( conf );
  57. else if ( segmentationtype == "none" )
  58. {
  59. segmentation = NULL;
  60. pixelWiseLabeling = true;
  61. useRegionFeature = false;
  62. }
  63. else if ( segmentationtype == "felzenszwalb" )
  64. segmentation = new RSGraphBased ( conf );
  65. else if ( segmentationtype == "slic" )
  66. segmentation = new RSSlic ( conf );
  67. else
  68. throw ( "no valid segmenation_type\n please choose between none, meanshift, slic and felzenszwalb\n" );
  69. ftypes = conf->gI ( section, "features", 100 );;
  70. string featsec = "Features";
  71. vector<Operation*> tops;
  72. if ( conf->gB ( featsec, "minus", true ) )
  73. tops.push_back ( new Minus() );
  74. if ( conf->gB ( featsec, "minus_abs", true ) )
  75. tops.push_back ( new MinusAbs() );
  76. if ( conf->gB ( featsec, "addition", true ) )
  77. tops.push_back ( new Addition() );
  78. if ( conf->gB ( featsec, "only1", true ) )
  79. tops.push_back ( new Only1() );
  80. if ( conf->gB ( featsec, "rel_x", true ) )
  81. tops.push_back ( new RelativeXPosition() );
  82. if ( conf->gB ( featsec, "rel_y", true ) )
  83. tops.push_back ( new RelativeYPosition() );
  84. if ( conf->gB ( featsec, "rel_z", true ) )
  85. tops.push_back ( new RelativeZPosition() );
  86. ops.push_back ( tops );
  87. tops.clear();
  88. tops.push_back ( new RegionFeat() );
  89. ops.push_back ( tops );
  90. tops.clear();
  91. if ( conf->gB ( featsec, "int", true ) )
  92. tops.push_back ( new IntegralOps() );
  93. if ( conf->gB ( featsec, "bi_int_cent", true ) )
  94. tops.push_back ( new BiIntegralCenteredOps() );
  95. if ( conf->gB ( featsec, "int_cent", true ) )
  96. tops.push_back ( new IntegralCenteredOps() );
  97. if ( conf->gB ( featsec, "haar_horz", true ) )
  98. tops.push_back ( new HaarHorizontal() );
  99. if ( conf->gB ( featsec, "haar_vert", true ) )
  100. tops.push_back ( new HaarVertical() );
  101. if ( conf->gB ( featsec, "haar_stack", true ) )
  102. tops.push_back ( new HaarStacked() );
  103. if ( conf->gB ( featsec, "haar_diagxy", true ) )
  104. tops.push_back ( new HaarDiagXY() );
  105. if ( conf->gB ( featsec, "haar_diagxz", true ) )
  106. tops.push_back ( new HaarDiagXZ() );
  107. if ( conf->gB ( featsec, "haar_diagyz", true ) )
  108. tops.push_back ( new HaarDiagYZ() );
  109. if ( conf->gB ( featsec, "haar3_horz", true ) )
  110. tops.push_back ( new Haar3Horiz() );
  111. if ( conf->gB ( featsec, "haar3_vert", true ) )
  112. tops.push_back ( new Haar3Vert() );
  113. if ( conf->gB ( featsec, "haar3_stack", true ) )
  114. tops.push_back ( new Haar3Stack() );
  115. ops.push_back ( tops );
  116. ops.push_back ( tops );
  117. tops.clear();
  118. if ( conf->gB ( featsec, "minus", true ) )
  119. tops.push_back ( new Minus() );
  120. if ( conf->gB ( featsec, "minus_abs", true ) )
  121. tops.push_back ( new MinusAbs() );
  122. if ( conf->gB ( featsec, "addition", true ) )
  123. tops.push_back ( new Addition() );
  124. if ( conf->gB ( featsec, "only1", true ) )
  125. tops.push_back ( new Only1() );
  126. if ( conf->gB ( featsec, "rel_x", true ) )
  127. tops.push_back ( new RelativeXPosition() );
  128. if ( conf->gB ( featsec, "rel_y", true ) )
  129. tops.push_back ( new RelativeYPosition() );
  130. if ( conf->gB ( featsec, "rel_z", true ) )
  131. tops.push_back ( new RelativeZPosition() );
  132. ops.push_back ( tops );
  133. useGradient = conf->gB ( featsec, "use_gradient", true );
  134. useWeijer = conf->gB ( featsec, "use_weijer", true );
  135. useAdditionalLayer = conf->gB ( featsec, "use_additional_layer", false );
  136. useVariance = conf->gB ( featsec, "use_variance", false );
  137. // geometric features of hoiem
  138. useHoiemFeatures = conf->gB ( featsec, "use_hoiem_features", false );
  139. if ( useHoiemFeatures )
  140. {
  141. hoiemDirectory = conf->gS ( featsec, "hoiem_directory" );
  142. }
  143. opOverview = vector<int> ( NBOPERATIONS, 0 );
  144. contextOverview = vector<vector<double> > ( maxDepth, vector<double> ( 2, 0.0 ) );
  145. calcVal.push_back ( new MCImageAccess() );
  146. calcVal.push_back ( new MCImageAccess() );
  147. calcVal.push_back ( new MCImageAccess() );
  148. calcVal.push_back ( new MCImageAccess() );
  149. calcVal.push_back ( new ClassificationResultAccess() );
  150. classnames = md->getClassNames ( "train" );
  151. ///////////////////////////////////
  152. // Train Segmentation Context Trees
  153. ///////////////////////////////////
  154. if ( saveLoadData )
  155. {
  156. if ( FileMgt::fileExists ( fileLocation ) )
  157. read ( fileLocation );
  158. else
  159. {
  160. train ( md );
  161. write ( fileLocation );
  162. }
  163. }
  164. else
  165. {
  166. train ( md );
  167. }
  168. }
  169. SemSegContextTree::~SemSegContextTree()
  170. {
  171. }
  172. double SemSegContextTree::getBestSplit ( std::vector<NICE::MultiChannelImage3DT<double> > &feats, std::vector<NICE::MultiChannelImage3DT<unsigned short int> > &currentfeats, const std::vector<NICE::MultiChannelImageT<int> > &labels, int node, Operation *&splitop, double &splitval, const int &tree, vector<vector<vector<double> > > &regionProbs )
  173. {
  174. Timer t;
  175. t.start();
  176. int imgCount = 0;
  177. try
  178. {
  179. imgCount = ( int ) feats.size();
  180. }
  181. catch ( Exception )
  182. {
  183. cerr << "no features computed?" << endl;
  184. }
  185. double bestig = -numeric_limits< double >::max();
  186. splitop = NULL;
  187. splitval = -1.0;
  188. set<vector<int> >selFeats;
  189. map<int, int> e;
  190. int featcounter = forest[tree][node].featcounter;
  191. if ( featcounter < minFeats )
  192. {
  193. return 0.0;
  194. }
  195. vector<double> fraction ( a.size(), 0.0 );
  196. for ( uint i = 0; i < fraction.size(); i++ )
  197. {
  198. if ( forbidden_classes.find ( labelmapback[i] ) != forbidden_classes.end() )
  199. fraction[i] = 0;
  200. else
  201. fraction[i] = ( ( double ) maxSamples ) / ( ( double ) featcounter * a[i] * a.size() );
  202. }
  203. featcounter = 0;
  204. for ( int iCounter = 0; iCounter < imgCount; iCounter++ )
  205. {
  206. int xsize = ( int ) currentfeats[iCounter].width();
  207. int ysize = ( int ) currentfeats[iCounter].height();
  208. int zsize = ( int ) currentfeats[iCounter].depth();
  209. for ( int x = 0; x < xsize; x++ )
  210. {
  211. for ( int y = 0; y < ysize; y++ )
  212. {
  213. for ( int z = 0; z < zsize; z++ )
  214. {
  215. if ( currentfeats[iCounter].get ( x, y, z, tree ) == node )
  216. {
  217. int cn = labels[iCounter].get ( x, y, ( uint ) z );
  218. double randD = ( double ) rand() / ( double ) RAND_MAX;
  219. if ( labelmap.find ( cn ) == labelmap.end() )
  220. continue;
  221. if ( randD < fraction[labelmap[cn]] )
  222. {
  223. vector<int> tmp ( 4, 0 );
  224. tmp[0] = iCounter;
  225. tmp[1] = x;
  226. tmp[2] = y;
  227. tmp[3] = z;
  228. featcounter++;
  229. selFeats.insert ( tmp );
  230. e[cn]++;
  231. }
  232. }
  233. }
  234. }
  235. }
  236. }
  237. map<int, int>::iterator mapit;
  238. // global entropy
  239. double globent = 0.0;
  240. for ( mapit = e.begin() ; mapit != e.end(); mapit++ )
  241. {
  242. double p = ( double ) ( *mapit ).second / ( double ) featcounter;
  243. globent += p * log2 ( p );
  244. }
  245. globent = -globent;
  246. if ( globent < 0.5 )
  247. {
  248. return 0.0;
  249. }
  250. // vector of all possible features
  251. std::vector<Operation*> featsel;
  252. for ( int i = 0; i < featsPerSplit; i++ )
  253. {
  254. int x1, x2, y1, y2, z1, z2;
  255. int ft = ( int ) ( ( double ) rand() / ( double ) RAND_MAX * ( double ) ftypes );
  256. int tmpws = windowSize;
  257. if ( firstiteration )
  258. ft = 0;
  259. if ( channelsPerType[ft].size() == 0 )
  260. {
  261. ft = 0;
  262. }
  263. if ( ft > 1 )
  264. {
  265. //use larger window size for context features
  266. tmpws *= 3;
  267. }
  268. if ( ft == 1 )
  269. {
  270. if ( depth < 8 )
  271. {
  272. ft = 0;
  273. }
  274. }
  275. // random value range between (-window-size/2) and (window-size/2)
  276. double z_ratio = conf->gB ( "SSContextTree", "z_ratio", 1.0 );
  277. int tmp_z = ( int ) floor( (tmpws * z_ratio) + 0.5 );
  278. double y_ratio = conf->gB ( "SSContextTree", "y_ratio", 1.0 );
  279. int tmp_y = ( int ) floor( (tmpws * y_ratio) + 0.5 );
  280. x1 = ( int ) ( ( double ) rand() / ( double ) RAND_MAX * ( double ) tmpws ) - tmpws / 2;
  281. x2 = ( int ) ( ( double ) rand() / ( double ) RAND_MAX * ( double ) tmpws ) - tmpws / 2;
  282. y1 = ( int ) ( ( double ) rand() / ( double ) RAND_MAX * ( double ) tmp_y ) - tmp_y / 2;
  283. y2 = ( int ) ( ( double ) rand() / ( double ) RAND_MAX * ( double ) tmp_y ) - tmp_y / 2;
  284. z1 = ( int ) ( ( double ) rand() / ( double ) RAND_MAX * ( double ) tmp_z ) - tmp_z / 2;
  285. z2 = ( int ) ( ( double ) rand() / ( double ) RAND_MAX * ( double ) tmp_z ) - tmp_z / 2;
  286. int f1 = ( int ) ( ( double ) rand() / ( double ) RAND_MAX * ( double ) channelsPerType[ft].size() );
  287. int f2 = f1;
  288. if ( ( double ) rand() / ( double ) RAND_MAX > 0.5 )
  289. f2 = ( int ) ( ( double ) rand() / ( double ) RAND_MAX * ( double ) channelsPerType[ft].size() );
  290. int o = ( int ) ( ( double ) rand() / ( double ) RAND_MAX * ( double ) ops[ft].size() );
  291. f1 = channelsPerType[ft][f1];
  292. f2 = channelsPerType[ft][f2];
  293. if ( ft == 1 )
  294. {
  295. int classes = ( int ) regionProbs[0][0].size();
  296. f2 = ( int ) ( ( double ) rand() / ( double ) RAND_MAX * ( double ) classes );
  297. }
  298. // only depth-values in front of the current pixel are allowed
  299. bool z_negative_only = conf->gB ( "SSContextTree", "z_negative_only", false );
  300. if (z_negative_only)
  301. {
  302. z1 = -abs(z1);
  303. z2 = -abs(z2);
  304. }
  305. Operation *op = ops[ft][o]->clone();
  306. op->set ( x1, y1, z1, x2, y2, z2, f1, f2, calcVal[ft] );
  307. op->setFeatType ( ft );
  308. if ( ft == 3 || ft == 4 )
  309. op->setContext ( true );
  310. else
  311. op->setContext ( false );
  312. featsel.push_back ( op );
  313. }
  314. for ( int f = 0; f < featsPerSplit; f++ )
  315. {
  316. double l_bestig = -numeric_limits< double >::max();
  317. double l_splitval = -1.0;
  318. set<vector<int> >::iterator it;
  319. vector<double> vals;
  320. double maxval = -numeric_limits<double>::max();
  321. double minval = numeric_limits<double>::max();
  322. for ( it = selFeats.begin() ; it != selFeats.end(); it++ )
  323. {
  324. Features feat;
  325. feat.feats = &feats[ ( *it ) [0]];
  326. feat.cfeats = &currentfeats[ ( *it ) [0]];
  327. feat.cTree = tree;
  328. feat.tree = &forest[tree];
  329. assert ( forest.size() > ( uint ) tree );
  330. assert ( forest[tree][0].dist.size() > 0 );
  331. feat.rProbs = &regionProbs[ ( *it ) [0]];
  332. double val = featsel[f]->getVal ( feat, ( *it ) [1], ( *it ) [2], ( *it ) [3] );
  333. if ( !isfinite ( val ) )
  334. {
  335. //cerr << "feat " << feat.feats->width() << " " << feat.feats->height() << " " << feat.feats->depth() << endl;
  336. //cerr << "non finite value " << val << " for " << featsel[f]->writeInfos() << endl << (*it) [1] << " " << (*it) [2] << " " << (*it) [3] << endl;
  337. val = 0.0;
  338. }
  339. vals.push_back ( val );
  340. maxval = std::max ( val, maxval );
  341. minval = std::min ( val, minval );
  342. }
  343. if ( minval == maxval )
  344. continue;
  345. double scale = maxval - minval;
  346. vector<double> splits;
  347. for ( int r = 0; r < randomTests; r++ )
  348. {
  349. splits.push_back ( ( ( double ) rand() / ( double ) RAND_MAX*scale ) + minval );
  350. }
  351. for ( int run = 0 ; run < randomTests; run++ )
  352. {
  353. set<vector<int> >::iterator it2;
  354. double val = splits[run];
  355. map<int, int> eL, eR;
  356. int counterL = 0, counterR = 0;
  357. int counter2 = 0;
  358. for ( it2 = selFeats.begin() ; it2 != selFeats.end(); it2++, counter2++ )
  359. {
  360. int cn = labels[ ( *it2 ) [0]].get ( ( *it2 ) [1], ( *it2 ) [2], ( *it2 ) [3] );
  361. //cout << "vals[counter2] " << vals[counter2] << " val: " << val << endl;
  362. if ( vals[counter2] < val )
  363. {
  364. //left entropie:
  365. eL[cn] = eL[cn] + 1;
  366. counterL++;
  367. }
  368. else
  369. {
  370. //right entropie:
  371. eR[cn] = eR[cn] + 1;
  372. counterR++;
  373. }
  374. }
  375. double leftent = 0.0;
  376. for ( mapit = eL.begin() ; mapit != eL.end(); mapit++ )
  377. {
  378. double p = ( double ) ( *mapit ).second / ( double ) counterL;
  379. leftent -= p * log2 ( p );
  380. }
  381. double rightent = 0.0;
  382. for ( mapit = eR.begin() ; mapit != eR.end(); mapit++ )
  383. {
  384. double p = ( double ) ( *mapit ).second / ( double ) counterR;
  385. rightent -= p * log2 ( p );
  386. }
  387. //cout << "rightent: " << rightent << " leftent: " << leftent << endl;
  388. double pl = ( double ) counterL / ( double ) ( counterL + counterR );
  389. double ig = globent - ( 1.0 - pl ) * rightent - pl * leftent;
  390. //double ig = globent - rightent - leftent;
  391. if ( useShannonEntropy )
  392. {
  393. double esplit = - ( pl * log ( pl ) + ( 1 - pl ) * log ( 1 - pl ) );
  394. ig = 2 * ig / ( globent + esplit );
  395. }
  396. if ( ig > l_bestig )
  397. {
  398. l_bestig = ig;
  399. l_splitval = val;
  400. }
  401. }
  402. if ( l_bestig > bestig )
  403. {
  404. bestig = l_bestig;
  405. splitop = featsel[f];
  406. splitval = l_splitval;
  407. }
  408. }
  409. //FIXME: delete all features!
  410. /*for(int i = 0; i < featsPerSplit; i++)
  411. {
  412. if(featsel[i] != splitop)
  413. delete featsel[i];
  414. }*/
  415. #ifdef DEBUG
  416. //cout << "globent: " << globent << " bestig " << bestig << " splitval: " << splitval << endl;
  417. #endif
  418. return bestig;
  419. }
  420. inline double SemSegContextTree::getMeanProb ( const int &x, const int &y, const int &z, const int &channel, const MultiChannelImage3DT<unsigned short int> &currentfeats )
  421. {
  422. double val = 0.0;
  423. for ( int tree = 0; tree < nbTrees; tree++ )
  424. {
  425. val += forest[tree][currentfeats.get ( x,y,z,tree ) ].dist[channel];
  426. }
  427. return val / ( double ) nbTrees;
  428. }
  429. void SemSegContextTree::computeIntegralImage ( const NICE::MultiChannelImage3DT<unsigned short int> &currentfeats, NICE::MultiChannelImage3DT<double> &feats, int firstChannel )
  430. {
  431. int xsize = feats.width();
  432. int ysize = feats.height();
  433. int zsize = feats.depth();
  434. if ( firstiteration )
  435. {
  436. #pragma omp parallel for
  437. for ( int it = 0; it < ( int ) integralMap.size(); it++ )
  438. {
  439. int corg = integralMap[it].first;
  440. int cint = integralMap[it].second;
  441. for ( int z = 0; z < zsize; z++ )
  442. {
  443. for ( int y = 0; y < ysize; y++ )
  444. {
  445. for ( int x = 0; x < xsize; x++ )
  446. {
  447. feats ( x, y, z, cint ) = feats ( x, y, z, corg );
  448. }
  449. }
  450. }
  451. feats.calcIntegral ( cint );
  452. }
  453. }
  454. int channels = ( int ) forest[0][0].dist.size();
  455. #pragma omp parallel for
  456. for ( int c = 0; c < channels; c++ )
  457. {
  458. feats ( 0, 0, 0, firstChannel + c ) = getMeanProb ( 0, 0, 0, c, currentfeats );
  459. //first column
  460. for ( int y = 1; y < ysize; y++ )
  461. {
  462. feats ( 0, y, 0, firstChannel + c ) = getMeanProb ( 0, y, 0, c, currentfeats )
  463. + feats ( 0, y - 1, 0, firstChannel + c );
  464. }
  465. //first row
  466. for ( int x = 1; x < xsize; x++ )
  467. {
  468. feats ( x, 0, 0, firstChannel + c ) = getMeanProb ( x, 0, 0, c, currentfeats )
  469. + feats ( x - 1, 0, 0, firstChannel + c );
  470. }
  471. //first stack
  472. for ( int z = 1; z < zsize; z++ )
  473. {
  474. feats ( 0, 0, z, firstChannel + c ) = getMeanProb ( 0, 0, z, c, currentfeats )
  475. + feats ( 0, 0, z - 1, firstChannel + c );
  476. }
  477. //x-y plane
  478. for ( int y = 1; y < ysize; y++ )
  479. {
  480. for ( int x = 1; x < xsize; x++ )
  481. {
  482. feats ( x, y, 0, firstChannel + c ) = getMeanProb ( x, y, 0, c, currentfeats )
  483. + feats ( x, y - 1, 0, firstChannel + c )
  484. + feats ( x - 1, y, 0, firstChannel + c )
  485. - feats ( x - 1, y - 1, 0, firstChannel + c );
  486. }
  487. }
  488. //y-z plane
  489. for ( int z = 1; z < zsize; z++ )
  490. {
  491. for ( int y = 1; y < ysize; y++ )
  492. {
  493. feats ( 0, y, z, firstChannel + c ) = getMeanProb ( 0, y, z, c, currentfeats )
  494. + feats ( 0, y - 1, z, firstChannel + c )
  495. + feats ( 0, y, z - 1, firstChannel + c )
  496. - feats ( 0, y - 1, z - 1, firstChannel + c );
  497. }
  498. }
  499. //x-z plane
  500. for ( int z = 1; z < zsize; z++ )
  501. {
  502. for ( int x = 1; x < xsize; x++ )
  503. {
  504. feats ( x, 0, z, firstChannel + c ) = getMeanProb ( x, 0, z, c, currentfeats )
  505. + feats ( x - 1, 0, z, firstChannel + c )
  506. + feats ( x, 0, z - 1, firstChannel + c )
  507. - feats ( x - 1, 0, z - 1, firstChannel + c );
  508. }
  509. }
  510. //rest
  511. for ( int z = 1; z < zsize; z++ )
  512. {
  513. for ( int y = 1; y < ysize; y++ )
  514. {
  515. for ( int x = 1; x < xsize; x++ )
  516. {
  517. feats ( x, y, z, firstChannel + c ) = getMeanProb ( x, y, z, c, currentfeats )
  518. + feats ( x - 1, y, z, firstChannel + c )
  519. + feats ( x, y - 1, z, firstChannel + c )
  520. + feats ( x, y, z - 1, firstChannel + c )
  521. + feats ( x - 1, y - 1, z - 1, firstChannel + c )
  522. - feats ( x - 1, y - 1, z, firstChannel + c )
  523. - feats ( x - 1, y, z - 1, firstChannel + c )
  524. - feats ( x, y - 1, z - 1, firstChannel + c );
  525. }
  526. }
  527. }
  528. }
  529. }
  530. inline double computeWeight ( const double &d, const double &dim )
  531. {
  532. return 1.0 / ( pow ( 2, ( double ) ( dim - d + 1 ) ) );
  533. }
  534. void SemSegContextTree::train ( const MultiDataset *md )
  535. {
  536. int shortsize = numeric_limits<short>::max();
  537. Timer timer;
  538. timer.start();
  539. const LabeledSet train = * ( *md ) ["train"];
  540. const LabeledSet *trainp = &train;
  541. vector<int> zsizeVec;
  542. getDepthVector ( &train, zsizeVec );
  543. bool run_3dseg = conf->gB ( "debug", "run_3dseg", true );
  544. ProgressBar pb ( "compute feats" );
  545. pb.show();
  546. //TODO: Speichefresser!, lohnt sich sparse?
  547. vector<MultiChannelImage3DT<double> > allfeats;
  548. vector<MultiChannelImage3DT<unsigned short int> > currentfeats;
  549. vector<MultiChannelImageT<int> > labels;
  550. vector<SparseVector*> globalCategorFeats;
  551. vector<map<int,int> > classesPerImage;
  552. std::string forbidden_classes_s = conf->gS ( "analysis", "donttrain", "" );
  553. vector<vector<vector<double> > > regionProbs;
  554. vector<vector<int> > rSize;
  555. vector<int> amountRegionpI;
  556. if ( forbidden_classes_s == "" )
  557. {
  558. forbidden_classes_s = conf->gS ( "analysis", "forbidden_classes", "" );
  559. }
  560. classnames.getSelection ( forbidden_classes_s, forbidden_classes );
  561. int imgcounter = 0;
  562. int amountPixels = 0;
  563. ////////////////////////////////////////////////////
  564. //define which featurextraction methods should be used for each channel
  565. if ( imagetype == IMAGETYPE_RGB )
  566. {
  567. rawChannels = 3;
  568. }
  569. else
  570. {
  571. rawChannels = 1;
  572. }
  573. // how many channels without integral image
  574. int shift = 0;
  575. if ( useGradient )
  576. rawChannels *= 2;
  577. if ( useWeijer )
  578. rawChannels += 11;
  579. if ( useHoiemFeatures )
  580. rawChannels += 8;
  581. if ( useAdditionalLayer )
  582. rawChannels += 1;
  583. if ( useVariance )
  584. rawChannels += 1;
  585. // gray value images
  586. for ( int i = 0; i < rawChannels; i++ )
  587. {
  588. channelType.push_back ( 0 );
  589. }
  590. // regions
  591. if ( useRegionFeature )
  592. {
  593. channelType.push_back ( 1 );
  594. shift++;
  595. }
  596. ///////////////////////////// read input data /////////////////////////////////
  597. ///////////////////////////////////////////////////////////////////////////////
  598. int depthCount = 0;
  599. vector< string > filelist;
  600. NICE::MultiChannelImageT<uchar> pixelLabels;
  601. LOOP_ALL_S ( *trainp )
  602. {
  603. EACH_INFO ( classno, info );
  604. std::string file = info.img();
  605. filelist.push_back ( file );
  606. depthCount++;
  607. const LocalizationResult *locResult = info.localization();
  608. // getting groundtruth
  609. NICE::Image pL;
  610. pL.resize ( locResult->xsize, locResult->ysize );
  611. pL.set ( 0 );
  612. locResult->calcLabeledImage ( pL, ( *classNames ).getBackgroundClass() );
  613. pixelLabels.addChannel ( pL );
  614. if ( locResult->size() <= 0 )
  615. {
  616. fprintf ( stderr, "WARNING: NO ground truth polygons found for %s !\n",
  617. file.c_str() );
  618. continue;
  619. }
  620. fprintf ( stderr, "SSContext: Collecting pixel examples from localization info: %s\n", file.c_str() );
  621. int depthBoundary = 0;
  622. if ( run_3dseg )
  623. {
  624. depthBoundary = zsizeVec[imgcounter];
  625. }
  626. if ( depthCount < depthBoundary ) continue;
  627. // all image slices collected -> make a 3d image
  628. NICE::MultiChannelImage3DT<double> imgData;
  629. make3DImage ( filelist, imgData );
  630. int xsize = imgData.width();
  631. int ysize = imgData.height();
  632. int zsize = imgData.depth();
  633. amountPixels += xsize * ysize * zsize;
  634. MultiChannelImageT<int> tmpMat ( xsize, ysize, ( uint ) zsize );
  635. labels.push_back ( tmpMat );
  636. currentfeats.push_back ( MultiChannelImage3DT<unsigned short int> ( xsize, ysize, zsize, nbTrees ) );
  637. currentfeats[imgcounter].setAll ( 0 );
  638. //TODO: resize image?!
  639. MultiChannelImage3DT<double> feats;
  640. allfeats.push_back ( feats );
  641. int amountRegions;
  642. // read image and do some simple transformations
  643. extractBasicFeatures ( allfeats[imgcounter], imgData, filelist, amountRegions );
  644. if ( useRegionFeature )
  645. {
  646. amountRegionpI.push_back ( amountRegions );
  647. rSize.push_back ( vector<int> ( amountRegions, 0 ) );
  648. for ( int z = 0; z < zsize; z++ )
  649. {
  650. for ( int y = 0; y < ysize; y++ )
  651. {
  652. for ( int x = 0; x < xsize; x++ )
  653. {
  654. rSize[imgcounter][allfeats[imgcounter] ( x, y, z, rawChannels ) ]++;
  655. }
  656. }
  657. }
  658. }
  659. for ( int x = 0; x < xsize; x++ )
  660. {
  661. for ( int y = 0; y < ysize; y++ )
  662. {
  663. for ( int z = 0; z < zsize; z++ )
  664. {
  665. if ( run_3dseg )
  666. classno = pixelLabels ( x, y, ( uint ) z );
  667. else
  668. classno = pL.getPixelQuick ( x,y );
  669. labels[imgcounter].set ( x, y, classno, ( uint ) z );
  670. if ( forbidden_classes.find ( classno ) != forbidden_classes.end() )
  671. continue;
  672. labelcounter[classno]++;
  673. }
  674. }
  675. }
  676. if ( useCategorization )
  677. {
  678. globalCategorFeats.push_back ( new SparseVector() );
  679. classesPerImage.push_back ( map<int,int>() );
  680. for ( int x = 0; x < xsize; x++ )
  681. {
  682. for ( int y = 0; y < ysize; y++ )
  683. {
  684. for ( int z = 0; z < zsize; z++ )
  685. {
  686. if ( run_3dseg )
  687. classno = pixelLabels ( x, y, ( uint ) z );
  688. else
  689. classno = pL.getPixelQuick ( x,y );
  690. if ( forbidden_classes.find ( classno ) != forbidden_classes.end() )
  691. continue;
  692. classesPerImage[imgcounter][classno] = 1;
  693. }
  694. }
  695. }
  696. }
  697. pb.update ( trainp->count() );
  698. filelist.clear();
  699. pixelLabels.reInit ( 0,0,0 );
  700. depthCount = 0;
  701. imgcounter++;
  702. }
  703. pb.hide();
  704. map<int, int>::iterator mapit;
  705. int classes = 0;
  706. for ( mapit = labelcounter.begin(); mapit != labelcounter.end(); mapit++ )
  707. {
  708. labelmap[mapit->first] = classes;
  709. labelmapback[classes] = mapit->first;
  710. classes++;
  711. }
  712. //////////////////////////// channel configuration ////////////////////////////
  713. ///////////////////////////////////////////////////////////////////////////////
  714. for ( int i = 0; i < rawChannels; i++ )
  715. {
  716. channelType.push_back ( 2 );
  717. }
  718. // integral images
  719. for ( int i = 0; i < classes; i++ )
  720. {
  721. channelType.push_back ( 3 );
  722. }
  723. integralMap.clear();
  724. for ( int i = 0; i < rawChannels; i++ )
  725. {
  726. integralMap.push_back ( pair<int, int> ( i, i + rawChannels + shift ) );
  727. }
  728. int amountTypes = 5;
  729. channelsPerType = vector<vector<int> > ( amountTypes, vector<int>() );
  730. for ( int i = 0; i < ( int ) channelType.size(); i++ )
  731. {
  732. channelsPerType[channelType[i]].push_back ( i );
  733. }
  734. for ( int i = 0; i < classes; i++ )
  735. {
  736. channelsPerType[channelsPerType.size()-1].push_back ( i );
  737. }
  738. ftypes = std::min ( amountTypes, ftypes );
  739. ///////////////////////////////////////////////////////////////////////////////
  740. ///////////////////////////////////////////////////////////////////////////////
  741. if ( useRegionFeature )
  742. {
  743. for ( int a = 0; a < ( int ) amountRegionpI.size(); a++ )
  744. {
  745. regionProbs.push_back ( vector<vector<double> > ( amountRegionpI[a], vector<double> ( classes, 0.0 ) ) );
  746. }
  747. }
  748. //balancing
  749. int featcounter = 0;
  750. a = vector<double> ( classes, 0.0 );
  751. for ( int iCounter = 0; iCounter < imgcounter; iCounter++ )
  752. {
  753. int xsize = ( int ) currentfeats[iCounter].width();
  754. int ysize = ( int ) currentfeats[iCounter].height();
  755. int zsize = ( int ) currentfeats[iCounter].depth();
  756. for ( int x = 0; x < xsize; x++ )
  757. {
  758. for ( int y = 0; y < ysize; y++ )
  759. {
  760. for ( int z = 0; z < zsize; z++ )
  761. {
  762. featcounter++;
  763. int cn = labels[iCounter] ( x, y, ( uint ) z );
  764. if ( labelmap.find ( cn ) == labelmap.end() )
  765. continue;
  766. a[labelmap[cn]] ++;
  767. }
  768. }
  769. }
  770. }
  771. for ( int i = 0; i < ( int ) a.size(); i++ )
  772. {
  773. a[i] /= ( double ) featcounter;
  774. }
  775. #ifdef DEBUG
  776. for ( int i = 0; i < ( int ) a.size(); i++ )
  777. {
  778. cout << "a[" << i << "]: " << a[i] << endl;
  779. }
  780. cout << "a.size: " << a.size() << endl;
  781. #endif
  782. depth = 0;
  783. uniquenumber = 0;
  784. for ( int t = 0; t < nbTrees; t++ )
  785. {
  786. vector<TreeNode> singletree;
  787. singletree.push_back ( TreeNode() );
  788. singletree[0].dist = vector<double> ( classes, 0.0 );
  789. singletree[0].depth = depth;
  790. singletree[0].featcounter = amountPixels;
  791. singletree[0].nodeNumber = uniquenumber;
  792. uniquenumber++;
  793. forest.push_back ( singletree );
  794. }
  795. vector<int> startnode ( nbTrees, 0 );
  796. bool allleaf = false;
  797. //int baseFeatSize = allfeats[0].size();
  798. timer.stop();
  799. cerr << "preprocessing finished in: " << timer.getLastAbsolute() << " seconds" << endl;
  800. timer.start();
  801. while ( !allleaf && depth < maxDepth )
  802. {
  803. depth++;
  804. #ifdef DEBUG
  805. cout << "depth: " << depth << endl;
  806. #endif
  807. allleaf = true;
  808. vector<MultiChannelImage3DT<unsigned short int> > lastfeats = currentfeats;
  809. vector<vector<vector<double> > > lastRegionProbs = regionProbs;
  810. if ( useRegionFeature )
  811. {
  812. int a_max = ( int ) regionProbs.size();
  813. for ( int a = 0; a < a_max; a++ )
  814. {
  815. int b_max = ( int ) regionProbs[a].size();
  816. for ( int b = 0; b < b_max; b++ )
  817. {
  818. int c_max = ( int ) regionProbs[a][b].size();
  819. for ( int c = 0; c < c_max; c++ )
  820. {
  821. regionProbs[a][b][c] = 0.0;
  822. }
  823. }
  824. }
  825. }
  826. #if 1
  827. Timer timerDepth;
  828. timerDepth.start();
  829. #endif
  830. double weight = computeWeight ( depth, maxDepth ) - computeWeight ( depth - 1, maxDepth );
  831. if ( depth == 1 )
  832. {
  833. weight = computeWeight ( 1, maxDepth );
  834. }
  835. // omp_set_dynamic(0);
  836. #pragma omp parallel for
  837. for ( int tree = 0; tree < nbTrees; tree++ )
  838. {
  839. const int t = ( int ) forest[tree].size();
  840. const int s = startnode[tree];
  841. startnode[tree] = t;
  842. //#pragma omp parallel for
  843. for ( int i = s; i < t; i++ )
  844. {
  845. if ( !forest[tree][i].isleaf && forest[tree][i].left < 0 )
  846. {
  847. Operation *splitfeat = NULL;
  848. double splitval;
  849. double bestig = getBestSplit ( allfeats, lastfeats, labels, i, splitfeat, splitval, tree, lastRegionProbs );
  850. for ( int ii = 0; ii < ( int ) lastfeats.size(); ii++ )
  851. {
  852. for ( int c = 0; c < lastfeats[ii].channels(); c++ )
  853. {
  854. short unsigned int minv, maxv;
  855. lastfeats[ii].statistics ( minv, maxv, c );
  856. }
  857. }
  858. forest[tree][i].feat = splitfeat;
  859. forest[tree][i].decision = splitval;
  860. if ( splitfeat != NULL )
  861. {
  862. allleaf = false;
  863. int left;
  864. #pragma omp critical
  865. {
  866. left = forest[tree].size();
  867. forest[tree].push_back ( TreeNode() );
  868. forest[tree].push_back ( TreeNode() );
  869. }
  870. int right = left + 1;
  871. forest[tree][i].left = left;
  872. forest[tree][i].right = right;
  873. forest[tree][left].dist = vector<double> ( classes, 0.0 );
  874. forest[tree][right].dist = vector<double> ( classes, 0.0 );
  875. forest[tree][left].depth = depth;
  876. forest[tree][right].depth = depth;
  877. forest[tree][left].featcounter = 0;
  878. forest[tree][right].featcounter = 0;
  879. forest[tree][left].nodeNumber = uniquenumber;
  880. int leftu = uniquenumber;
  881. uniquenumber++;
  882. forest[tree][right].nodeNumber = uniquenumber;
  883. int rightu = uniquenumber;
  884. uniquenumber++;
  885. forest[tree][right].featcounter = 0;
  886. #pragma omp parallel for
  887. for ( int iCounter = 0; iCounter < imgcounter; iCounter++ )
  888. {
  889. int xsize = currentfeats[iCounter].width();
  890. int ysize = currentfeats[iCounter].height();
  891. int zsize = currentfeats[iCounter].depth();
  892. for ( int x = 0; x < xsize; x++ )
  893. {
  894. for ( int y = 0; y < ysize; y++ )
  895. {
  896. for ( int z = 0; z < zsize; z++ )
  897. {
  898. if ( currentfeats[iCounter].get ( x, y, z, tree ) == i )
  899. {
  900. Features feat;
  901. feat.feats = &allfeats[iCounter];
  902. feat.cfeats = &lastfeats[iCounter];
  903. feat.cTree = tree;
  904. feat.tree = &forest[tree];
  905. feat.rProbs = &lastRegionProbs[iCounter];
  906. double val = splitfeat->getVal ( feat, x, y, z );
  907. if ( !isfinite ( val ) )
  908. {
  909. val = 0.0;
  910. }
  911. #pragma omp critical
  912. if ( val < splitval )
  913. {
  914. currentfeats[iCounter].set ( x, y, z, left, tree );
  915. if ( labelmap.find ( labels[iCounter] ( x, y, ( uint ) z ) ) != labelmap.end() )
  916. forest[tree][left].dist[labelmap[labels[iCounter] ( x, y, ( uint ) z ) ]]++;
  917. forest[tree][left].featcounter++;
  918. if ( useCategorization && leftu < shortsize )
  919. ( *globalCategorFeats[iCounter] ) [leftu]+=weight;
  920. }
  921. else
  922. {
  923. currentfeats[iCounter].set ( x, y, z, right, tree );
  924. if ( labelmap.find ( labels[iCounter] ( x, y, ( uint ) z ) ) != labelmap.end() )
  925. forest[tree][right].dist[labelmap[labels[iCounter] ( x, y, ( uint ) z ) ]]++;
  926. forest[tree][right].featcounter++;
  927. if ( useCategorization && rightu < shortsize )
  928. ( *globalCategorFeats[iCounter] ) [rightu]+=weight;
  929. }
  930. }
  931. }
  932. }
  933. }
  934. }
  935. double lcounter = 0.0, rcounter = 0.0;
  936. for ( uint d = 0; d < forest[tree][left].dist.size(); d++ )
  937. {
  938. if ( forbidden_classes.find ( labelmapback[d] ) != forbidden_classes.end() )
  939. {
  940. forest[tree][left].dist[d] = 0;
  941. forest[tree][right].dist[d] = 0;
  942. }
  943. else
  944. {
  945. forest[tree][left].dist[d] /= a[d];
  946. lcounter += forest[tree][left].dist[d];
  947. forest[tree][right].dist[d] /= a[d];
  948. rcounter += forest[tree][right].dist[d];
  949. }
  950. }
  951. if ( lcounter <= 0 || rcounter <= 0 )
  952. {
  953. cout << "lcounter : " << lcounter << " rcounter: " << rcounter << endl;
  954. cout << "splitval: " << splitval << " splittype: " << splitfeat->writeInfos() << endl;
  955. cout << "bestig: " << bestig << endl;
  956. for ( int iCounter = 0; iCounter < imgcounter; iCounter++ )
  957. {
  958. int xsize = currentfeats[iCounter].width();
  959. int ysize = currentfeats[iCounter].height();
  960. int zsize = currentfeats[iCounter].depth();
  961. int counter = 0;
  962. for ( int x = 0; x < xsize; x++ )
  963. {
  964. for ( int y = 0; y < ysize; y++ )
  965. {
  966. for ( int z = 0; z < zsize; z++ )
  967. {
  968. if ( lastfeats[iCounter].get ( x, y, tree ) == i )
  969. {
  970. if ( ++counter > 30 )
  971. break;
  972. Features feat;
  973. feat.feats = &allfeats[iCounter];
  974. feat.cfeats = &lastfeats[iCounter];
  975. feat.cTree = tree;
  976. feat.tree = &forest[tree];
  977. feat.rProbs = &lastRegionProbs[iCounter];
  978. double val = splitfeat->getVal ( feat, x, y, z );
  979. if ( !isfinite ( val ) )
  980. {
  981. val = 0.0;
  982. }
  983. cout << "splitval: " << splitval << " val: " << val << endl;
  984. }
  985. }
  986. }
  987. }
  988. }
  989. assert ( lcounter > 0 && rcounter > 0 );
  990. }
  991. for ( uint d = 0; d < forest[tree][left].dist.size(); d++ )
  992. {
  993. forest[tree][left].dist[d] /= lcounter;
  994. forest[tree][right].dist[d] /= rcounter;
  995. }
  996. }
  997. else
  998. {
  999. forest[tree][i].isleaf = true;
  1000. }
  1001. }
  1002. }
  1003. }
  1004. if ( useRegionFeature )
  1005. {
  1006. for ( int iCounter = 0; iCounter < imgcounter; iCounter++ )
  1007. {
  1008. int xsize = currentfeats[iCounter].width();
  1009. int ysize = currentfeats[iCounter].height();
  1010. int zsize = currentfeats[iCounter].depth();
  1011. #pragma omp parallel for
  1012. for ( int x = 0; x < xsize; x++ )
  1013. {
  1014. for ( int y = 0; y < ysize; y++ )
  1015. {
  1016. for ( int z = 0; z < zsize; z++ )
  1017. {
  1018. for ( int tree = 0; tree < nbTrees; tree++ )
  1019. {
  1020. int node = currentfeats[iCounter].get ( x, y, z, tree );
  1021. for ( uint d = 0; d < forest[tree][node].dist.size(); d++ )
  1022. {
  1023. regionProbs[iCounter][ ( int ) ( allfeats[iCounter] ( x, y, z, rawChannels ) ) ][d] += forest[tree][node].dist[d];
  1024. }
  1025. }
  1026. }
  1027. }
  1028. }
  1029. }
  1030. int a_max = ( int ) regionProbs.size();
  1031. for ( int a = 0; a < a_max; a++ )
  1032. {
  1033. int b_max = ( int ) regionProbs[a].size();
  1034. for ( int b = 0; b < b_max; b++ )
  1035. {
  1036. int c_max = ( int ) regionProbs[a][b].size();
  1037. for ( int c = 0; c < c_max; c++ )
  1038. {
  1039. regionProbs[a][b][c] /= ( double ) ( rSize[a][b] );
  1040. }
  1041. }
  1042. }
  1043. }
  1044. //compute integral images
  1045. if ( firstiteration )
  1046. {
  1047. for ( int i = 0; i < imgcounter; i++ )
  1048. {
  1049. allfeats[i].addChannel ( ( int ) ( classes + rawChannels ) );
  1050. }
  1051. }
  1052. for ( int i = 0; i < imgcounter; i++ )
  1053. {
  1054. computeIntegralImage ( currentfeats[i], allfeats[i], channelType.size() - classes );
  1055. }
  1056. if ( firstiteration )
  1057. {
  1058. firstiteration = false;
  1059. }
  1060. #if 1
  1061. timerDepth.stop();
  1062. cout << "time for depth " << depth << ": " << timerDepth.getLastAbsolute() << endl;
  1063. #endif
  1064. lastfeats.clear();
  1065. lastRegionProbs.clear();
  1066. }
  1067. timer.stop();
  1068. cerr << "learning finished in: " << timer.getLastAbsolute() << " seconds" << endl;
  1069. timer.start();
  1070. cout << "uniquenumber " << uniquenumber << endl;
  1071. if ( useCategorization && fasthik != NULL )
  1072. {
  1073. uniquenumber = std::min ( shortsize, uniquenumber );
  1074. for ( uint i = 0; i < globalCategorFeats.size(); i++ )
  1075. {
  1076. globalCategorFeats[i]->setDim ( uniquenumber );
  1077. globalCategorFeats[i]->normalize();
  1078. }
  1079. map<int,Vector> ys;
  1080. int cCounter = 0;
  1081. for ( map<int,int>::iterator it = labelmap.begin(); it != labelmap.end(); it++, cCounter++ )
  1082. {
  1083. ys[cCounter] = Vector ( globalCategorFeats.size() );
  1084. for ( int i = 0; i < imgcounter; i++ )
  1085. {
  1086. if ( classesPerImage[i].find ( it->first ) != classesPerImage[i].end() )
  1087. {
  1088. ys[cCounter][i] = 1;
  1089. }
  1090. else
  1091. {
  1092. ys[cCounter][i] = -1;
  1093. }
  1094. }
  1095. }
  1096. fasthik->train ( globalCategorFeats, ys );
  1097. }
  1098. #ifdef DEBUG
  1099. for ( int tree = 0; tree < nbTrees; tree++ )
  1100. {
  1101. int t = ( int ) forest[tree].size();
  1102. for ( int i = 0; i < t; i++ )
  1103. {
  1104. printf ( "tree[%i]: left: %i, right: %i", i, forest[tree][i].left, forest[tree][i].right );
  1105. if ( !forest[tree][i].isleaf && forest[tree][i].left != -1 )
  1106. {
  1107. cout << ", feat: " << forest[tree][i].feat->writeInfos() << " ";
  1108. opOverview[forest[tree][i].feat->getOps() ]++;
  1109. contextOverview[forest[tree][i].depth][ ( int ) forest[tree][i].feat->getContext() ]++;
  1110. }
  1111. for ( int d = 0; d < ( int ) forest[tree][i].dist.size(); d++ )
  1112. {
  1113. cout << " " << forest[tree][i].dist[d];
  1114. }
  1115. cout << endl;
  1116. }
  1117. }
  1118. std::map<int, int> featTypeCounter;
  1119. for ( int tree = 0; tree < nbTrees; tree++ )
  1120. {
  1121. int t = ( int ) forest[tree].size();
  1122. for ( int i = 0; i < t; i++ )
  1123. {
  1124. if ( !forest[tree][i].isleaf && forest[tree][i].left != -1 )
  1125. {
  1126. featTypeCounter[forest[tree][i].feat->getFeatType() ] += 1;
  1127. }
  1128. }
  1129. }
  1130. cout << "evaluation of featuretypes" << endl;
  1131. for ( map<int, int>::const_iterator it = featTypeCounter.begin(); it != featTypeCounter.end(); it++ )
  1132. {
  1133. cerr << it->first << ": " << it->second << endl;
  1134. }
  1135. for ( uint c = 0; c < ops.size(); c++ )
  1136. {
  1137. for ( int t = 0; t < ( int ) ops[c].size(); t++ )
  1138. {
  1139. cout << ops[c][t]->writeInfos() << ": " << opOverview[ops[c][t]->getOps() ] << endl;
  1140. }
  1141. }
  1142. for ( int d = 0; d < maxDepth; d++ )
  1143. {
  1144. double sum = contextOverview[d][0] + contextOverview[d][1];
  1145. if ( sum == 0 )
  1146. sum = 1;
  1147. contextOverview[d][0] /= sum;
  1148. contextOverview[d][1] /= sum;
  1149. cout << "depth: " << d << " woContext: " << contextOverview[d][0] << " wContext: " << contextOverview[d][1] << endl;
  1150. }
  1151. #endif
  1152. timer.stop();
  1153. cerr << "rest finished in: " << timer.getLastAbsolute() << " seconds" << endl;
  1154. timer.start();
  1155. }
  1156. void SemSegContextTree::extractBasicFeatures ( NICE::MultiChannelImage3DT<double> &feats, const NICE::MultiChannelImage3DT<double> &imgData, const vector<string> &filelist, int &amountRegions )
  1157. {
  1158. int xsize = imgData.width();
  1159. int ysize = imgData.height();
  1160. int zsize = imgData.depth();
  1161. //TODO: resize image?!
  1162. amountRegions = 0;
  1163. feats.reInit ( xsize, ysize, zsize, imgData.channels() );
  1164. feats.setAll ( 0 );
  1165. for ( int z = 0; z < zsize; z++ )
  1166. {
  1167. NICE::MultiChannelImageT<double> feats_tmp;
  1168. feats_tmp.reInit ( xsize, ysize, 3 );
  1169. if ( imagetype == IMAGETYPE_RGB )
  1170. {
  1171. NICE::ColorImage img = imgData.getColor ( z );
  1172. for ( int x = 0; x < xsize; x++ )
  1173. {
  1174. for ( int y = 0; y < ysize; y++ )
  1175. {
  1176. for ( int r = 0; r < 3; r++ )
  1177. {
  1178. feats_tmp.set ( x, y, img.getPixel ( x, y, r ), ( uint ) r );
  1179. }
  1180. }
  1181. }
  1182. }
  1183. else
  1184. {
  1185. NICE::ImageT<double> img = imgData.getChannelT ( z,0 );
  1186. for ( int x = 0; x < xsize; x++ )
  1187. {
  1188. for ( int y = 0; y < ysize; y++ )
  1189. {
  1190. feats_tmp.set ( x, y, img.getPixel ( x, y ), 0 );
  1191. }
  1192. }
  1193. }
  1194. if ( imagetype == IMAGETYPE_RGB )
  1195. feats_tmp = ColorSpace::rgbtolab ( feats_tmp );
  1196. for ( int x = 0; x < xsize; x++ )
  1197. {
  1198. for ( int y = 0; y < ysize; y++ )
  1199. {
  1200. if ( imagetype == IMAGETYPE_RGB )
  1201. {
  1202. for ( uint r = 0; r < 3; r++ )
  1203. {
  1204. feats.set ( x, y, z, feats_tmp.get ( x, y, r ), r );
  1205. }
  1206. }
  1207. else
  1208. {
  1209. feats.set ( x, y, z, feats_tmp.get ( x, y, 0 ), 0 );
  1210. }
  1211. }
  1212. }
  1213. if ( useGradient )
  1214. {
  1215. int currentsize = feats_tmp.channels();
  1216. feats_tmp.addChannel ( currentsize );
  1217. for ( int c = 0; c < currentsize; c++ )
  1218. {
  1219. ImageT<double> tmp = feats_tmp[c];
  1220. ImageT<double> tmp2 = feats_tmp[c+currentsize];
  1221. NICE::FilterT<double, double, double>::gradientStrength ( tmp, tmp2 );
  1222. }
  1223. }
  1224. if ( useWeijer )
  1225. {
  1226. if ( imagetype == IMAGETYPE_RGB )
  1227. {
  1228. NICE::ColorImage img = imgData.getColor ( z );
  1229. NICE::MultiChannelImageT<double> cfeats;
  1230. lfcw->getFeats ( img, cfeats );
  1231. feats_tmp.addChannel ( cfeats );
  1232. }
  1233. else
  1234. {
  1235. cerr << "Can't compute weijer features of a grayscale image." << endl;
  1236. }
  1237. }
  1238. if ( useAdditionalLayer )
  1239. {
  1240. vector<string> list;
  1241. StringTools::split ( filelist[z], '/', list );
  1242. string layerPath = StringTools::trim ( filelist[z], list.back() ) + "addlayer/" + list.back();
  1243. NICE::Image layer ( layerPath );
  1244. feats_tmp.addChannel ( layer );
  1245. //cout << "Added file " << layerPath << " to feature stack " << endl;
  1246. }
  1247. // read the geometric cues produced by Hoiem et al.
  1248. if ( useHoiemFeatures )
  1249. {
  1250. // we could also give the following set as a config option
  1251. string hoiemClasses_s = "sky 000 090-045 090-090 090-135 090 090-por 090-sol";
  1252. vector<string> hoiemClasses;
  1253. StringTools::split ( hoiemClasses_s, ' ', hoiemClasses );
  1254. // Now we have to do some fancy regular expressions :)
  1255. // Original image filename: basel_000083.jpg
  1256. // hoiem result: basel_000083_c_sky.png
  1257. // Fancy class of Ferid which supports string handling especially for filenames
  1258. FileName fn ( filelist[z] );
  1259. fn.removeExtension();
  1260. FileName fnBase = fn.extractFileName();
  1261. // counter for the channel index, starts with the current size of the destination multi-channel image
  1262. int currentChannel = feats_tmp.channels();
  1263. // add a channel for each feature in advance
  1264. feats_tmp.addChannel ( hoiemClasses.size() );
  1265. // loop through all geometric categories and add the images
  1266. for ( vector<string>::const_iterator i = hoiemClasses.begin(); i != hoiemClasses.end(); i++, currentChannel++ )
  1267. {
  1268. string hoiemClass = *i;
  1269. FileName fnConfidenceImage ( hoiemDirectory + fnBase.str() + "_c_" + hoiemClass + ".png" );
  1270. if ( ! fnConfidenceImage.fileExists() )
  1271. {
  1272. fthrow ( Exception, "Unable to read the Hoiem geometric confidence image: " << fnConfidenceImage.str() << " (original image is " << filelist[z] << ")" );
  1273. }
  1274. else
  1275. {
  1276. Image confidenceImage ( fnConfidenceImage.str() );
  1277. // check whether the image size is consistent
  1278. if ( confidenceImage.width() != feats_tmp.width() || confidenceImage.height() != feats_tmp.height() )
  1279. {
  1280. fthrow ( Exception, "The size of the geometric confidence image does not match with the original image size: " << fnConfidenceImage.str() );
  1281. }
  1282. ImageT<double> dst = feats_tmp[currentChannel];
  1283. // copy standard image to double image
  1284. for ( uint y = 0 ; y < ( uint ) confidenceImage.height(); y++ )
  1285. for ( uint x = 0 ; x < ( uint ) confidenceImage.width(); x++ )
  1286. feats_tmp ( x, y, currentChannel ) = ( double ) confidenceImage ( x, y );
  1287. }
  1288. }
  1289. }
  1290. uint oldChannels = feats.channels();
  1291. if ( feats.channels() < feats_tmp.channels() )
  1292. feats.addChannel ( feats_tmp.channels()-feats.channels() );
  1293. for ( int x = 0; x < xsize; x++ )
  1294. {
  1295. for ( int y = 0; y < ysize; y++ )
  1296. {
  1297. for ( uint r = oldChannels; r < ( uint ) feats_tmp.channels(); r++ )
  1298. {
  1299. feats.set ( x, y, z, feats_tmp.get ( x, y, r ), r );
  1300. }
  1301. }
  1302. }
  1303. }
  1304. if ( useRegionFeature )
  1305. {
  1306. //using segmentation
  1307. MultiChannelImageT<int> regions;
  1308. regions.reInit( xsize, ysize, zsize );
  1309. vector<int> chanSelect;
  1310. for ( int i=0; i<3; i++ )
  1311. chanSelect.push_back ( i );
  1312. amountRegions = segmentation->segRegions ( imgData, regions, chanSelect );
  1313. int cchannel = feats.channels();
  1314. feats.addChannel ( 1 );
  1315. for ( int z = 0; z < ( int ) regions.channels(); z++ )
  1316. {
  1317. for ( int y = 0; y < regions.height(); y++ )
  1318. {
  1319. for ( int x = 0; x < regions.width(); x++ )
  1320. {
  1321. feats.set ( x, y, z, regions ( x, y, ( uint ) z ), cchannel );
  1322. }
  1323. }
  1324. }
  1325. }
  1326. if ( useVariance )
  1327. {
  1328. int cchannel = feats.channels();
  1329. if (imagetype == IMAGETYPE_RGB)
  1330. {
  1331. feats.addChannel( 3 );
  1332. for (int c = 0; c < 3; c++)
  1333. {
  1334. feats.calcVariance( c, cchannel+c );
  1335. }
  1336. }
  1337. else
  1338. {
  1339. feats.addChannel( 1 );
  1340. feats.calcVariance( 0, cchannel );
  1341. }
  1342. }
  1343. }
  1344. void SemSegContextTree::semanticseg ( NICE::MultiChannelImage3DT<double> & imgData,
  1345. NICE::MultiChannelImageT<double> & segresult,
  1346. NICE::MultiChannelImage3DT<double> & probabilities,
  1347. const std::vector<std::string> & filelist )
  1348. {
  1349. int xsize = imgData.width();
  1350. int ysize = imgData.height();
  1351. int zsize = imgData.depth();
  1352. firstiteration = true;
  1353. int classes = labelmapback.size();
  1354. int numClasses = classNames->numClasses();
  1355. fprintf ( stderr, "ContextTree classification !\n" );
  1356. probabilities.reInit ( xsize, ysize, zsize, numClasses );
  1357. probabilities.setAll ( 0 );
  1358. SparseVector *globalCategorFeat = new SparseVector();
  1359. MultiChannelImage3DT<double> feats;
  1360. // Basic Features
  1361. int amountRegions;
  1362. extractBasicFeatures ( feats, imgData, filelist, amountRegions ); //read image and do some simple transformations
  1363. vector<int> rSize;
  1364. if ( useRegionFeature )
  1365. {
  1366. rSize = vector<int> ( amountRegions, 0 );
  1367. for ( int z = 0; z < zsize; z++ )
  1368. {
  1369. for ( int y = 0; y < ysize; y++ )
  1370. {
  1371. for ( int x = 0; x < xsize; x++ )
  1372. {
  1373. rSize[feats ( x, y, z, rawChannels ) ]++;
  1374. }
  1375. }
  1376. }
  1377. }
  1378. bool allleaf = false;
  1379. MultiChannelImage3DT<unsigned short int> currentfeats ( xsize, ysize, zsize, nbTrees );
  1380. currentfeats.setAll ( 0 );
  1381. depth = 0;
  1382. vector<vector<double> > regionProbs;
  1383. if ( useRegionFeature )
  1384. {
  1385. regionProbs = vector<vector<double> > ( amountRegions, vector<double> ( classes, 0.0 ) );
  1386. }
  1387. for ( int d = 0; d < maxDepth && !allleaf; d++ )
  1388. {
  1389. depth++;
  1390. vector<vector<double> > lastRegionProbs = regionProbs;
  1391. if ( useRegionFeature )
  1392. {
  1393. int b_max = ( int ) regionProbs.size();
  1394. for ( int b = 0; b < b_max; b++ )
  1395. {
  1396. int c_max = ( int ) regionProbs[b].size();
  1397. for ( int c = 0; c < c_max; c++ )
  1398. {
  1399. regionProbs[b][c] = 0.0;
  1400. }
  1401. }
  1402. }
  1403. double weight = computeWeight ( depth, maxDepth ) - computeWeight ( depth - 1, maxDepth );
  1404. if ( depth == 1 )
  1405. {
  1406. weight = computeWeight ( 1, maxDepth );
  1407. }
  1408. allleaf = true;
  1409. MultiChannelImage3DT<unsigned short int> lastfeats = currentfeats;
  1410. int tree;
  1411. #pragma omp parallel for private(tree)
  1412. for ( tree = 0; tree < nbTrees; tree++ )
  1413. {
  1414. for ( int x = 0; x < xsize; x++ )
  1415. {
  1416. for ( int y = 0; y < ysize; y++ )
  1417. {
  1418. for ( int z = 0; z < zsize; z++ )
  1419. {
  1420. int t = currentfeats.get ( x, y, z, tree );
  1421. if ( forest[tree][t].left > 0 )
  1422. {
  1423. allleaf = false;
  1424. Features feat;
  1425. feat.feats = &feats;
  1426. feat.cfeats = &lastfeats;
  1427. feat.cTree = tree;
  1428. feat.tree = &forest[tree];
  1429. feat.rProbs = &lastRegionProbs;
  1430. double val = forest[tree][t].feat->getVal ( feat, x, y, z );
  1431. if ( !isfinite ( val ) )
  1432. {
  1433. val = 0.0;
  1434. }
  1435. if ( val < forest[tree][t].decision )
  1436. {
  1437. currentfeats.set ( x, y, z, forest[tree][t].left, tree );
  1438. #pragma omp critical
  1439. {
  1440. if ( fasthik != NULL && useCategorization && forest[tree][forest[tree][t].left].nodeNumber < uniquenumber )
  1441. ( *globalCategorFeat ) [forest[tree][forest[tree][t].left].nodeNumber] += weight;
  1442. }
  1443. }
  1444. else
  1445. {
  1446. currentfeats.set ( x, y, z, forest[tree][t].right, tree );
  1447. #pragma omp critical
  1448. {
  1449. if ( fasthik != NULL && useCategorization && forest[tree][forest[tree][t].right].nodeNumber < uniquenumber )
  1450. ( *globalCategorFeat ) [forest[tree][forest[tree][t].right].nodeNumber] += weight;
  1451. }
  1452. }
  1453. }
  1454. }
  1455. }
  1456. }
  1457. }
  1458. if ( useRegionFeature )
  1459. {
  1460. int xsize = currentfeats.width();
  1461. int ysize = currentfeats.height();
  1462. int zsize = currentfeats.depth();
  1463. #pragma omp parallel for
  1464. for ( int x = 0; x < xsize; x++ )
  1465. {
  1466. for ( int y = 0; y < ysize; y++ )
  1467. {
  1468. for ( int z = 0; z < zsize; z++ )
  1469. {
  1470. for ( int tree = 0; tree < nbTrees; tree++ )
  1471. {
  1472. int node = currentfeats.get ( x, y, z, tree );
  1473. for ( uint d = 0; d < forest[tree][node].dist.size(); d++ )
  1474. {
  1475. regionProbs[ ( int ) ( feats ( x, y, z, rawChannels ) ) ][d] += forest[tree][node].dist[d];
  1476. }
  1477. }
  1478. }
  1479. }
  1480. }
  1481. for ( int b = 0; b < ( int ) regionProbs.size(); b++ )
  1482. {
  1483. for ( int c = 0; c < ( int ) regionProbs[b].size(); c++ )
  1484. {
  1485. regionProbs[b][c] /= ( double ) ( rSize[b] );
  1486. }
  1487. }
  1488. }
  1489. if ( depth < maxDepth )
  1490. {
  1491. //compute integral images
  1492. if ( firstiteration )
  1493. {
  1494. feats.addChannel ( classes + rawChannels );
  1495. }
  1496. computeIntegralImage ( currentfeats, feats, channelType.size() - classes );
  1497. if ( firstiteration )
  1498. {
  1499. firstiteration = false;
  1500. }
  1501. }
  1502. }
  1503. int allClasses = ( int ) probabilities.channels();
  1504. vector<int> useclass ( allClasses, 1 );
  1505. vector<int> classesInImg;
  1506. if ( useCategorization )
  1507. {
  1508. if ( cndir != "" )
  1509. {
  1510. for ( int z = 0; z < zsize; z++ )
  1511. {
  1512. std::vector< std::string > list;
  1513. StringTools::split ( filelist[z], '/', list );
  1514. string orgname = list.back();
  1515. ifstream infile ( ( cndir + "/" + orgname + ".dat" ).c_str() );
  1516. while ( !infile.eof() && infile.good() )
  1517. {
  1518. int tmp;
  1519. infile >> tmp;
  1520. assert ( tmp >= 0 && tmp < allClasses );
  1521. classesInImg.push_back ( tmp );
  1522. }
  1523. }
  1524. }
  1525. else
  1526. {
  1527. globalCategorFeat->setDim ( uniquenumber );
  1528. globalCategorFeat->normalize();
  1529. ClassificationResult cr = fasthik->classify ( globalCategorFeat );
  1530. for ( uint i = 0; i < ( uint ) classes; i++ )
  1531. {
  1532. cerr << cr.scores[i] << " ";
  1533. if ( cr.scores[i] > 0.0/*-0.3*/ )
  1534. {
  1535. classesInImg.push_back ( i );
  1536. }
  1537. }
  1538. }
  1539. cerr << "amount of classes: " << classes << " used classes: " << classesInImg.size() << endl;
  1540. }
  1541. if ( classesInImg.size() == 0 )
  1542. {
  1543. for ( uint i = 0; i < ( uint ) classes; i++ )
  1544. {
  1545. classesInImg.push_back ( i );
  1546. }
  1547. }
  1548. if ( pixelWiseLabeling )
  1549. {
  1550. //finales labeln:
  1551. //long int offset = 0;
  1552. for ( int x = 0; x < xsize; x++ )
  1553. {
  1554. for ( int y = 0; y < ysize; y++ )
  1555. {
  1556. for ( int z = 0; z < zsize; z++ )
  1557. {
  1558. double maxvalue = - numeric_limits<double>::max(); //TODO: das kann auch nur pro knoten gemacht werden, nicht pro pixel
  1559. int maxindex = 0;
  1560. for ( uint c = 0; c < classesInImg.size(); c++ )
  1561. {
  1562. int i = classesInImg[c];
  1563. int currentclass = labelmapback[i];
  1564. if ( useclass[currentclass] )
  1565. {
  1566. probabilities ( x, y, z, currentclass ) = getMeanProb ( x, y, z, i, currentfeats );
  1567. if ( probabilities ( x, y, z, currentclass ) > maxvalue )
  1568. {
  1569. maxvalue = probabilities ( x, y, z, currentclass );
  1570. maxindex = currentclass;
  1571. }
  1572. }
  1573. }
  1574. segresult.set ( x, y, maxindex, ( uint ) z );
  1575. if ( maxvalue > 1 )
  1576. cout << "maxvalue: " << maxvalue << endl;
  1577. }
  1578. }
  1579. }
  1580. #undef VISUALIZE
  1581. #ifdef VISUALIZE
  1582. for ( int z = 0; z < zsize; z++ )
  1583. {
  1584. for ( int j = 0 ; j < ( int ) probabilities.channels(); j++ )
  1585. {
  1586. //cout << "class: " << j << endl;//" " << cn.text (j) << endl;
  1587. NICE::Matrix tmp ( probabilities.height(), probabilities.width() );
  1588. double maxval = -numeric_limits<double>::max();
  1589. double minval = numeric_limits<double>::max();
  1590. for ( int y = 0; y < probabilities.height(); y++ )
  1591. for ( int x = 0; x < probabilities.width(); x++ )
  1592. {
  1593. double val = probabilities ( x, y, z, j );
  1594. tmp ( y, x ) = val;
  1595. maxval = std::max ( val, maxval );
  1596. minval = std::min ( val, minval );
  1597. }
  1598. tmp ( 0, 0 ) = 1.0;
  1599. tmp ( 0, 1 ) = 0.0;
  1600. NICE::ColorImage imgrgb ( probabilities.width(), probabilities.height() );
  1601. ICETools::convertToRGB ( tmp, imgrgb );
  1602. cout << "maxval = " << maxval << " minval: " << minval << " for class " << j << endl; //cn.text (j) << endl;
  1603. std::string s;
  1604. std::stringstream out;
  1605. out << "tmpprebmap" << z << "_" << j << ".ppm";
  1606. s = out.str();
  1607. imgrgb.write ( s );
  1608. //showImage(imgrgb, "Ergebnis");
  1609. //getchar();
  1610. }
  1611. }
  1612. cout << "fertsch" << endl;
  1613. getchar();
  1614. cout << "weiter gehtsch" << endl;
  1615. #endif
  1616. }
  1617. else
  1618. {
  1619. //using segmentation
  1620. NICE::MultiChannelImageT<int> regions;
  1621. int xsize = feats.width();
  1622. int ysize = feats.height();
  1623. int zsize = feats.depth();
  1624. regions.reInit ( xsize, ysize, zsize );
  1625. if ( useRegionFeature )
  1626. {
  1627. int rchannel = -1;
  1628. for ( uint i = 0; i < channelType.size(); i++ )
  1629. {
  1630. if ( channelType[i] == 1 )
  1631. {
  1632. rchannel = i;
  1633. break;
  1634. }
  1635. }
  1636. assert ( rchannel > -1 );
  1637. for ( int z = 0; z < zsize; z++ )
  1638. {
  1639. for ( int y = 0; y < ysize; y++ )
  1640. {
  1641. for ( int x = 0; x < xsize; x++ )
  1642. {
  1643. regions.set ( x, y, feats ( x, y, z, rchannel ), ( uint ) z );
  1644. }
  1645. }
  1646. }
  1647. }
  1648. else
  1649. {
  1650. amountRegions = 0;
  1651. vector<int> chanSelect;
  1652. for ( int i=0; i<3; i++ )
  1653. chanSelect.push_back ( i );
  1654. amountRegions = segmentation->segRegions ( imgData, regions, chanSelect );
  1655. #ifdef DEBUG
  1656. for ( unsigned int z = 0; z < ( uint ) zsize; z++ )
  1657. {
  1658. NICE::Matrix regmask;
  1659. NICE::ColorImage colorimg ( xsize, ysize );
  1660. NICE::ColorImage marked ( xsize, ysize );
  1661. regmask.resize ( xsize, ysize );
  1662. for ( int y = 0; y < ysize; y++ )
  1663. {
  1664. for ( int x = 0; x < xsize; x++ )
  1665. {
  1666. regmask ( x,y ) = regions ( x,y,z );
  1667. colorimg.setPixelQuick ( x, y, 0, imgData.get ( x,y,z,0 ) );
  1668. colorimg.setPixelQuick ( x, y, 1, imgData.get ( x,y,z,0 ) );
  1669. colorimg.setPixelQuick ( x, y, 2, imgData.get ( x,y,z,0 ) );
  1670. }
  1671. }
  1672. vector<int> colorvals;
  1673. colorvals.push_back ( 255 );
  1674. colorvals.push_back ( 0 );
  1675. colorvals.push_back ( 0 );
  1676. segmentation->markContours ( colorimg, regmask, colorvals, marked );
  1677. std::vector<string> list;
  1678. StringTools::split ( filelist[z], '/', list );
  1679. string savePath = StringTools::trim ( filelist[z], list.back() ) + "marked/" + list.back();
  1680. marked.write ( savePath );
  1681. }
  1682. #endif
  1683. }
  1684. regionProbs.clear();
  1685. regionProbs = vector<vector<double> > ( amountRegions, vector<double> ( classes, 0.0 ) );
  1686. vector<int> bestlabels ( amountRegions, labelmapback[classesInImg[0]] );
  1687. for ( int z = 0; z < zsize; z++ )
  1688. {
  1689. for ( int y = 0; y < ysize; y++ )
  1690. {
  1691. for ( int x = 0; x < xsize; x++ )
  1692. {
  1693. int cregion = regions ( x, y, ( uint ) z );
  1694. for ( uint c = 0; c < classesInImg.size(); c++ )
  1695. {
  1696. int d = classesInImg[c];
  1697. regionProbs[cregion][d] += getMeanProb ( x, y, z, d, currentfeats );
  1698. }
  1699. }
  1700. }
  1701. }
  1702. for ( int r = 0; r < amountRegions; r++ )
  1703. {
  1704. double maxval = regionProbs[r][classesInImg[0]];
  1705. bestlabels[r] = classesInImg[0];
  1706. for ( int d = 1; d < classes; d++ )
  1707. {
  1708. if ( maxval < regionProbs[r][d] )
  1709. {
  1710. maxval = regionProbs[r][d];
  1711. bestlabels[r] = d;
  1712. }
  1713. }
  1714. bestlabels[r] = labelmapback[bestlabels[r]];
  1715. }
  1716. for ( int z = 0; z < zsize; z++ )
  1717. {
  1718. for ( int y = 0; y < ysize; y++ )
  1719. {
  1720. for ( int x = 0; x < xsize; x++ )
  1721. {
  1722. segresult.set ( x, y, bestlabels[regions ( x,y, ( uint ) z ) ], ( uint ) z );
  1723. }
  1724. }
  1725. }
  1726. //#define WRITEREGIONS
  1727. #ifdef WRITEREGIONS
  1728. for ( int z = 0; z < zsize; z++ )
  1729. {
  1730. RegionGraph rg;
  1731. NICE::ColorImage img ( xsize,ysize );
  1732. if ( imagetype == IMAGETYPE_RGB )
  1733. {
  1734. img = imgData.getColor ( z );
  1735. }
  1736. else
  1737. {
  1738. NICE::Image gray = imgData.getChannel ( z );
  1739. for ( int y = 0; y < ysize; y++ )
  1740. {
  1741. for ( int x = 0; x < xsize; x++ )
  1742. {
  1743. int val = gray.getPixelQuick ( x,y );
  1744. img.setPixelQuick ( x, y, val, val, val );
  1745. }
  1746. }
  1747. }
  1748. Matrix regions_tmp ( xsize,ysize );
  1749. for ( int y = 0; y < ysize; y++ )
  1750. {
  1751. for ( int x = 0; x < xsize; x++ )
  1752. {
  1753. regions_tmp ( x,y ) = regions ( x,y, ( uint ) z );
  1754. }
  1755. }
  1756. segmentation->getGraphRepresentation ( img, regions_tmp, rg );
  1757. for ( uint pos = 0; pos < regionProbs.size(); pos++ )
  1758. {
  1759. rg[pos]->setProbs ( regionProbs[pos] );
  1760. }
  1761. std::string s;
  1762. std::stringstream out;
  1763. std::vector< std::string > list;
  1764. StringTools::split ( filelist[z], '/', list );
  1765. out << "rgout/" << list.back() << ".graph";
  1766. string writefile = out.str();
  1767. rg.write ( writefile );
  1768. }
  1769. #endif
  1770. }
  1771. cout << "segmentation finished" << endl;
  1772. }
  1773. void SemSegContextTree::store ( std::ostream & os, int format ) const
  1774. {
  1775. os.precision ( numeric_limits<double>::digits10 + 1 );
  1776. os << nbTrees << endl;
  1777. classnames.store ( os );
  1778. map<int, int>::const_iterator it;
  1779. os << labelmap.size() << endl;
  1780. for ( it = labelmap.begin() ; it != labelmap.end(); it++ )
  1781. os << ( *it ).first << " " << ( *it ).second << endl;
  1782. os << labelmapback.size() << endl;
  1783. for ( it = labelmapback.begin() ; it != labelmapback.end(); it++ )
  1784. os << ( *it ).first << " " << ( *it ).second << endl;
  1785. int trees = forest.size();
  1786. os << trees << endl;
  1787. for ( int t = 0; t < trees; t++ )
  1788. {
  1789. int nodes = forest[t].size();
  1790. os << nodes << endl;
  1791. for ( int n = 0; n < nodes; n++ )
  1792. {
  1793. 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;
  1794. os << forest[t][n].dist << endl;
  1795. if ( forest[t][n].feat == NULL )
  1796. os << -1 << endl;
  1797. else
  1798. {
  1799. os << forest[t][n].feat->getOps() << endl;
  1800. forest[t][n].feat->store ( os );
  1801. }
  1802. }
  1803. }
  1804. os << channelType.size() << endl;
  1805. for ( int i = 0; i < ( int ) channelType.size(); i++ )
  1806. {
  1807. os << channelType[i] << " ";
  1808. }
  1809. os << endl;
  1810. os << integralMap.size() << endl;
  1811. for ( int i = 0; i < ( int ) integralMap.size(); i++ )
  1812. {
  1813. os << integralMap[i].first << " " << integralMap[i].second << endl;
  1814. }
  1815. os << rawChannels << endl;
  1816. os << uniquenumber << endl;
  1817. }
  1818. void SemSegContextTree::restore ( std::istream & is, int format )
  1819. {
  1820. is >> nbTrees;
  1821. classnames.restore ( is );
  1822. int lsize;
  1823. is >> lsize;
  1824. labelmap.clear();
  1825. for ( int l = 0; l < lsize; l++ )
  1826. {
  1827. int first, second;
  1828. is >> first;
  1829. is >> second;
  1830. labelmap[first] = second;
  1831. }
  1832. is >> lsize;
  1833. labelmapback.clear();
  1834. for ( int l = 0; l < lsize; l++ )
  1835. {
  1836. int first, second;
  1837. is >> first;
  1838. is >> second;
  1839. labelmapback[first] = second;
  1840. }
  1841. int trees;
  1842. is >> trees;
  1843. forest.clear();
  1844. for ( int t = 0; t < trees; t++ )
  1845. {
  1846. vector<TreeNode> tmptree;
  1847. forest.push_back ( tmptree );
  1848. int nodes;
  1849. is >> nodes;
  1850. for ( int n = 0; n < nodes; n++ )
  1851. {
  1852. TreeNode tmpnode;
  1853. forest[t].push_back ( tmpnode );
  1854. is >> forest[t][n].left;
  1855. is >> forest[t][n].right;
  1856. is >> forest[t][n].decision;
  1857. is >> forest[t][n].isleaf;
  1858. is >> forest[t][n].depth;
  1859. is >> forest[t][n].featcounter;
  1860. is >> forest[t][n].nodeNumber;
  1861. is >> forest[t][n].dist;
  1862. int feattype;
  1863. is >> feattype;
  1864. assert ( feattype < NBOPERATIONS );
  1865. forest[t][n].feat = NULL;
  1866. if ( feattype >= 0 )
  1867. {
  1868. for ( uint o = 0; o < ops.size(); o++ )
  1869. {
  1870. for ( uint o2 = 0; o2 < ops[o].size(); o2++ )
  1871. {
  1872. if ( forest[t][n].feat == NULL )
  1873. {
  1874. for ( uint c = 0; c < ops[o].size(); c++ )
  1875. {
  1876. if ( ops[o][o2]->getOps() == feattype )
  1877. {
  1878. forest[t][n].feat = ops[o][o2]->clone();
  1879. break;
  1880. }
  1881. }
  1882. }
  1883. }
  1884. }
  1885. assert ( forest[t][n].feat != NULL );
  1886. forest[t][n].feat->restore ( is );
  1887. }
  1888. }
  1889. }
  1890. channelType.clear();
  1891. int ctsize;
  1892. is >> ctsize;
  1893. for ( int i = 0; i < ctsize; i++ )
  1894. {
  1895. int tmp;
  1896. is >> tmp;
  1897. channelType.push_back ( tmp );
  1898. }
  1899. integralMap.clear();
  1900. int iMapSize;
  1901. is >> iMapSize;
  1902. for ( int i = 0; i < iMapSize; i++ )
  1903. {
  1904. int first;
  1905. int second;
  1906. is >> first;
  1907. is >> second;
  1908. integralMap.push_back ( pair<int, int> ( first, second ) );
  1909. }
  1910. is >> rawChannels;
  1911. is >> uniquenumber;
  1912. }