SemSegContextTree.cpp 63 KB

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