Debian Codegraph @

src/imageclasses/jlann_lib.cc

raw symbols SCIP
1 /**********************************************************************
2 jlann_lib.cc: classify raster image using Artificial Neural Network
3 Author(s): [email protected]
4 Copyright (C) 2016-2020 European Union (Joint Research Centre)
5
6 This file is part of jiplib.
7
8 jiplib is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
12
13 jiplib is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with jiplib. If not, see <https://www.gnu.org/licenses/>.
20 ***********************************************************************/
21 #include <stdlib.h>
22 #include <vector>
23 #include <map>
24 #include <algorithm>
25 #include "Jim.h"
26 #include "VectorOgr.h"
27 // #include "ImgReaderOgr.h"
28 // #include "ImgWriterOgr.h"
29 #include "base/Optionjl.h"
30 #include "base/PosValue.h"
31 #include "algorithms/ConfusionMatrix.h"
32 #include "floatfann.h"
33 #include "algorithms/myfann_cpp.h"
34
35 using namespace std;
36 using namespace app;
37
38 std::string VectorOgr::trainANN(app::AppFactory& app){
39 confusionmatrix::ConfusionMatrix cm;
40
41 //--------------------------- command line options ------------------------------------
42 // Optionjl<std::string> model_opt("model", "model", "Model filename to save trained classifier.");
43 // Optionjl<std::string> tlayer_opt("tln", "tln", "Sample layer name(s)");
44 // Optionjl<std::string> attribute_opt("af", "af", "Attribute filter");
45 Optionjl<std::string> label_opt("label", "label", "Attribute name for class label in training vector file.","label");
46 Optionjl<unsigned int> balance_opt("bal", "balance", "Balance the input data to this number of samples for each class", 0);
47 Optionjl<bool> random_opt("random", "random", "Randomize training data for balancing", true, 2);
48 Optionjl<unsigned int> minSize_opt("min", "min", "If number of training pixels is less then min, do not take this class into account (0: consider all classes)", 0);
49 // Optionjl<unsigned int> band_opt("b", "band", "Band index (starting from 0, either use band option or use start to end)");
50 // Optionjl<unsigned int> bstart_opt("sband", "startband", "Start band sequence number");
51 // Optionjl<unsigned int> bend_opt("eband", "endband", "End band sequence number");
52 Optionjl<std::string> bandNames_opt("bn", "bandname", "Band name(s) to use. Leave empty to use all bands");
53 Optionjl<double> offset_opt("offset", "offset", "Offset value for each spectral band input features: refl[band]=(DN[band]-offset[band])/scale[band]", 0.0);
54 Optionjl<double> scale_opt("scale", "scale", "Scale value for each spectral band input features: refl=(DN[band]-offset[band])/scale[band] (use 0 if scale min and max in each band to -1.0 and 1.0)", 0.0);
55 Optionjl<unsigned short> cv_opt("cv", "cv", "N-fold cross validation mode",0);
56 Optionjl<std::string> cmformat_opt("cmf","cmf","Format for confusion matrix (ascii or latex)","ascii");
57 Optionjl<unsigned int> nneuron_opt("nn", "nneuron", "number of neurons in hidden layers in neural network (multiple hidden layers are set by defining multiple number of neurons: -n 15 -n 1, default is one hidden layer with 5 neurons)", 5);
58 Optionjl<float> connection_opt("\0", "connection", "connection rate (default: 1.0 for a fully connected network)", 1.0);
59 Optionjl<float> learning_opt("l", "learning", "learning rate (default: 0.7)", 0.7);
60 Optionjl<float> weights_opt("w", "weights", "weights for neural network. Apply to fully connected network only, starting from first input neuron to last output neuron, including the bias neurons (last neuron in each but last layer)", 0.0);
61 Optionjl<unsigned int> maxit_opt("\0", "maxit", "number of maximum iterations (epoch) (default: 500)", 500);
62 Optionjl<std::string> classname_opt("c", "class", "List of class names.");
63 Optionjl<short> classvalue_opt("r", "reclass", "List of class values (use same order as in class opt).");
64 Optionjl<short> verbose_opt("v", "verbose", "Verbose level",0,2);
65
66 random_opt.setHide(1);
67 minSize_opt.setHide(1);
68 // band_opt.setHide(1);
69 // bstart_opt.setHide(1);
70 // bend_opt.setHide(1);
71 connection_opt.setHide(1);
72 learning_opt.setHide(1);
73 weights_opt.setHide(1);
74 maxit_opt.setHide(1);
75 verbose_opt.setHide(2);
76
77 bool doProcess;//stop process when program was invoked with help option (-h --help)
78 try{
79 // doProcess=model_opt.retrieveOption(app);
80 doProcess=label_opt.retrieveOption(app);
81 // tlayer_opt.retrieveOption(app);
82 // attribute_opt.retrieveOption(app);
83 balance_opt.retrieveOption(app);
84 random_opt.retrieveOption(app);
85 minSize_opt.retrieveOption(app);
86 // band_opt.retrieveOption(app);
87 // bstart_opt.retrieveOption(app);
88 // bend_opt.retrieveOption(app);
89 bandNames_opt.retrieveOption(app);
90 offset_opt.retrieveOption(app);
91 scale_opt.retrieveOption(app);
92 cv_opt.retrieveOption(app);
93 cmformat_opt.retrieveOption(app);
94 nneuron_opt.retrieveOption(app);
95 connection_opt.retrieveOption(app);
96 learning_opt.retrieveOption(app);
97 weights_opt.retrieveOption(app);
98 maxit_opt.retrieveOption(app);
99 classname_opt.retrieveOption(app);
100 classvalue_opt.retrieveOption(app);
101 verbose_opt.retrieveOption(app);
102 // memory_opt.retrieveOption(app);
103
104 if(!doProcess){
105 cout << endl;
106 std::ostringstream helpStream;
107 helpStream << "short option -h shows basic options only, use long option --help to show all options" << std::endl;
108 throw(helpStream.str());//help was invoked, stop processing
109 }
110 FANN::neural_net net;//the neural network
111
112 // if(model_opt.empty()){
113 // std::string errorString="Error: filename to save model is empty";
114 // throw(errorString);
115 // }
116
117 unsigned int nclass=0;
118 unsigned int nband=0;
119 map<string,Vector2d<float> > trainingMap;
120 vector< Vector2d<float> > trainingPixels;//[class][sample][band]
121 map<string,short> classValueMap;
122 vector<std::string> nameVector;
123 if(classname_opt.size()){
124 assert(classname_opt.size()==classvalue_opt.size());
125 for(unsigned int iclass=0;iclass<classname_opt.size();++iclass)
126 classValueMap[classname_opt[iclass]]=classvalue_opt[iclass];
127 }
128 // setAttributeFilter(attribute_opt[0]);
129 sortByLabel(trainingMap,label_opt[0],bandNames_opt);
130
131 //convert trainingMap to trainingPixels, removing small classes (< minSize_opt[0])
132 map<string,Vector2d<float> >::iterator mapit=trainingMap.begin();
133 while(mapit!=trainingMap.end()){
134 //delete small classes
135 if((mapit->second).size()<minSize_opt[0]){
136 trainingMap.erase(mapit);
137 continue;
138 }
139 trainingPixels.push_back(mapit->second);
140 if(verbose_opt[0]>1)
141 std::cout << mapit->first << ": " << (mapit->second).size() << " samples" << std::endl;
142 ++mapit;
143 }
144 nclass=trainingPixels.size();
145 if(classname_opt.size())
146 assert(nclass==classname_opt.size());
147 nband=trainingPixels[0][0].size();
148 //balance training data
149 if(balance_opt[0]>0){
150 while(balance_opt.size()<nclass)
151 balance_opt.push_back(balance_opt.back());
152 if(random_opt[0])
153 srand(time(NULL));
154 int totalSamples=0;
155 for(short iclass=0;iclass<nclass;++iclass){
156 if(trainingPixels[iclass].size()>balance_opt[iclass]){
157 while(trainingPixels[iclass].size()>balance_opt[iclass]){
158 int index=rand()%trainingPixels[iclass].size();
159 trainingPixels[iclass].erase(trainingPixels[iclass].begin()+index);
160 }
161 }
162 else{
163 int oldsize=trainingPixels[iclass].size();
164 for(int isample=trainingPixels[iclass].size();isample<balance_opt[iclass];++isample){
165 int index = rand()%oldsize;
166 trainingPixels[iclass].push_back(trainingPixels[iclass][index]);
167 }
168 }
169 totalSamples+=trainingPixels[iclass].size();
170 }
171 }
172
173 statfactory::StatFactory stat;
174 vector<double> offset;
175 vector<double> scale;
176 //set scale and offset
177 offset.resize(nband);
178 scale.resize(nband);
179 for(int iband=0;iband<nband;++iband){
180 offset[iband]=(offset_opt.size()==1)?offset_opt[0]:offset_opt[iband];
181 scale[iband]=(scale_opt.size()==1)?scale_opt[0]:scale_opt[iband];
182 //search for min and maximum
183 if(scale[iband]<=0){
184 float theMin=trainingPixels[0][0][iband];
185 float theMax=trainingPixels[0][0][iband];
186 for(short iclass=0;iclass<nclass;++iclass){
187 for(int isample=0;isample<trainingPixels[iclass].size();++isample){
188 if(theMin>trainingPixels[iclass][isample][iband])
189 theMin=trainingPixels[iclass][isample][iband];
190 if(theMax<trainingPixels[iclass][isample][iband])
191 theMax=trainingPixels[iclass][isample][iband];
192 }
193 }
194 offset[iband]=theMin+(theMax-theMin)/2.0;
195 scale[iband]=(theMax-theMin)/2.0;
196 }
197 }
198 // map<string,Vector2d<float> >::iterator mapit=trainingMap.begin();
199
200 mapit=trainingMap.begin();
201 bool doSort=true;
202 while(mapit!=trainingMap.end()){
203 nameVector.push_back(mapit->first);
204 if(classValueMap.size()){
205 //check if name in training is covered by classname_opt (values can not be 0)
206 if(classValueMap[mapit->first]>0){
207 if(cm.getClassIndex(type2string<short>(classValueMap[mapit->first]))<0){
208 cm.pushBackClassName(type2string<short>(classValueMap[mapit->first]),doSort);
209 }
210 }
211 else{
212 std::string errorString="Error: names in classname option are not complete, please check names in training vector and make sure classvalue is > 0";
213 throw(errorString);
214 }
215 }
216 else
217 cm.pushBackClassName(mapit->first,doSort);
218 ++mapit;
219 }
220 if(classname_opt.empty()){
221 //std::cerr << "Warning: no class name and value pair provided for all " << nclass << " classes, using string2type<int> instead!" << std::endl;
222 for(int iclass=0;iclass<nclass;++iclass){
223 if(verbose_opt[0])
224 std::cout << iclass << " " << cm.getClass(iclass) << " -> " << string2type<short>(cm.getClass(iclass)) << std::endl;
225 classValueMap[cm.getClass(iclass)]=string2type<short>(cm.getClass(iclass));
226 }
227 }
228
229 //Calculate features of training set
230 vector< Vector2d<float> > trainingFeatures(nclass);
231 for(short iclass=0;iclass<nclass;++iclass){
232 int nctraining=0;
233 if(verbose_opt[0]>=1)
234 std::cout << "calculating features for class " << iclass << std::endl;
235 if(random_opt[0])
236 srand(time(NULL));
237 nctraining=trainingPixels[iclass].size();
238 if(nctraining<=0)
239 nctraining=1;
240 assert(nctraining<=trainingPixels[iclass].size());
241 if(verbose_opt[0]>1)
242 std::cout << "nctraining (class " << iclass << "): " << nctraining << std::endl;
243 trainingFeatures[iclass].resize(nctraining);
244 for(int isample=0;isample<nctraining;++isample){
245 //scale pixel values according to scale and offset!!!
246 for(int iband=0;iband<nband;++iband){
247 float value=trainingPixels[iclass][isample][iband];
248 trainingFeatures[iclass][isample].push_back((value-offset[iband])/scale[iband]);
249 }
250 }
251 assert(trainingFeatures[iclass].size()==nctraining);
252 }
253
254 unsigned int nFeatures=trainingFeatures[0][0].size();
255 unsigned int ntraining=0;
256 for(short iclass=0;iclass<nclass;++iclass)
257 ntraining+=trainingFeatures[iclass].size();
258
259 const unsigned int num_layers = nneuron_opt.size()+2;
260 const float desired_error = 0.0003;
261 const unsigned int iterations_between_reports = (verbose_opt[0])? maxit_opt[0]+1:0;
262 if(verbose_opt[0]>=1){
263 std::cout << "number of features: " << nFeatures << std::endl;
264 std::cout << "creating artificial neural network with " << nneuron_opt.size() << " hidden layer, having " << std::endl;
265 for(unsigned int ilayer=0;ilayer<nneuron_opt.size();++ilayer)
266 std::cout << nneuron_opt[ilayer] << " ";
267 std::cout << "neurons" << std::endl;
268 std::cout << "connection_opt[0]: " << connection_opt[0] << std::endl;
269 std::cout << "num_layers: " << num_layers << std::endl;
270 std::cout << "nFeatures: " << nFeatures << std::endl;
271 std::cout << "nneuron_opt[0]: " << nneuron_opt[0] << std::endl;
272 std::cout << "number of classes (nclass): " << nclass << std::endl;
273 }
274 switch(num_layers){
275 case(3):{
276 // net.create_sparse(connection_opt[0],num_layers, nFeatures, nneuron_opt[0], nclass);//replace all create_sparse with create_sparse_array due to bug in FANN!
277 unsigned int layers[3];
278 layers[0]=nFeatures;
279 layers[1]=nneuron_opt[0];
280 layers[2]=nclass;
281 net.create_sparse_array(connection_opt[0],num_layers,layers);
282 break;
283 }
284 case(4):{
285 unsigned int layers[4];
286 layers[0]=nFeatures;
287 layers[1]=nneuron_opt[0];
288 layers[2]=nneuron_opt[1];
289 layers[3]=nclass;
290 // layers.push_back(nFeatures);
291 // for(int ihidden=0;ihidden<nneuron_opt.size();++ihidden)
292 // layers.push_back(nneuron_opt[ihidden]);
293 // layers.push_back(nclass);
294 net.create_sparse_array(connection_opt[0],num_layers,layers);
295 break;
296 }
297 default:
298 cerr << "Only 1 or 2 hidden layers are supported!" << std::endl;
299 exit(1);
300 break;
301 }
302 if(verbose_opt[0]>=1)
303 std::cout << "network created" << std::endl;
304
305 net.set_learning_rate(learning_opt[0]);
306
307 // net.set_activation_steepness_hidden(1.0);
308 // net.set_activation_steepness_output(1.0);
309
310 net.set_activation_function_hidden(FANN::SIGMOID_SYMMETRIC_STEPWISE);
311 net.set_activation_function_output(FANN::SIGMOID_SYMMETRIC_STEPWISE);
312
313 // Set additional properties such as the training algorithm
314 // net.set_training_algorithm(FANN::TRAIN_QUICKPROP);
315
316 // Output network type and parameters
317 if(verbose_opt[0]>=1){
318 std::cout << std::endl << "Network Type : ";
319 switch (net.get_network_type())
320 {
321 case FANN::LAYER:
322 std::cout << "LAYER" << std::endl;
323 break;
324 case FANN::SHORTCUT:
325 std::cout << "SHORTCUT" << std::endl;
326 break;
327 default:
328 std::cout << "UNKNOWN" << std::endl;
329 break;
330 }
331 net.print_parameters();
332 }
333
334 if(cv_opt[0]>1){
335 if(verbose_opt[0])
336 std::cout << "cross validation" << std::endl;
337 vector<unsigned short> referenceVector;
338 vector<unsigned short> outputVector;
339 float rmse=net.cross_validation(trainingFeatures,
340 ntraining,
341 cv_opt[0],
342 maxit_opt[0],
343 desired_error,
344 referenceVector,
345 outputVector,
346 verbose_opt[0]);
347 map<string,Vector2d<float> >::iterator mapit=trainingMap.begin();
348 for(unsigned int isample=0;isample<referenceVector.size();++isample){
349 string refClassName=nameVector[referenceVector[isample]];
350 string className=nameVector[outputVector[isample]];
351 if(classValueMap.size())
352 cm.incrementResult(type2string<short>(classValueMap[refClassName]),type2string<short>(classValueMap[className]),1.0);
353 else
354 cm.incrementResult(cm.getClass(referenceVector[isample]),cm.getClass(outputVector[isample]),1.0);
355 }
356 }
357
358 if(verbose_opt[0]>=1)
359 std::cout << std::endl << "Set training data" << std::endl;
360
361 if(verbose_opt[0]>=1)
362 std::cout << std::endl << "Training network" << std::endl;
363
364 if(verbose_opt[0]>=1){
365 std::cout << "Max Epochs " << setw(8) << maxit_opt[0] << ". "
366 << "Desired Error: " << left << desired_error << right << std::endl;
367 }
368 if(weights_opt.size()==net.get_total_connections()){//no new training needed (same training sample)
369 vector<fann_connection> convector;
370 net.get_connection_array(convector);
371 for(unsigned int i_connection=0;i_connection<net.get_total_connections();++i_connection)
372 convector[i_connection].weight=weights_opt[i_connection];
373 net.set_weight_array(convector);
374 }
375 else{
376 bool initWeights=true;
377 net.train_on_data(trainingFeatures,ntraining,initWeights, maxit_opt[0],
378 iterations_between_reports, desired_error);
379 }
380
381
382 if(verbose_opt[0]>=2){
383 net.print_connections();
384 vector<fann_connection> convector;
385 net.get_connection_array(convector);
386 for(unsigned int i_connection=0;i_connection<net.get_total_connections();++i_connection)
387 std::cout << "connection " << i_connection << ": " << convector[i_connection].weight << std::endl;
388
389 }
390 if(cv_opt[0]>1){
391 assert(cm.nReference());
392 cm.setFormat(cmformat_opt[0]);
393 cm.reportSE95(false);
394 std::cout << cm << std::endl;
395 }
396 //--------------------------------- end of training -----------------------------------
397 // net.save(model_opt[0], offset, scale, classValueMap, nameVector, bandNames_opt);
398 std::ostringstream outputStream;
399 net.ann_serialize_model(outputStream, offset, scale, classValueMap, nameVector, bandNames_opt);
400 return outputStream.str();
401 }
402 catch(std::string errorString){
403 std::cerr << errorString << std::endl;
404 throw;
405 }
406 }
407
408 /**
409 * @param app application specific option arguments
410 * @return output classified raster dataset
411 **/
412 shared_ptr<Jim> Jim::classifyANN(app::AppFactory& app){
413 try{
414 shared_ptr<Jim> imgWriter=createImg();
415 classifyANN(*imgWriter, app);
416 return(imgWriter);
417 }
418 catch(string helpString){
419 cerr << helpString << endl;
420 throw;
421 }
422 }
423
424 /**
425 * @param app application specific option arguments
426 * @return output classified raster dataset
427 **/
428 // shared_ptr<Jim> Jim::ann(app::AppFactory& app){
429 // try{
430 // shared_ptr<Jim> imgWriter=createImg();
431 // ann(*imgWriter, app);
432 // return(imgWriter);
433 // }
434 // catch(string helpString){
435 // cerr << helpString << endl;
436 // return(0);
437 // }
438 // }
439
440 /**
441 * @param imgWriter output classified raster dataset
442 * @param app application specific option arguments
443 * @return CE_None if successful, CE_Failure if failed
444 **/
445 void Jim::classifyANN(Jim& imgWriter, app::AppFactory& app){
446 vector<double> priors;
447
448 //--------------------------- command line options ------------------------------------
449 Optionjl<std::string> model_opt("model", "model", "Model filename for trained classifier.");
450 Optionjl<unsigned int> band_opt("b", "band", "band index (starting from 0, either use band option or use start to end)");
451 // Optionjl<std::string> bandNames_opt("bn", "bandname", "Band name(s) to use. Leave empty to use all bands");
452 Optionjl<unsigned int> bstart_opt("sband", "startband", "Start band sequence number");
453 Optionjl<unsigned int> bend_opt("eband", "endband", "End band sequence number");
454 // Optionjl<double> offset_opt("offset", "offset", "offset value for each spectral band input features: refl[band]=(DN[band]-offset[band])/scale[band]", 0.0);
455 // Optionjl<double> scale_opt("scale", "scale", "scale value for each spectral band input features: refl=(DN[band]-offset[band])/scale[band] (use 0 if scale min and max in each band to -1.0 and 1.0)", 0.0);
456 Optionjl<double> priors_opt("prior", "prior", "prior probabilities for each class (e.g., -p 0.3 -p 0.3 -p 0.2 )", 0.0);
457 Optionjl<string> priorimg_opt("pim", "priorimg", "prior probability image (multi-band img with band for each class","",2);
458 Optionjl<string> extent_opt("e", "extent", "Only classify within extent from polygons in vector file");
459 Optionjl<string> eoption_opt("eo","eo", "special extent options controlling rasterization: ATTRIBUTE|CHUNKYSIZE|ALL_TOUCHED|BURN_VALUE_FROM|MERGE_ALG, e.g., -eo ATTRIBUTE=fieldname");
460 Optionjl<string> mask_opt("m", "mask", "Only classify within specified mask (vector or raster). For raster mask, set nodata values with the option msknodata.");
461 Optionjl<short> msknodata_opt("msknodata", "msknodata", "mask value(s) not to consider for classification. Values will be taken over in classification image. Default is 0", 0);
462 Optionjl<double> srcnodata_opt("srcnodata", "srcnodata", "Nodata value in source",0);
463 Optionjl<unsigned short> dstnodata_opt("dstnodata", "dstnodata", "Nodata value to put where image is masked as nodata", 0);
464 // Optionjl<unsigned short> nodata_opt("nodata", "nodata", "nodata value to put where image is masked as nodata", 0);
465 Optionjl<string> colorTable_opt("ct", "ct", "colour table in ASCII format having 5 columns: id R G B ALFA (0: transparent, 255: solid)");
466 Optionjl<string> prob_opt("\0", "prob", "probability image. Default is no probability image");
467 Optionjl<string> entropy_opt("entropy", "entropy", "entropy image (measure for uncertainty of classifier output","",2);
468 Optionjl<short> verbose_opt("v", "verbose", "set to: 0 (results only), 1 (confusion matrix), 2 (debug)",0,2);
469 extent_opt.setHide(1);
470 eoption_opt.setHide(1);
471 band_opt.setHide(1);
472 bstart_opt.setHide(1);
473 bend_opt.setHide(1);
474 prob_opt.setHide(1);
475 priorimg_opt.setHide(1);
476 // offset_opt.setHide(1);
477 // scale_opt.setHide(1);
478 verbose_opt.setHide(2);
479
480 bool doProcess;//stop process when program was invoked with help option (-h --help)
481 try{
482 doProcess=model_opt.retrieveOption(app);
483 colorTable_opt.retrieveOption(app);
484 extent_opt.retrieveOption(app);
485 eoption_opt.retrieveOption(app);
486 mask_opt.retrieveOption(app);
487 msknodata_opt.retrieveOption(app);
488 srcnodata_opt.retrieveOption(app);
489 dstnodata_opt.retrieveOption(app);
490 // nodata_opt.retrieveOption(app);
491 // Advanced options
492 band_opt.retrieveOption(app);
493 // bandNames_opt.setHide(1);
494 bstart_opt.retrieveOption(app);
495 bend_opt.retrieveOption(app);
496 prob_opt.retrieveOption(app);
497 priorimg_opt.retrieveOption(app);
498 // offset_opt.retrieveOption(app);
499 // scale_opt.retrieveOption(app);
500 priors_opt.retrieveOption(app);
501 entropy_opt.retrieveOption(app);
502 verbose_opt.retrieveOption(app);
503
504 if(!doProcess){
505 std::cout << std::endl;
506 std::ostringstream helpStream;
507 helpStream << "short option -h shows basic options only, use long option --help to show all options" << std::endl;
508 throw(helpStream.str());//help was invoked, stop processing
509 }
510
511 if(entropy_opt[0]=="")
512 entropy_opt.clear();
513 if(priorimg_opt[0]=="")
514 priorimg_opt.clear();
515
516 if(model_opt.empty()){
517 string errorString="Error: no model filename provided";
518 throw(errorString);
519 }
520
521 // ImgReaderOgr extentReader;
522 VectorOgr extentReader;
523 Jim maskReader;
524 // OGRLayer *readLayer;
525
526 double ulx=0;
527 double uly=0;
528 double lrx=0;
529 double lry=0;
530
531 // bool maskIsVector=false;
532 if(extent_opt.size()){
533 if(mask_opt.size()){
534 string errorString="Error: can only either mask or extent, not both";
535 throw(errorString);
536 }
537 std::vector<std::string> layernames;
538 layernames.clear();
539 extentReader.open(extent_opt[0],layernames,true);
540 // readLayer = extentReader.getDataSource()->GetLayer(0);
541 extentReader.getExtent(ulx,uly,lrx,lry);
542 maskReader.open(this->nrOfCol(),this->nrOfRow(),1,GDT_Float64);
543 double gt[6];
544 this->getGeoTransform(gt);
545 maskReader.setGeoTransform(gt);
546 maskReader.setProjection(this->getProjection());
547 // vector<double> burnValues(1,1);//burn value is 1 (single band)
548 maskReader.d_rasterizeBuf(extentReader,dstnodata_opt[0],eoption_opt);
549 maskReader.GDALSetNoDataValue(dstnodata_opt[0]);
550 extentReader.close();
551 }
552
553 unsigned int totalSamples=0;
554 FANN::neural_net net;//the neural network
555
556
557 vector<double> offset;
558 vector<double> scale;
559 map<string,short> classValueMap;
560 vector<std::string> nameVector;
561 vector<std::string> bandNames;
562
563 if(!net.create_from_file(model_opt[0],offset,scale,classValueMap,nameVector,bandNames)){
564 std::ostringstream errorStream;
565 errorStream << "Error: could not create neural network from file " << model_opt[0];
566 throw(errorStream.str());
567 }
568
569 //todo: check if get_num_output() is really the number of classes
570 unsigned int nclass=net.get_num_output();
571 unsigned int nband=bandNames.size()?bandNames.size():offset.size();//todo: find a more elegant way to define number of bands (in model?)
572
573 //normalize priors from command line
574 if(priors_opt.size()>1){//priors from argument list
575 priors.resize(priors_opt.size());
576 double normPrior=0;
577 for(unsigned int iclass=0;iclass<priors_opt.size();++iclass){
578 priors[iclass]=priors_opt[iclass];
579 normPrior+=priors[iclass];
580 }
581 //normalize
582 for(unsigned int iclass=0;iclass<priors_opt.size();++iclass)
583 priors[iclass]/=normPrior;
584 }
585 else{//default: equal priors for each class
586 if(priors_opt.size()==1){
587 priors.resize(nclass);
588 for(short iclass=0;iclass<nclass;++iclass)
589 priors[iclass]=1.0/nclass;
590 }
591 }
592
593 //convert start and end band options to vector of band indexes
594 if(bstart_opt.size()){
595 if(bend_opt.size()!=bstart_opt.size()){
596 string errorstring="Error: options for start and end band indexes must be provided as pairs, missing end band";
597 throw(errorstring);
598 }
599 band_opt.clear();
600 for(unsigned int ipair=0;ipair<bstart_opt.size();++ipair){
601 if(bend_opt[ipair]<=bstart_opt[ipair]){
602 string errorstring="Error: index for end band must be smaller then start band";
603 throw(errorstring);
604 }
605 for(unsigned int iband=bstart_opt[ipair];iband<=bend_opt[ipair];++iband)
606 band_opt.push_back(iband);
607 }
608 }
609
610 //sort bands
611 if(band_opt.size())
612 std::sort(band_opt.begin(),band_opt.end());
613 else{
614 unsigned short iband=0;
615 while(band_opt.size()<nrOfBand())
616 band_opt.push_back(iband++);
617 }
618
619 // if(classname_opt.size()){
620 // assert(classname_opt.size()==classvalue_opt.size());
621 // for(unsigned int iclass=0;iclass<classname_opt.size();++iclass)
622 // classValueMap[classname_opt[iclass]]=classvalue_opt[iclass];
623 // }
624
625 const char* pszMessage;
626 void* pProgressArg=NULL;
627 GDALProgressFunc pfnProgress=GDALTermProgress;
628 float progress=0;
629 if(!verbose_opt[0])
630 MyProgressFunc(progress,pszMessage,pProgressArg);
631
632 //-------------------------------- open image file ------------------------------------
633 bool inputIsRaster=true;
634 int nrow=nrOfRow();
635 int ncol=nrOfCol();
636 if(this->isInit()){
637 if(verbose_opt[0]>=1)
638 std::cout << "opening image" << std::endl;
639 // imgWriter.open(*this,false);
640 imgWriter.open(ncol,nrow,1,GDT_Byte);
641 imgWriter.GDALSetNoDataValue(dstnodata_opt[0]);
642 imgWriter.copyGeoTransform(*this);
643 imgWriter.setProjection(this->getProjection());
644 if(colorTable_opt.size())
645 imgWriter.setColorTable(colorTable_opt[0],0);
646 Jim priorReader;
647 if(priorimg_opt.size()){
648 if(verbose_opt[0]>=1)
649 std::cout << "opening prior image " << priorimg_opt[0] << std::endl;
650 priorReader.open(priorimg_opt[0]);
651 assert(priorReader.nrOfCol()==ncol);
652 assert(priorReader.nrOfRow()==nrow);
653 }
654
655 vector<char> classOut(ncol);//classified line for writing to image file
656
657 Jim probImage;
658 Jim entropyImage;
659
660 string imageType=imgWriter.getImageType();
661 if(prob_opt.size()){
662 probImage.open(prob_opt[0],ncol,nrow,nclass,GDT_Byte,imageType);
663 probImage.GDALSetNoDataValue(dstnodata_opt[0]);
664 probImage.copyGeoTransform(imgWriter);
665 probImage.setProjection(this->getProjection());
666 }
667 if(entropy_opt.size()){
668 entropyImage.open(entropy_opt[0],ncol,nrow,1,GDT_Byte,imageType);
669 entropyImage.GDALSetNoDataValue(dstnodata_opt[0]);
670 entropyImage.copyGeoTransform(imgWriter);
671 entropyImage.setProjection(this->getProjection());
672 }
673
674 if(mask_opt.size()){
675 if(verbose_opt[0]>=1)
676 std::cout << "opening mask image file " << mask_opt[0] << std::endl;
677 maskReader.open(mask_opt[0]);
678 }
679
680 for(unsigned int iline=0;iline<nrow;++iline){
681 vector<float> buffer(ncol);
682 vector<short> lineMask;
683 Vector2d<float> linePrior;
684 if(priorimg_opt.size())
685 linePrior.resize(nclass,ncol);//prior prob for each class
686 Vector2d<float> hpixel(ncol);
687 Vector2d<float> fpixel(ncol);
688 Vector2d<float> probOut(nclass,ncol);//posterior prob for each (internal) class
689 vector<float> entropy(ncol);
690 if(band_opt.size()){
691 for(unsigned int iband=0;iband<band_opt.size();++iband){
692 if(verbose_opt[0]==2)
693 std::cout << "reading band " << band_opt[iband] << std::endl;
694 assert(band_opt[iband]>=0);
695 assert(band_opt[iband]<nrOfBand());
696 readData(buffer,iline,band_opt[iband]);
697 for(unsigned int icol=0;icol<ncol;++icol)
698 hpixel[icol].push_back(buffer[icol]);
699 }
700 }
701 else{
702 for(unsigned int iband=0;iband<nband;++iband){
703 if(verbose_opt[0]==2)
704 std::cout << "reading band " << iband << std::endl;
705 assert(iband>=0);
706 assert(iband<nrOfBand());
707 readData(buffer,iline,iband);
708 for(unsigned int icol=0;icol<ncol;++icol)
709 hpixel[icol].push_back(buffer[icol]);
710 }
711 }
712 assert(nband==hpixel[0].size());
713 if(verbose_opt[0]==2)
714 std::cout << "used bands: " << nband << std::endl;
715 //read prior
716 if(priorimg_opt.size()){
717 for(short iclass=0;iclass<nclass;++iclass){
718 if(verbose_opt.size()>1)
719 std::cout << "Reading " << priorimg_opt[0] << " band " << iclass << " line " << iline << std::endl;
720 priorReader.readData(linePrior[iclass],iline,iclass);
721 }
722 }
723 double oldRowMask=-1;//keep track of row mask to optimize number of line readings
724 //process per pixel
725 for(unsigned int icol=0;icol<ncol;++icol){
726 assert(hpixel[icol].size()==nband);
727 bool doClassify=true;
728 bool masked=false;
729 double geox=0;
730 double geoy=0;
731 if(maskReader.isInit()){
732 //read mask
733 double colMask=0;
734 double rowMask=0;
735
736 imgWriter.image2geo(icol,iline,geox,geoy);
737 maskReader.geo2image(geox,geoy,colMask,rowMask);
738 colMask=static_cast<int>(colMask);
739 rowMask=static_cast<int>(rowMask);
740 if(rowMask>=0&&rowMask<maskReader.nrOfRow()&&colMask>=0&&colMask<maskReader.nrOfCol()){
741 if(static_cast<int>(rowMask)!=static_cast<int>(oldRowMask)){
742 assert(rowMask>=0&&rowMask<maskReader.nrOfRow());
743 // maskReader.readData(lineMask[imask],GDT_Int32,static_cast<unsigned int>(rowMask));
744 maskReader.readData(lineMask,static_cast<unsigned int>(rowMask));
745 oldRowMask=rowMask;
746 }
747 short theMask=0;
748 for(short ivalue=0;ivalue<msknodata_opt.size();++ivalue){
749 // if(msknodata_opt[ivalue]>=0){//values set in msknodata_opt are invalid
750 if(lineMask[colMask]==msknodata_opt[ivalue]){
751 theMask=lineMask[colMask];
752 masked=true;
753 break;
754 }
755 }
756 if(masked){
757 classOut[icol]=theMask;
758 continue;
759 }
760 }
761 }
762 bool valid=false;
763 for(int iband=0;iband<hpixel[icol].size();++iband){
764 if(hpixel[icol][iband]!=srcnodata_opt[0]){
765 valid=true;
766 break;
767 }
768 }
769 if(!valid)
770 doClassify=false;
771 for(short iclass=0;iclass<nclass;++iclass)
772 probOut[iclass][icol]=0;
773 if(!doClassify){
774 classOut[icol]=dstnodata_opt[0];
775 continue;//next column
776 }
777 //----------------------------------- classification -------------------
778 //calculate image features
779 fpixel[icol].clear();
780 for(int iband=0;iband<nband;++iband)
781 fpixel[icol].push_back((hpixel[icol][iband]-offset[iband])/scale[iband]);
782 vector<float> result(nclass);
783 result=net.run(fpixel[icol]);
784 vector<float> prValues(nclass);
785 float maxP=0;
786
787 double normPrior=0;
788 if(priorimg_opt.size()){
789 for(short iclass=0;iclass<nclass;++iclass)
790 normPrior+=linePrior[iclass][icol];
791 }
792 for(short iclass=0;iclass<nclass;++iclass){
793 result[iclass]=(result[iclass]+1.0)/2.0;//bring back to scale [0,1]
794 if(priorimg_opt.size())
795 priors[iclass]=linePrior[iclass][icol]/normPrior;//todo: check if correct for all cases... (automatic classValueMap and manual input for names and values)
796 probOut[iclass][icol]=result[iclass]*priors[iclass];
797 }
798
799 //search for max class prob
800 float max1=0;//max probability
801 float max2=0;//second max probability
802 float norm=0;
803 for(short iclass=0;iclass<nclass;++iclass){
804 if(probOut[iclass][icol]>max1){
805 max1=probOut[iclass][icol];
806 classOut[icol]=classValueMap[nameVector[iclass]];
807 }
808 else if(probOut[iclass][icol]>max2)
809 max2=probOut[iclass][icol];
810 norm+=probOut[iclass][icol];
811 }
812 //normalize probOut and convert to percentage
813 entropy[icol]=0;
814 for(short iclass=0;iclass<nclass;++iclass){
815 float prv=probOut[iclass][icol];
816 prv/=norm;
817 entropy[icol]-=prv*log(prv)/log(2.0);
818 prv*=100.0;
819
820 probOut[iclass][icol]=static_cast<short>(prv+0.5);
821 }
822 entropy[icol]/=log(static_cast<double>(nclass))/log(2.0);
823 entropy[icol]=static_cast<short>(100*entropy[icol]+0.5);
824 }//icol
825 //----------------------------------- write output ------------------------------------------
826 if(prob_opt.size()){
827 for(unsigned int iclass=0;iclass<nclass;++iclass)
828 probImage.writeData(probOut[iclass],iline,iclass);
829 }
830 if(entropy_opt.size()){
831 entropyImage.writeData(entropy,iline);
832 }
833 imgWriter.writeData(classOut,iline);
834 if(!verbose_opt[0]){
835 progress=static_cast<float>(iline+1.0)/imgWriter.nrOfRow();
836 MyProgressFunc(progress,pszMessage,pProgressArg);
837 }
838 }
839 // imgWriter.close();
840 if(mask_opt.size())
841 maskReader.close();
842 if(priorimg_opt.size())
843 priorReader.close();
844 if(prob_opt.size())
845 probImage.close();
846 if(entropy_opt.size())
847 entropyImage.close();
848 }
849 }
850 catch(BadConversion conversionString){
851 std::cerr << "Error: did you provide class pairs names (-c) and integer values (-r) for each class in training vector?" << std::endl;
852 throw;
853 }
854 catch(string predefinedString){
855 std::cout << predefinedString << std::endl;
856 throw;
857 }
858 }
859
860 /**
861 * @param imgWriter output classified raster dataset
862 * @param app application specific option arguments
863 * @return CE_None if successful, CE_Failure if failed
864 **/
865 // CPLErr Jim::ann(Jim& imgWriter, app::AppFactory& app){
866 // vector<double> priors;
867
868 // //--------------------------- command line options ------------------------------------
869 // Optionjl<string> training_opt("t", "training", "training vector file. A single vector file contains all training features (must be set as: B0, B1, B2,...) for all classes (class numbers identified by label option). Use multiple training files for bootstrap aggregation (alternative to the bag and bsize options, where a random subset is taken from a single training file)");
870 // Optionjl<string> tlayer_opt("tln", "tln", "training layer name(s)");
871 // Optionjl<string> label_opt("label", "label", "identifier for class label in training vector file.","label");
872 // Optionjl<unsigned int> balance_opt("bal", "balance", "balance the input data to this number of samples for each class", 0);
873 // Optionjl<bool> random_opt("random", "random", "in case of balance, randomize input data", true,2);
874 // Optionjl<int> minSize_opt("min", "min", "if number of training pixels is less then min, do not take this class into account (0: consider all classes)", 0);
875 // Optionjl<unsigned int> band_opt("b", "band", "band index (starting from 0, either use band option or use start to end)");
876 // Optionjl<unsigned int> bstart_opt("sband", "startband", "Start band sequence number");
877 // Optionjl<unsigned int> bend_opt("eband", "endband", "End band sequence number");
878 // Optionjl<double> offset_opt("offset", "offset", "offset value for each spectral band input features: refl[band]=(DN[band]-offset[band])/scale[band]", 0.0);
879 // Optionjl<double> scale_opt("scale", "scale", "scale value for each spectral band input features: refl=(DN[band]-offset[band])/scale[band] (use 0 if scale min and max in each band to -1.0 and 1.0)", 0.0);
880 // Optionjl<double> priors_opt("prior", "prior", "prior probabilities for each class (e.g., -p 0.3 -p 0.3 -p 0.2 )", 0.0);
881 // Optionjl<string> priorimg_opt("pim", "priorimg", "prior probability image (multi-band img with band for each class","",2);
882 // Optionjl<unsigned short> cv_opt("cv", "cv", "n-fold cross validation mode",0);
883 // Optionjl<string> cmformat_opt("cmf","cmf","Format for confusion matrix (ascii or latex)","ascii");
884 // Optionjl<unsigned short> comb_opt("comb", "comb", "how to combine bootstrap aggregation classifiers (0: sum rule, 1: product rule, 2: max rule). Also used to aggregate classes with rc option. Default is sum rule (0)",0);
885 // Optionjl<unsigned short> bag_opt("bag", "bag", "Number of bootstrap aggregations (default is no bagging: 1)", 1);
886 // Optionjl<int> bagSize_opt("bs", "bsize", "Percentage of features used from available training features for each bootstrap aggregation (one size for all classes, or a different size for each class respectively", 100);
887 // Optionjl<string> classBag_opt("cb", "classbag", "output for each individual bootstrap aggregation (default is blank)");
888 // Optionjl<string> extent_opt("e", "extent", "Only classify within extent from polygons in vector file");
889 // Optionjl<string> eoption_opt("eo","eo", "special extent options controlling rasterization: ATTRIBUTE|CHUNKYSIZE|ALL_TOUCHED|BURN_VALUE_FROM|MERGE_ALG, e.g., -eo ATTRIBUTE=fieldname");
890 // Optionjl<string> mask_opt("m", "mask", "Only classify within specified mask (vector or raster). For raster mask, set nodata values with the option msknodata.");
891 // Optionjl<short> msknodata_opt("msknodata", "msknodata", "mask value(s) not to consider for classification. Values will be taken over in classification image. Default is 0", 0);
892 // Optionjl<unsigned short> nodata_opt("nodata", "nodata", "nodata value to put where image is masked as nodata", 0);
893 // Optionjl<string> output_opt("o", "output", "output classification image");
894 // Optionjl<string> otype_opt("ot", "otype", "Data type for output image ({Byte/Int16/UInt16/UInt32/Int32/Float32/Float64/CInt16/CInt32/CFloat32/CFloat64}). Empty string: inherit type from input image");
895 // Optionjl<string> colorTable_opt("ct", "ct", "colour table in ASCII format having 5 columns: id R G B ALFA (0: transparent, 255: solid)");
896 // Optionjl<string> prob_opt("\0", "prob", "probability image. Default is no probability image");
897 // Optionjl<string> entropy_opt("entropy", "entropy", "entropy image (measure for uncertainty of classifier output","",2);
898 // Optionjl<string> active_opt("active", "active", "ogr output for active training sample.","",2);
899 // Optionjl<string> ogrformat_opt("f", "f", "Output ogr format for active training sample","SQLite");
900 // Optionjl<unsigned int> nactive_opt("na", "nactive", "number of active training points",1);
901 // Optionjl<string> classname_opt("c", "class", "list of class names.");
902 // Optionjl<short> classvalue_opt("r", "reclass", "list of class values (use same order as in class opt).");
903 // Optionjl<short> verbose_opt("v", "verbose", "set to: 0 (results only), 1 (confusion matrix), 2 (debug)",0,2);
904 // Optionjl<unsigned int> nneuron_opt("nn", "nneuron", "number of neurons in hidden layers in neural network (multiple hidden layers are set by defining multiple number of neurons: -n 15 -n 1, default is one hidden layer with 5 neurons)", 5);
905 // Optionjl<float> connection_opt("\0", "connection", "connection reate (default: 1.0 for a fully connected network)", 1.0);
906 // Optionjl<float> learning_opt("l", "learning", "learning rate (default: 0.7)", 0.7);
907 // Optionjl<float> weights_opt("w", "weights", "weights for neural network. Apply to fully connected network only, starting from first input neuron to last output neuron, including the bias neurons (last neuron in each but last layer)", 0.0);
908 // Optionjl<unsigned int> maxit_opt("\0", "maxit", "number of maximum iterations (epoch) (default: 500)", 500);
909 // extent_opt.setHide(1);
910 // eoption_opt.setHide(1);
911 // band_opt.setHide(1);
912 // bstart_opt.setHide(1);
913 // bend_opt.setHide(1);
914 // balance_opt.setHide(1);
915 // minSize_opt.setHide(1);
916 // bag_opt.setHide(1);
917 // bagSize_opt.setHide(1);
918 // comb_opt.setHide(1);
919 // classBag_opt.setHide(1);
920 // minSize_opt.setHide(1);
921 // prob_opt.setHide(1);
922 // priorimg_opt.setHide(1);
923 // minSize_opt.setHide(1);
924 // offset_opt.setHide(1);
925 // scale_opt.setHide(1);
926 // connection_opt.setHide(1);
927 // weights_opt.setHide(1);
928 // maxit_opt.setHide(1);
929 // learning_opt.setHide(1);
930 // verbose_opt.setHide(2);
931
932 // bool doProcess;//stop process when program was invoked with help option (-h --help)
933 // try{
934 // doProcess=training_opt.retrieveOption(app);
935 // cv_opt.retrieveOption(app);
936 // cmformat_opt.retrieveOption(app);
937 // tlayer_opt.retrieveOption(app);
938 // classname_opt.retrieveOption(app);
939 // classvalue_opt.retrieveOption(app);
940 // ogrformat_opt.retrieveOption(app);
941 // colorTable_opt.retrieveOption(app);
942 // label_opt.retrieveOption(app);
943 // priors_opt.retrieveOption(app);
944 // extent_opt.retrieveOption(app);
945 // balance_opt.retrieveOption(app);
946 // random_opt.retrieveOption(app);
947 // minSize_opt.retrieveOption(app);
948 // band_opt.retrieveOption(app);
949 // bstart_opt.retrieveOption(app);
950 // bend_opt.retrieveOption(app);
951 // offset_opt.retrieveOption(app);
952 // scale_opt.retrieveOption(app);
953 // priorimg_opt.retrieveOption(app);
954 // comb_opt.retrieveOption(app);
955 // bag_opt.retrieveOption(app);
956 // bagSize_opt.retrieveOption(app);
957 // classBag_opt.retrieveOption(app);
958 // mask_opt.retrieveOption(app);
959 // msknodata_opt.retrieveOption(app);
960 // nodata_opt.retrieveOption(app);
961 // output_opt.retrieveOption(app);
962 // otype_opt.retrieveOption(app);
963 // prob_opt.retrieveOption(app);
964 // entropy_opt.retrieveOption(app);
965 // active_opt.retrieveOption(app);
966 // nactive_opt.retrieveOption(app);
967 // verbose_opt.retrieveOption(app);
968 // nneuron_opt.retrieveOption(app);
969 // connection_opt.retrieveOption(app);
970 // weights_opt.retrieveOption(app);
971 // learning_opt.retrieveOption(app);
972 // maxit_opt.retrieveOption(app);
973
974 // if(!doProcess){
975 // std::cout << std::endl;
976 // std::ostringstream helpStream;
977 // helpStream << "short option -h shows basic options only, use long option --help to show all options" << std::endl;
978 // throw(helpStream.str());//help was invoked, stop processing
979 // }
980
981 // if(entropy_opt[0]=="")
982 // entropy_opt.clear();
983 // if(active_opt[0]=="")
984 // active_opt.clear();
985 // if(priorimg_opt[0]=="")
986 // priorimg_opt.clear();
987
988 // if(training_opt.empty()){
989 // string errorString="Error: no training vector dataset provided";
990 // throw(errorString);
991 // }
992
993 // if(verbose_opt[0]>=1){
994 // if(mask_opt.size())
995 // std::cout << "mask filename: " << mask_opt[0] << std::endl;
996 // std::cout << "training vector file: " << std::endl;
997 // for(unsigned int ifile=0;ifile<training_opt.size();++ifile)
998 // std::cout << training_opt[ifile] << std::endl;
999 // }
1000 // unsigned short nbag=(training_opt.size()>1)?training_opt.size():bag_opt[0];
1001 // if(verbose_opt[0]>=1)
1002 // std::cout << "number of bootstrap aggregations: " << nbag << std::endl;
1003
1004 // ImgReaderOgr extentReader;
1005 // Jim maskReader;
1006 // // OGRLayer *readLayer;
1007
1008 // double ulx=0;
1009 // double uly=0;
1010 // double lrx=0;
1011 // double lry=0;
1012
1013 // // bool maskIsVector=false;
1014 // if(extent_opt.size()){
1015 // if(mask_opt.size()){
1016 // string errorString="Error: can only either mask or extent, not both";
1017 // throw(errorString);
1018 // }
1019 // extentReader.open(extent_opt[0]);
1020 // // readLayer = extentReader.getDataSource()->GetLayer(0);
1021 // if(!(extentReader.getExtent(ulx,uly,lrx,lry))){
1022 // cerr << "Error: could not get extent from " << mask_opt[0] << endl;
1023 // exit(1);
1024 // }
1025 // maskReader.open(this->nrOfCol(),this->nrOfRow(),1,GDT_Float64);
1026 // double gt[6];
1027 // this->getGeoTransform(gt);
1028 // maskReader.setGeoTransform(gt);
1029 // maskReader.setProjection(this->getProjection());
1030 // // vector<double> burnValues(1,1);//burn value is 1 (single band)
1031 // maskReader.rasterizeBuf(extentReader,nodata_opt[0],eoption_opt);
1032 // maskReader.GDALSetNoDataValue(nodata_opt[0]);
1033 // extentReader.close();
1034 // }
1035
1036 // ImgWriterOgr activeWriter;
1037 // if(active_opt.size()){
1038 // ImgReaderOgr trainingReader(training_opt[0]);
1039 // activeWriter.open(active_opt[0],ogrformat_opt[0]);
1040 // activeWriter.createLayer(active_opt[0],trainingReader.getProjection(),wkbPoint,NULL);
1041 // activeWriter.copyFields(trainingReader);
1042 // }
1043 // vector<PosValue> activePoints(nactive_opt[0]);
1044 // for(unsigned int iactive=0;iactive<activePoints.size();++iactive){
1045 // activePoints[iactive].value=1.0;
1046 // activePoints[iactive].posx=0.0;
1047 // activePoints[iactive].posy=0.0;
1048 // }
1049
1050 // unsigned int totalSamples=0;
1051 // unsigned int nactive=0;
1052 // vector<FANN::neural_net> net(nbag);//the neural network
1053
1054 // unsigned int nclass=0;
1055 // unsigned int nband=0;
1056 // unsigned int startBand=2;//first two bands represent X and Y pos
1057
1058 // //normalize priors from command line
1059 // if(priors_opt.size()>1){//priors from argument list
1060 // priors.resize(priors_opt.size());
1061 // double normPrior=0;
1062 // for(unsigned int iclass=0;iclass<priors_opt.size();++iclass){
1063 // priors[iclass]=priors_opt[iclass];
1064 // normPrior+=priors[iclass];
1065 // }
1066 // //normalize
1067 // for(unsigned int iclass=0;iclass<priors_opt.size();++iclass)
1068 // priors[iclass]/=normPrior;
1069 // }
1070
1071 // //convert start and end band options to vector of band indexes
1072 // if(bstart_opt.size()){
1073 // if(bend_opt.size()!=bstart_opt.size()){
1074 // string errorstring="Error: options for start and end band indexes must be provided as pairs, missing end band";
1075 // throw(errorstring);
1076 // }
1077 // band_opt.clear();
1078 // for(unsigned int ipair=0;ipair<bstart_opt.size();++ipair){
1079 // if(bend_opt[ipair]<=bstart_opt[ipair]){
1080 // string errorstring="Error: index for end band must be smaller then start band";
1081 // throw(errorstring);
1082 // }
1083 // for(unsigned int iband=bstart_opt[ipair];iband<=bend_opt[ipair];++iband)
1084 // band_opt.push_back(iband);
1085 // }
1086 // }
1087
1088 // //sort bands
1089 // if(band_opt.size())
1090 // std::sort(band_opt.begin(),band_opt.end());
1091
1092 // map<string,short> classValueMap;
1093 // vector<std::string> nameVector;
1094 // if(classname_opt.size()){
1095 // assert(classname_opt.size()==classvalue_opt.size());
1096 // for(unsigned int iclass=0;iclass<classname_opt.size();++iclass)
1097 // classValueMap[classname_opt[iclass]]=classvalue_opt[iclass];
1098 // }
1099
1100 // //----------------------------------- Training -------------------------------
1101 // confusionmatrix::ConfusionMatrix cm;
1102 // vector< vector<double> > offset(nbag);
1103 // vector< vector<double> > scale(nbag);
1104 // map<string,Vector2d<float> > trainingMap;
1105 // vector< Vector2d<float> > trainingPixels;//[class][sample][band]
1106 // vector<string> fields;
1107 // for(unsigned int ibag=0;ibag<nbag;++ibag){
1108 // //organize training data
1109 // if(ibag<training_opt.size()){//if bag contains new training pixels
1110 // trainingMap.clear();
1111 // trainingPixels.clear();
1112 // if(verbose_opt[0]>=1)
1113 // std::cout << "reading imageVector file " << training_opt[0] << std::endl;
1114 // ImgReaderOgr trainingReaderBag(training_opt[ibag]);
1115 // if(band_opt.size())
1116 // totalSamples=trainingReaderBag.readDataImageOgr(trainingMap,fields,band_opt,label_opt[0],tlayer_opt);
1117 // else
1118 // totalSamples=trainingReaderBag.readDataImageOgr(trainingMap,fields,0,0,label_opt[0],tlayer_opt);
1119 // if(trainingMap.size()<2){
1120 // string errorstring="Error: could not read at least two classes from training file, did you provide class labels in training sample (see option label)?";
1121 // throw(errorstring);
1122 // }
1123 // trainingReaderBag.close();
1124 // //convert map to vector
1125 // if(verbose_opt[0]>1)
1126 // std::cout << "training pixels: " << std::endl;
1127 // map<string,Vector2d<float> >::iterator mapit=trainingMap.begin();
1128 // while(mapit!=trainingMap.end()){
1129 // //delete small classes
1130 // if((mapit->second).size()<minSize_opt[0]){
1131 // trainingMap.erase(mapit);
1132 // continue;
1133 // }
1134 // trainingPixels.push_back(mapit->second);
1135 // if(verbose_opt[0]>1)
1136 // std::cout << mapit->first << ": " << (mapit->second).size() << " samples" << std::endl;
1137 // ++mapit;
1138 // }
1139 // if(!ibag){
1140 // nclass=trainingPixels.size();
1141 // if(classname_opt.size())
1142 // assert(nclass==classname_opt.size());
1143 // nband=(training_opt.size())?trainingPixels[0][0].size()-2:trainingPixels[0][0].size();//X and Y
1144 // }
1145 // else{
1146 // assert(nclass==trainingPixels.size());
1147 // assert(nband==(training_opt.size())?trainingPixels[0][0].size()-2:trainingPixels[0][0].size());
1148 // }
1149
1150 // //do not remove outliers here: could easily be obtained through ogr2ogr -where 'B2<110' output.shp input.shp
1151 // //balance training data
1152 // if(balance_opt[0]>0){
1153 // while(balance_opt.size()<nclass)
1154 // balance_opt.push_back(balance_opt.back());
1155 // if(random_opt[0])
1156 // srand(time(NULL));
1157 // totalSamples=0;
1158 // for(short iclass=0;iclass<nclass;++iclass){
1159 // if(trainingPixels[iclass].size()>balance_opt[iclass]){
1160 // while(trainingPixels[iclass].size()>balance_opt[iclass]){
1161 // int index=rand()%trainingPixels[iclass].size();
1162 // trainingPixels[iclass].erase(trainingPixels[iclass].begin()+index);
1163 // }
1164 // }
1165 // else{
1166 // int oldsize=trainingPixels[iclass].size();
1167 // for(int isample=trainingPixels[iclass].size();isample<balance_opt[iclass];++isample){
1168 // int index = rand()%oldsize;
1169 // trainingPixels[iclass].push_back(trainingPixels[iclass][index]);
1170 // }
1171 // }
1172 // totalSamples+=trainingPixels[iclass].size();
1173 // }
1174 // }
1175
1176 // //set scale and offset
1177 // offset[ibag].resize(nband);
1178 // scale[ibag].resize(nband);
1179 // if(offset_opt.size()>1)
1180 // assert(offset_opt.size()==nband);
1181 // if(scale_opt.size()>1)
1182 // assert(scale_opt.size()==nband);
1183 // for(unsigned int iband=0;iband<nband;++iband){
1184 // if(verbose_opt[0]>=1)
1185 // std::cout << "scaling for band" << iband << std::endl;
1186 // offset[ibag][iband]=(offset_opt.size()==1)?offset_opt[0]:offset_opt[iband];
1187 // scale[ibag][iband]=(scale_opt.size()==1)?scale_opt[0]:scale_opt[iband];
1188 // //search for min and maximum
1189 // if(scale[ibag][iband]<=0){
1190 // float theMin=trainingPixels[0][0][iband+startBand];
1191 // float theMax=trainingPixels[0][0][iband+startBand];
1192 // for(short iclass=0;iclass<nclass;++iclass){
1193 // for(int isample=0;isample<trainingPixels[iclass].size();++isample){
1194 // if(theMin>trainingPixels[iclass][isample][iband+startBand])
1195 // theMin=trainingPixels[iclass][isample][iband+startBand];
1196 // if(theMax<trainingPixels[iclass][isample][iband+startBand])
1197 // theMax=trainingPixels[iclass][isample][iband+startBand];
1198 // }
1199 // }
1200 // offset[ibag][iband]=theMin+(theMax-theMin)/2.0;
1201 // scale[ibag][iband]=(theMax-theMin)/2.0;
1202 // if(verbose_opt[0]>=1){
1203 // std::cout << "Extreme image values for band " << iband << ": [" << theMin << "," << theMax << "]" << std::endl;
1204 // std::cout << "Using offset, scale: " << offset[ibag][iband] << ", " << scale[ibag][iband] << std::endl;
1205 // std::cout << "scaled values for band " << iband << ": [" << (theMin-offset[ibag][iband])/scale[ibag][iband] << "," << (theMax-offset[ibag][iband])/scale[ibag][iband] << "]" << std::endl;
1206 // }
1207 // }
1208 // }
1209 // }
1210 // else{//use same offset and scale
1211 // offset[ibag].resize(nband);
1212 // scale[ibag].resize(nband);
1213 // for(int iband=0;iband<nband;++iband){
1214 // offset[ibag][iband]=offset[0][iband];
1215 // scale[ibag][iband]=scale[0][iband];
1216 // }
1217 // }
1218
1219 // if(!ibag){
1220 // if(priors_opt.size()==1){//default: equal priors for each class
1221 // priors.resize(nclass);
1222 // for(short iclass=0;iclass<nclass;++iclass)
1223 // priors[iclass]=1.0/nclass;
1224 // }
1225 // assert(priors_opt.size()==1||priors_opt.size()==nclass);
1226
1227 // //set bagsize for each class if not done already via command line
1228 // while(bagSize_opt.size()<nclass)
1229 // bagSize_opt.push_back(bagSize_opt.back());
1230
1231 // if(verbose_opt[0]>=1){
1232 // std::cout << "number of bands: " << nband << std::endl;
1233 // std::cout << "number of classes: " << nclass << std::endl;
1234 // std::cout << "priors:";
1235 // if(priorimg_opt.empty()){
1236 // for(short iclass=0;iclass<nclass;++iclass)
1237 // std::cout << " " << priors[iclass];
1238 // std::cout << std::endl;
1239 // }
1240 // }
1241 // map<string,Vector2d<float> >::iterator mapit=trainingMap.begin();
1242 // bool doSort=true;
1243 // while(mapit!=trainingMap.end()){
1244 // nameVector.push_back(mapit->first);
1245 // if(classValueMap.size()){
1246 // //check if name in training is covered by classname_opt (values can not be 0)
1247 // if(classValueMap[mapit->first]>0){
1248 // if(cm.getClassIndex(type2string<short>(classValueMap[mapit->first]))<0)
1249 // cm.pushBackClassName(type2string<short>(classValueMap[mapit->first]),doSort);
1250 // }
1251 // else{
1252 // std::cerr << "Error: names in classname option are not complete, please check names in training vector and make sure classvalue is > 0" << std::endl;
1253 // exit(1);
1254 // }
1255 // }
1256 // else
1257 // cm.pushBackClassName(mapit->first,doSort);
1258 // ++mapit;
1259 // }
1260 // if(classname_opt.empty()){
1261 // //std::cerr << "Warning: no class name and value pair provided for all " << nclass << " classes, using string2type<int> instead!" << std::endl;
1262 // for(short iclass=0;iclass<nclass;++iclass){
1263 // if(verbose_opt[0])
1264 // std::cout << iclass << " " << cm.getClass(iclass) << " -> " << string2type<short>(cm.getClass(iclass)) << std::endl;
1265 // classValueMap[cm.getClass(iclass)]=string2type<short>(cm.getClass(iclass));
1266 // }
1267 // }
1268 // // if(priors_opt.size()==nameVector.size()){
1269 // // std::cerr << "Warning: please check if priors are provided in correct order!!!" << std::endl;
1270 // // for(unsigned int iclass=0;iclass<nameVector.size();++iclass)
1271 // // std::cerr << nameVector[iclass] << " " << priors_opt[iclass] << std::endl;
1272 // // }
1273 // }//if(!ibag)
1274
1275 // //Calculate features of training set
1276 // vector< Vector2d<float> > trainingFeatures(nclass);
1277 // for(short iclass=0;iclass<nclass;++iclass){
1278 // int nctraining=0;
1279 // if(verbose_opt[0]>=1)
1280 // std::cout << "calculating features for class " << iclass << std::endl;
1281 // if(random_opt[0])
1282 // srand(time(NULL));
1283 // nctraining=(bagSize_opt[iclass]<100)? trainingPixels[iclass].size()/100.0*bagSize_opt[iclass] : trainingPixels[iclass].size();//bagSize_opt[iclass] given in % of training size
1284 // if(nctraining<=0)
1285 // nctraining=1;
1286 // assert(nctraining<=trainingPixels[iclass].size());
1287 // if(bagSize_opt[iclass]<100)
1288 // random_shuffle(trainingPixels[iclass].begin(),trainingPixels[iclass].end());
1289 // if(verbose_opt[0]>1)
1290 // std::cout << "nctraining (class " << iclass << "): " << nctraining << std::endl;
1291 // trainingFeatures[iclass].resize(nctraining);
1292 // for(int isample=0;isample<nctraining;++isample){
1293 // //scale pixel values according to scale and offset!!!
1294 // for(int iband=0;iband<nband;++iband){
1295 // float value=trainingPixels[iclass][isample][iband+startBand];
1296 // trainingFeatures[iclass][isample].push_back((value-offset[ibag][iband])/scale[ibag][iband]);
1297 // }
1298 // }
1299 // assert(trainingFeatures[iclass].size()==nctraining);
1300 // }
1301
1302 // unsigned int nFeatures=trainingFeatures[0][0].size();
1303 // if(verbose_opt[0]>=1)
1304 // std::cout << "number of features: " << nFeatures << std::endl;
1305 // unsigned int ntraining=0;
1306 // for(short iclass=0;iclass<nclass;++iclass)
1307 // ntraining+=trainingFeatures[iclass].size();
1308
1309 // const unsigned int num_layers = nneuron_opt.size()+2;
1310 // const float desired_error = 0.0003;
1311 // const unsigned int iterations_between_reports = (verbose_opt[0])? maxit_opt[0]+1:0;
1312 // if(verbose_opt[0]>=1){
1313 // std::cout << "number of features: " << nFeatures << std::endl;
1314 // std::cout << "creating artificial neural network with " << nneuron_opt.size() << " hidden layer, having " << std::endl;
1315 // for(unsigned int ilayer=0;ilayer<nneuron_opt.size();++ilayer)
1316 // std::cout << nneuron_opt[ilayer] << " ";
1317 // std::cout << "neurons" << std::endl;
1318 // std::cout << "connection_opt[0]: " << connection_opt[0] << std::endl;
1319 // std::cout << "num_layers: " << num_layers << std::endl;
1320 // std::cout << "nFeatures: " << nFeatures << std::endl;
1321 // std::cout << "nneuron_opt[0]: " << nneuron_opt[0] << std::endl;
1322 // std::cout << "number of classes (nclass): " << nclass << std::endl;
1323 // }
1324 // switch(num_layers){
1325 // case(3):{
1326 // // net[ibag].create_sparse(connection_opt[0],num_layers, nFeatures, nneuron_opt[0], nclass);//replace all create_sparse with create_sparse_array due to bug in FANN!
1327 // unsigned int layers[3];
1328 // layers[0]=nFeatures;
1329 // layers[1]=nneuron_opt[0];
1330 // layers[2]=nclass;
1331 // net[ibag].create_sparse_array(connection_opt[0],num_layers,layers);
1332 // break;
1333 // }
1334 // case(4):{
1335 // unsigned int layers[4];
1336 // layers[0]=nFeatures;
1337 // layers[1]=nneuron_opt[0];
1338 // layers[2]=nneuron_opt[1];
1339 // layers[3]=nclass;
1340 // // layers.push_back(nFeatures);
1341 // // for(int ihidden=0;ihidden<nneuron_opt.size();++ihidden)
1342 // // layers.push_back(nneuron_opt[ihidden]);
1343 // // layers.push_back(nclass);
1344 // net[ibag].create_sparse_array(connection_opt[0],num_layers,layers);
1345 // break;
1346 // }
1347 // default:
1348 // cerr << "Only 1 or 2 hidden layers are supported!" << std::endl;
1349 // exit(1);
1350 // break;
1351 // }
1352 // if(verbose_opt[0]>=1)
1353 // std::cout << "network created" << std::endl;
1354
1355 // net[ibag].set_learning_rate(learning_opt[0]);
1356
1357 // // net.set_activation_steepness_hidden(1.0);
1358 // // net.set_activation_steepness_output(1.0);
1359
1360 // net[ibag].set_activation_function_hidden(FANN::SIGMOID_SYMMETRIC_STEPWISE);
1361 // net[ibag].set_activation_function_output(FANN::SIGMOID_SYMMETRIC_STEPWISE);
1362
1363 // // Set additional properties such as the training algorithm
1364 // // net.set_training_algorithm(FANN::TRAIN_QUICKPROP);
1365
1366 // // Output network type and parameters
1367 // if(verbose_opt[0]>=1){
1368 // std::cout << std::endl << "Network Type : ";
1369 // switch (net[ibag].get_network_type())
1370 // {
1371 // case FANN::LAYER:
1372 // std::cout << "LAYER" << std::endl;
1373 // break;
1374 // case FANN::SHORTCUT:
1375 // std::cout << "SHORTCUT" << std::endl;
1376 // break;
1377 // default:
1378 // std::cout << "UNKNOWN" << std::endl;
1379 // break;
1380 // }
1381 // net[ibag].print_parameters();
1382 // }
1383
1384 // if(cv_opt[0]>1){
1385 // if(verbose_opt[0])
1386 // std::cout << "cross validation" << std::endl;
1387 // vector<unsigned short> referenceVector;
1388 // vector<unsigned short> outputVector;
1389 // float rmse=net[ibag].cross_validation(trainingFeatures,
1390 // ntraining,
1391 // cv_opt[0],
1392 // maxit_opt[0],
1393 // desired_error,
1394 // referenceVector,
1395 // outputVector,
1396 // verbose_opt[0]);
1397 // map<string,Vector2d<float> >::iterator mapit=trainingMap.begin();
1398 // for(unsigned int isample=0;isample<referenceVector.size();++isample){
1399 // string refClassName=nameVector[referenceVector[isample]];
1400 // string className=nameVector[outputVector[isample]];
1401 // if(classValueMap.size())
1402 // cm.incrementResult(type2string<short>(classValueMap[refClassName]),type2string<short>(classValueMap[className]),1.0/nbag);
1403 // else
1404 // cm.incrementResult(cm.getClass(referenceVector[isample]),cm.getClass(outputVector[isample]),1.0/nbag);
1405 // }
1406 // }
1407
1408 // if(verbose_opt[0]>=1)
1409 // std::cout << std::endl << "Set training data" << std::endl;
1410
1411 // if(verbose_opt[0]>=1)
1412 // std::cout << std::endl << "Training network" << std::endl;
1413
1414 // if(verbose_opt[0]>=1){
1415 // std::cout << "Max Epochs " << setw(8) << maxit_opt[0] << ". "
1416 // << "Desired Error: " << left << desired_error << right << std::endl;
1417 // }
1418 // if(weights_opt.size()==net[ibag].get_total_connections()){//no new training needed (same training sample)
1419 // vector<fann_connection> convector;
1420 // net[ibag].get_connection_array(convector);
1421 // for(unsigned int i_connection=0;i_connection<net[ibag].get_total_connections();++i_connection)
1422 // convector[i_connection].weight=weights_opt[i_connection];
1423 // net[ibag].set_weight_array(convector);
1424 // }
1425 // else{
1426 // bool initWeights=true;
1427 // net[ibag].train_on_data(trainingFeatures,ntraining,initWeights, maxit_opt[0],
1428 // iterations_between_reports, desired_error);
1429 // }
1430
1431
1432 // if(verbose_opt[0]>=2){
1433 // net[ibag].print_connections();
1434 // vector<fann_connection> convector;
1435 // net[ibag].get_connection_array(convector);
1436 // for(unsigned int i_connection=0;i_connection<net[ibag].get_total_connections();++i_connection)
1437 // std::cout << "connection " << i_connection << ": " << convector[i_connection].weight << std::endl;
1438
1439 // }
1440 // }//for ibag
1441 // if(cv_opt[0]>1){
1442 // assert(cm.nReference());
1443 // cm.setFormat(cmformat_opt[0]);
1444 // cm.reportSE95(false);
1445 // std::cout << cm << std::endl;
1446 // // std::cout << "class #samples userAcc prodAcc" << std::endl;
1447 // // double se95_ua=0;
1448 // // double se95_pa=0;
1449 // // double se95_oa=0;
1450 // // double dua=0;
1451 // // double dpa=0;
1452 // // double doa=0;
1453 // // for(unsigned int iclass=0;iclass<cm.nClasses();++iclass){
1454 // // dua=cm.ua_pct(cm.getClass(iclass),&se95_ua);
1455 // // dpa=cm.pa_pct(cm.getClass(iclass),&se95_pa);
1456 // // std::cout << cm.getClass(iclass) << " " << cm.nReference(cm.getClass(iclass)) << " " << dua << " (" << se95_ua << ")" << " " << dpa << " (" << se95_pa << ")" << std::endl;
1457 // // }
1458 // // std::cout << "Kappa: " << cm.kappa() << std::endl;
1459 // // doa=cm.oa_pct(&se95_oa);
1460 // // std::cout << "Overall Accuracy: " << doa << " (" << se95_oa << ")" << std::endl;
1461 // }
1462 // //--------------------------------- end of training -----------------------------------
1463
1464 // const char* pszMessage;
1465 // void* pProgressArg=NULL;
1466 // GDALProgressFunc pfnProgress=GDALTermProgress;
1467 // float progress=0;
1468 // if(!verbose_opt[0])
1469 // MyProgressFunc(progress,pszMessage,pProgressArg);
1470 // //-------------------------------- open image file ------------------------------------
1471 // // bool inputIsRaster=false;
1472 // bool inputIsRaster=true;
1473 // // ImgReaderOgr imgReaderOgr;
1474 // // //todo: will not work in GDAL v2.0
1475 // // try{
1476 // // imgReaderOgr.open(input_opt[0]);
1477 // // imgReaderOgr.close();
1478 // // }
1479 // // catch(string errorString){
1480 // // inputIsRaster=true;
1481 // // }
1482 // // if(inputIsRaster){
1483 // int nrow=nrOfRow();
1484 // int ncol=nrOfCol();
1485 // if(this->isInit()){
1486 // if(verbose_opt[0]>=1)
1487 // std::cout << "opening image" << std::endl;
1488 // // imgWriter.open(*this,false);
1489 // imgWriter.open(ncol,nrow,1,GDT_Byte);
1490 // imgWriter.GDALSetNoDataValue(nodata_opt[0]);
1491 // imgWriter.copyGeoTransform(*this);
1492 // imgWriter.setProjection(this->getProjection());
1493 // if(colorTable_opt.size())
1494 // imgWriter.setColorTable(colorTable_opt[0],0);
1495 // Jim priorReader;
1496 // if(priorimg_opt.size()){
1497 // if(verbose_opt[0]>=1)
1498 // std::cout << "opening prior image " << priorimg_opt[0] << std::endl;
1499 // priorReader.open(priorimg_opt[0]);
1500 // assert(priorReader.nrOfCol()==ncol);
1501 // assert(priorReader.nrOfRow()==nrow);
1502 // }
1503
1504 // vector<char> classOut(ncol);//classified line for writing to image file
1505
1506 // // assert(nband==imgWriter.nrOfBand());
1507 // Jim classImageBag;
1508 // // Jim classImageOut;
1509 // Jim probImage;
1510 // Jim entropyImage;
1511
1512 // string imageType=imgWriter.getImageType();
1513 // if(classBag_opt.size()){
1514 // classImageBag.open(classBag_opt[0],ncol,nrow,nbag,GDT_Byte,imageType);
1515 // classImageBag.GDALSetNoDataValue(nodata_opt[0]);
1516 // classImageBag.copyGeoTransform(imgWriter);
1517 // classImageBag.setProjection(this->getProjection());
1518 // }
1519 // if(prob_opt.size()){
1520 // probImage.open(prob_opt[0],ncol,nrow,nclass,GDT_Byte,imageType);
1521 // probImage.GDALSetNoDataValue(nodata_opt[0]);
1522 // probImage.copyGeoTransform(imgWriter);
1523 // probImage.setProjection(this->getProjection());
1524 // }
1525 // if(entropy_opt.size()){
1526 // entropyImage.open(entropy_opt[0],ncol,nrow,1,GDT_Byte,imageType);
1527 // entropyImage.GDALSetNoDataValue(nodata_opt[0]);
1528 // entropyImage.copyGeoTransform(imgWriter);
1529 // entropyImage.setProjection(this->getProjection());
1530 // }
1531
1532 // // if(maskIsVector){
1533 // // //todo: produce unique name or perform in memory solving issue on flush memory buffer (check gdal development list on how to retrieve gdal mem buffer)
1534 // // maskWriter.open("/vsimem/mask.tif",ncol,nrow,1,GDT_Float32,imageType,memory_opt[0],option_opt);
1535 // // maskWriter.GDALSetNoDataValue(nodata_opt[0]);
1536 // // maskWriter.copyGeoTransform(testImage);
1537 // // maskWriter.setProjection(imgWriter.getProjection());
1538 // // vector<double> burnValues(1,1);//burn value is 1 (single band)
1539 // // maskWriter.rasterizeOgr(extentReader,burnValues);
1540 // // extentReader.close();
1541 // // maskWriter.close();
1542 // // mask_opt.clear();
1543 // // mask_opt.push_back("/vsimem/mask.tif");
1544 // // }
1545 // // // Jim maskReader;
1546 // if(mask_opt.size()){
1547 // if(verbose_opt[0]>=1)
1548 // std::cout << "opening mask image file " << mask_opt[0] << std::endl;
1549 // maskReader.open(mask_opt[0]);
1550 // }
1551
1552 // for(unsigned int iline=0;iline<nrow;++iline){
1553 // vector<float> buffer(ncol);
1554 // vector<short> lineMask;
1555 // Vector2d<float> linePrior;
1556 // if(priorimg_opt.size())
1557 // linePrior.resize(nclass,ncol);//prior prob for each class
1558 // Vector2d<float> hpixel(ncol);
1559 // Vector2d<float> fpixel(ncol);
1560 // Vector2d<float> probOut(nclass,ncol);//posterior prob for each (internal) class
1561 // vector<float> entropy(ncol);
1562 // Vector2d<char> classBag;//classified line for writing to image file
1563 // if(classBag_opt.size())
1564 // classBag.resize(nbag,ncol);
1565 // //read all bands of all pixels in this line in hline
1566 // if(band_opt.size()){
1567 // for(unsigned int iband=0;iband<band_opt.size();++iband){
1568 // if(verbose_opt[0]==2)
1569 // std::cout << "reading band " << band_opt[iband] << std::endl;
1570 // assert(band_opt[iband]>=0);
1571 // assert(band_opt[iband]<imgWriter.nrOfBand());
1572 // readData(buffer,iline,band_opt[iband]);
1573 // for(unsigned int icol=0;icol<ncol;++icol)
1574 // hpixel[icol].push_back(buffer[icol]);
1575 // }
1576 // }
1577 // else{
1578 // for(unsigned int iband=0;iband<nband;++iband){
1579 // if(verbose_opt[0]==2)
1580 // std::cout << "reading band " << iband << std::endl;
1581 // assert(iband>=0);
1582 // assert(iband<imgWriter.nrOfBand());
1583 // readData(buffer,iline,iband);
1584 // for(unsigned int icol=0;icol<ncol;++icol)
1585 // hpixel[icol].push_back(buffer[icol]);
1586 // }
1587 // }
1588 // assert(nband==hpixel[0].size());
1589 // if(verbose_opt[0]==2)
1590 // std::cout << "used bands: " << nband << std::endl;
1591 // //read prior
1592 // if(priorimg_opt.size()){
1593 // for(short iclass=0;iclass<nclass;++iclass){
1594 // if(verbose_opt.size()>1)
1595 // std::cout << "Reading " << priorimg_opt[0] << " band " << iclass << " line " << iline << std::endl;
1596 // priorReader.readData(linePrior[iclass],iline,iclass);
1597 // }
1598 // }
1599 // double oldRowMask=-1;//keep track of row mask to optimize number of line readings
1600 // //process per pixel
1601 // for(unsigned int icol=0;icol<ncol;++icol){
1602 // assert(hpixel[icol].size()==nband);
1603 // bool doClassify=true;
1604 // bool masked=false;
1605 // double geox=0;
1606 // double geoy=0;
1607 // if(maskReader.isInit()){
1608 // //read mask
1609 // double colMask=0;
1610 // double rowMask=0;
1611
1612 // imgWriter.image2geo(icol,iline,geox,geoy);
1613 // maskReader.geo2image(geox,geoy,colMask,rowMask);
1614 // colMask=static_cast<int>(colMask);
1615 // rowMask=static_cast<int>(rowMask);
1616 // if(rowMask>=0&&rowMask<maskReader.nrOfRow()&&colMask>=0&&colMask<maskReader.nrOfCol()){
1617 // if(static_cast<int>(rowMask)!=static_cast<int>(oldRowMask)){
1618 // assert(rowMask>=0&&rowMask<maskReader.nrOfRow());
1619 // // maskReader.readData(lineMask[imask],GDT_Int32,static_cast<unsigned int>(rowMask));
1620 // maskReader.readData(lineMask,static_cast<unsigned int>(rowMask));
1621 // oldRowMask=rowMask;
1622 // }
1623 // short theMask=0;
1624 // for(short ivalue=0;ivalue<msknodata_opt.size();++ivalue){
1625 // // if(msknodata_opt[ivalue]>=0){//values set in msknodata_opt are invalid
1626 // if(lineMask[colMask]==msknodata_opt[ivalue]){
1627 // theMask=lineMask[colMask];
1628 // masked=true;
1629 // break;
1630 // }
1631 // // }
1632 // // else{//only values set in msknodata_opt are valid
1633 // // if(lineMask[colMask]!=-msknodata_opt[ivalue]){
1634 // // theMask=lineMask[colMask];
1635 // // masked=true;
1636 // // }
1637 // // else{
1638 // // masked=false;
1639 // // break;
1640 // // }
1641 // // }
1642 // }
1643 // if(masked){
1644 // if(classBag_opt.size())
1645 // for(unsigned int ibag=0;ibag<nbag;++ibag)
1646 // classBag[ibag][icol]=theMask;
1647 // classOut[icol]=theMask;
1648 // continue;
1649 // }
1650 // }
1651 // bool valid=false;
1652 // for(unsigned int iband=0;iband<hpixel[icol].size();++iband){
1653 // if(hpixel[icol][iband]){
1654 // valid=true;
1655 // break;
1656 // }
1657 // }
1658 // if(!valid)
1659 // doClassify=false;
1660 // }
1661 // for(short iclass=0;iclass<nclass;++iclass)
1662 // probOut[iclass][icol]=0;
1663 // if(!doClassify){
1664 // if(classBag_opt.size())
1665 // for(int ibag=0;ibag<nbag;++ibag)
1666 // classBag[ibag][icol]=nodata_opt[0];
1667 // classOut[icol]=nodata_opt[0];
1668 // continue;//next column
1669 // }
1670 // //----------------------------------- classification -------------------
1671 // for(int ibag=0;ibag<nbag;++ibag){
1672 // //calculate image features
1673 // fpixel[icol].clear();
1674 // for(int iband=0;iband<nband;++iband)
1675 // fpixel[icol].push_back((hpixel[icol][iband]-offset[ibag][iband])/scale[ibag][iband]);
1676 // vector<float> result(nclass);
1677 // result=net[ibag].run(fpixel[icol]);
1678 // vector<float> prValues(nclass);
1679 // float maxP=0;
1680
1681 // //calculate posterior prob of bag
1682 // if(classBag_opt.size()){
1683 // //search for max prob within bag
1684 // maxP=0;
1685 // classBag[ibag][icol]=0;
1686 // }
1687 // double normPrior=0;
1688 // if(priorimg_opt.size()){
1689 // for(short iclass=0;iclass<nclass;++iclass)
1690 // normPrior+=linePrior[iclass][icol];
1691 // }
1692 // for(short iclass=0;iclass<nclass;++iclass){
1693 // result[iclass]=(result[iclass]+1.0)/2.0;//bring back to scale [0,1]
1694 // if(priorimg_opt.size())
1695 // priors[iclass]=linePrior[iclass][icol]/normPrior;//todo: check if correct for all cases... (automatic classValueMap and manual input for names and values)
1696 // switch(comb_opt[0]){
1697 // default:
1698 // case(0)://sum rule
1699 // probOut[iclass][icol]+=result[iclass]*priors[iclass];//add probabilities for each bag
1700 // break;
1701 // case(1)://product rule
1702 // probOut[iclass][icol]*=pow(static_cast<float>(priors[iclass]),static_cast<float>(1.0-nbag)/nbag)*result[iclass];//multiply probabilities for each bag
1703 // break;
1704 // case(2)://max rule
1705 // if(priors[iclass]*result[iclass]>probOut[iclass][icol])
1706 // probOut[iclass][icol]=priors[iclass]*result[iclass];
1707 // break;
1708 // }
1709 // if(classBag_opt.size()){
1710 // //search for max prob within bag
1711 // // if(prValues[iclass]>maxP){
1712 // // maxP=prValues[iclass];
1713 // // classBag[ibag][icol]=vcode[iclass];
1714 // // }
1715 // if(result[iclass]>maxP){
1716 // maxP=result[iclass];
1717 // classBag[ibag][icol]=iclass;
1718 // }
1719 // }
1720 // }
1721 // }//ibag
1722
1723 // //search for max class prob
1724 // float maxBag1=0;//max probability
1725 // float maxBag2=0;//second max probability
1726 // float normBag=0;
1727 // for(short iclass=0;iclass<nclass;++iclass){
1728 // if(probOut[iclass][icol]>maxBag1){
1729 // maxBag1=probOut[iclass][icol];
1730 // classOut[icol]=classValueMap[nameVector[iclass]];
1731 // }
1732 // else if(probOut[iclass][icol]>maxBag2)
1733 // maxBag2=probOut[iclass][icol];
1734 // normBag+=probOut[iclass][icol];
1735 // }
1736 // //normalize probOut and convert to percentage
1737 // entropy[icol]=0;
1738 // for(short iclass=0;iclass<nclass;++iclass){
1739 // float prv=probOut[iclass][icol];
1740 // prv/=normBag;
1741 // entropy[icol]-=prv*log(prv)/log(2.0);
1742 // prv*=100.0;
1743
1744 // probOut[iclass][icol]=static_cast<short>(prv+0.5);
1745 // // assert(classValueMap[nameVector[iclass]]<probOut.size());
1746 // // assert(classValueMap[nameVector[iclass]]>=0);
1747 // // probOut[classValueMap[nameVector[iclass]]][icol]=static_cast<short>(prv+0.5);
1748 // }
1749 // entropy[icol]/=log(static_cast<double>(nclass))/log(2.0);
1750 // entropy[icol]=static_cast<short>(100*entropy[icol]+0.5);
1751 // if(active_opt.size()){
1752 // if(entropy[icol]>activePoints.back().value){
1753 // activePoints.back().value=entropy[icol];//replace largest value (last)
1754 // activePoints.back().posx=icol;
1755 // activePoints.back().posy=iline;
1756 // std::sort(activePoints.begin(),activePoints.end(),Decrease_PosValue());//sort in descending order (largest first, smallest last)
1757 // if(verbose_opt[0])
1758 // std::cout << activePoints.back().posx << " " << activePoints.back().posy << " " << activePoints.back().value << std::endl;
1759 // }
1760 // }
1761 // }//icol
1762 //----------------------------------- write output ------------------------------------------
1763 // if(classBag_opt.size())
1764 // for(unsigned int ibag=0;ibag<nbag;++ibag)
1765 // classImageBag.writeData(classBag[ibag],iline,ibag);
1766 // if(prob_opt.size()){
1767 // for(unsigned int iclass=0;iclass<nclass;++iclass)
1768 // probImage.writeData(probOut[iclass],iline,iclass);
1769 // }
1770 // if(entropy_opt.size()){
1771 // entropyImage.writeData(entropy,iline);
1772 // }
1773 // imgWriter.writeData(classOut,iline);
1774 // if(!verbose_opt[0]){
1775 // progress=static_cast<float>(iline+1.0)/imgWriter.nrOfRow();
1776 // MyProgressFunc(progress,pszMessage,pProgressArg);
1777 // }
1778 // }
1779 // //write active learning points
1780 // if(active_opt.size()){
1781 // for(int iactive=0;iactive<activePoints.size();++iactive){
1782 // std::map<string,double> pointMap;
1783 // for(int iband=0;iband<imgWriter.nrOfBand();++iband){
1784 // double value;
1785 // readData(value,static_cast<unsigned int>(activePoints[iactive].posx),static_cast<unsigned int>(activePoints[iactive].posy),iband);
1786 // ostringstream fs;
1787 // fs << "B" << iband;
1788 // pointMap[fs.str()]=value;
1789 // }
1790 // pointMap[label_opt[0]]=0;
1791 // double x, y;
1792 // imgWriter.image2geo(activePoints[iactive].posx,activePoints[iactive].posy,x,y);
1793 // std::string fieldname="id";//number of the point
1794 // activeWriter.addPoint(x,y,pointMap,fieldname,++nactive);
1795 // }
1796 // }
1797
1798 // // imgWriter.close();
1799 // if(mask_opt.size())
1800 // maskReader.close();
1801 // if(priorimg_opt.size())
1802 // priorReader.close();
1803 // if(prob_opt.size())
1804 // probImage.close();
1805 // if(entropy_opt.size())
1806 // entropyImage.close();
1807 // if(classBag_opt.size())
1808 // classImageBag.close();
1809 // // classImageOut.close();
1810 // }
1811 // if(cm.nReference()){
1812 // std::cout << cm << std::endl;
1813 // std::cout << "class #samples userAcc prodAcc" << std::endl;
1814 // double se95_ua=0;
1815 // double se95_pa=0;
1816 // double se95_oa=0;
1817 // double dua=0;
1818 // double dpa=0;
1819 // double doa=0;
1820 // for(short iclass=0;iclass<cm.nClasses();++iclass){
1821 // dua=cm.ua_pct(cm.getClass(iclass),&se95_ua);
1822 // dpa=cm.pa_pct(cm.getClass(iclass),&se95_pa);
1823 // cout << cm.getClass(iclass) << " " << cm.nReference(cm.getClass(iclass)) << " " << dua << " (" << se95_ua << ")" << " " << dpa << " (" << se95_pa << ")" << std::endl;
1824 // }
1825 // std::cout << "Kappa: " << cm.kappa() << std::endl;
1826 // doa=cm.oa_pct(&se95_oa);
1827 // std::cout << "Overall Accuracy: " << doa << " (" << se95_oa << ")" << std::endl;
1828 // }
1829 // if(active_opt.size())
1830 // activeWriter.close();
1831 // return(CE_None);
1832 // }
1833 // catch(BadConversion conversionString){
1834 // std::cerr << "Error: did you provide class pairs names (-c) and integer values (-r) for each class in training vector?" << std::endl;
1835 // return(CE_Failure);
1836 // }
1837 // catch(string predefinedString){
1838 // std::cout << predefinedString << std::endl;
1839 // return(CE_Failure);
1840 // }
1841 // }