Debian Codegraph @

src/imageclasses/jldiff_lib.cc

raw symbols SCIP
1 /**********************************************************************
2 jldiff_lib.cc: program to compare two raster image files
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 <assert.h>
22 #include "imageclasses/Jim.h"
23 #include "imageclasses/VectorOgr.h"
24 #include "base/Optionjl.h"
25 #include "apps/AppFactory.h"
26 #include "algorithms/ConfusionMatrix.h"
27
28 using namespace std;
29 using namespace app;
30
31 /**
32 * @param imgWriter output classified raster dataset
33 * @param app application specific option arguments
34 * @return CE_None if successful, CE_Failure if failed
35 **/
36 CPLErr Jim::diff(Jim& imgReference, app::AppFactory& app){
37 Optionjl<string> mask_opt("m", "mask", "Use the first band of the specified file as a validity mask. Nodata values can be set with the option msknodata.");
38 Optionjl<double> msknodata_opt("msknodata", "msknodata", "Mask value(s) where image is invalid. Use negative value for valid data (example: use -t -1: if only -1 is valid value)", 0);
39 Optionjl<double> nodata_opt("nodata", "nodata", "No data value(s) in input or reference dataset are ignored");
40 Optionjl<unsigned int> band_opt("b", "band", "Input (reference) raster band. Optionally, you can define different bands for input and reference bands respectively: -b 1 -b 0.", 0);
41 Optionjl<bool> rmse_opt("rmse", "rmse", "Report root mean squared error", false);
42 Optionjl<bool> regression_opt("reg", "reg", "Report linear regression (Input = c0+c1*Reference)", false);
43 Optionjl<bool> confusion_opt("cm", "confusion", "Create confusion matrix (to std out)", false);
44 Optionjl<string> cmformat_opt("cmf","cmf","Format for confusion matrix (ascii or latex)","ascii");
45 Optionjl<string> cmoutput_opt("cmo","cmo","Output file for confusion matrix");
46 Optionjl<bool> se95_opt("se95","se95","Report standard error for 95 confidence interval",false);
47 Optionjl<string> classname_opt("c", "class", "List of class names.");
48 Optionjl<short> classvalue_opt("r", "reclass", "List of class values (use same order as in classname option).");
49 Optionjl<string> output_opt("o", "output", "Output dataset (optional)");
50 Optionjl<string> oformat_opt("of", "oformat", "Output image format (see also gdal_translate).","GTiff");
51 Optionjl<string> colorTable_opt("ct", "ct", "Color table in ASCII format having 5 columns: id R G B ALFA (0: transparent, 255: solid).");
52 Optionjl<string> option_opt("co", "co", "Creation option for output file. Multiple options can be specified.");
53 Optionjl<short> valueE_opt("\0", "correct", "Value for correct pixels", 0,2);
54 Optionjl<short> valueO_opt("\0", "omission", "Value for omission errors: input label > reference label", 1,2);
55 Optionjl<short> valueC_opt("\0", "commission", "Value for commission errors: input label < reference label", 2,1);
56 Optionjl<short> verbose_opt("v", "verbose", "Verbose level", 0,2);
57
58 output_opt.setHide(1);
59 oformat_opt.setHide(1);
60 colorTable_opt.setHide(1);
61
62 bool doProcess;//stop process when program was invoked with help option (-h --help)
63 try{
64 doProcess=band_opt.retrieveOption(app);
65 rmse_opt.retrieveOption(app);
66 regression_opt.retrieveOption(app);
67 confusion_opt.retrieveOption(app);
68 classname_opt.retrieveOption(app);
69 classvalue_opt.retrieveOption(app);
70 nodata_opt.retrieveOption(app);
71 mask_opt.retrieveOption(app);
72 msknodata_opt.retrieveOption(app);
73 output_opt.retrieveOption(app);
74 cmformat_opt.retrieveOption(app);
75 cmoutput_opt.retrieveOption(app);
76 se95_opt.retrieveOption(app);
77 colorTable_opt.retrieveOption(app);
78 valueE_opt.retrieveOption(app);
79 valueO_opt.retrieveOption(app);
80 valueC_opt.retrieveOption(app);
81 verbose_opt.retrieveOption(app);
82 if(!doProcess){
83 cout << endl;
84 std::ostringstream helpStream;
85 helpStream << "short option -h shows basic options only, use long option --help to show all options" << std::endl;
86 throw(helpStream.str());//help was invoked, stop processing
87 }
88 Jim maskReader;
89
90 if(verbose_opt[0]){
91 cout << "no data flag(s) set to";
92 for(int iflag=0;iflag<nodata_opt.size();++iflag)
93 cout << " " << nodata_opt[iflag];
94 cout << endl;
95 }
96
97 //band_opt[0] is for input
98 //band_opt[1] is for reference
99 if(band_opt.size()<2)
100 band_opt.push_back(band_opt[0]);
101
102 if(nrOfBand()<=band_opt[0]){
103 std::ostringstream helpStream;
104 helpStream << "Error: band exceeds number of bands in input dataset" << std::endl;
105 throw(helpStream.str());//help was invoked, stop processing
106 }
107 if(imgReference.nrOfBand()<=band_opt[1]){
108 std::ostringstream helpStream;
109 helpStream << "Error: band exceeds number of bands in reference dataset" << std::endl;
110 throw(helpStream.str());//help was invoked, stop processing
111 }
112 // if(mask_opt.size())
113 // while(mask_opt.size()<input_opt.size())
114 // mask_opt.push_back(mask_opt[0]);
115 vector<short> inputRange;
116 vector<short> referenceRange;
117 confusionmatrix::ConfusionMatrix cm;
118 int nclass=0;
119 map<string,short> classValueMap;
120 vector<std::string> nameVector(255);//the inverse of the classValueMap
121 vector<string> classNames;
122
123 unsigned int ntotalValidation=0;
124 unsigned int nflagged=0;
125 Vector2d<unsigned int> resultClass;
126 vector<float> user;
127 vector<float> producer;
128 vector<unsigned int> nvalidation;
129
130 if(confusion_opt[0]){
131 if(verbose_opt[0])
132 cout << "opening input image file" << endl;
133 // this->open(input_opt[0],memory_opt[0]);//,imagicX_opt[0],imagicY_opt[0]);
134 this->getRange(inputRange,band_opt[0]);
135 this->close();
136
137 for(int iflag=0;iflag<nodata_opt.size();++iflag){
138 vector<short>::iterator fit;
139 fit=find(inputRange.begin(),inputRange.end(),static_cast<short>(nodata_opt[iflag]));
140 if(fit!=inputRange.end())
141 inputRange.erase(fit);
142 }
143 nclass=inputRange.size();
144 if(verbose_opt[0]){
145 cout << "nclass (inputRange.size()): " << nclass << endl;
146 cout << "input range: " << endl;
147 }
148 if(classname_opt.size()){
149 assert(classname_opt.size()==classvalue_opt.size());
150 for(int iclass=0;iclass<classname_opt.size();++iclass){
151 classValueMap[classname_opt[iclass]]=classvalue_opt[iclass];
152 assert(classvalue_opt[iclass]<nameVector.size());
153 nameVector[classvalue_opt[iclass]]=classname_opt[iclass];
154 }
155 }
156 // nclass=classValueMap.size();
157 for(int rc=0;rc<inputRange.size();++rc){
158 classNames.push_back(type2string(inputRange[rc]));
159 if(verbose_opt[0])
160 cout << inputRange[rc] << endl;
161 }
162 cm.setClassNames(classNames);
163 if(verbose_opt[0]){
164 cout << "class names: " << endl;
165 for(int iclass=0;iclass<cm.nClasses();++iclass)
166 cout << iclass << " " << cm.getClass(iclass) << endl;
167 }
168 resultClass.resize(nclass,nclass);
169 user.resize(nclass);
170 producer.resize(nclass);
171 nvalidation.resize(nclass);
172 //initialize
173 for(int rc=0;rc<nclass;++rc){
174 for(int ic=0;ic<nclass;++ic)
175 resultClass[rc][ic]=0;
176 nvalidation[rc]=0;
177 }
178 }
179
180 bool isDifferent=false;
181 bool refIsRaster=false;
182
183 const char* pszMessage;
184 void* pProgressArg=NULL;
185 GDALProgressFunc pfnProgress=GDALTermProgress;
186 float progress=0;
187 // if(reference_opt[0].find(".shp")!=string::npos){
188 Jim gdalWriter;
189 // this->open(input_opt[0],memory_opt[0]);
190 if(mask_opt.size())
191 maskReader.open(mask_opt[0]);
192 // maskReader.open(mask_opt[0],memory_opt[0]);
193 if(output_opt.size()){
194 if(verbose_opt[0])
195 cout << "opening output image " << output_opt[0] << endl;
196 if(option_opt.findSubstring("INTERLEAVE=")==option_opt.end()){
197 string theInterleave="INTERLEAVE=";
198 theInterleave+=this->getInterleave();
199 option_opt.push_back(theInterleave);
200 }
201 // gdalWriter.open(output_opt[0],this->nrOfCol(),this->nrOfRow(),1,this->getDataType(),oformat_opt[0],memory_opt[0],option_opt);
202 gdalWriter.open(output_opt[0],this->nrOfCol(),this->nrOfRow(),1,this->getGDALDataType(),oformat_opt[0],0,option_opt);
203 if(nodata_opt.size())
204 gdalWriter.GDALSetNoDataValue(nodata_opt[0]);
205 gdalWriter.copyGeoTransform(*this);
206 if(colorTable_opt.size())
207 gdalWriter.setColorTable(colorTable_opt[0]);
208 else if(this->getColorTable()!=NULL){
209 if(verbose_opt[0])
210 cout << "set colortable from input image" << endl;
211 gdalWriter.setColorTable(this->getColorTable());
212 }
213 }
214
215 //todo: support different data types!
216 vector<double> lineInput(this->nrOfCol());
217 vector<double> lineMask(maskReader.nrOfCol());
218 vector<double> lineOutput;
219 vector<double> bufferInput;//for regression
220 vector<double> bufferReference;//for regression
221 if(output_opt.size())
222 lineOutput.resize(this->nrOfCol());
223
224 int irow=0;
225 int icol=0;
226 double x=0;//geo coordinates
227 double y=0;//geo coordinates
228 double oldreferencerow=-1;
229 double oldmaskrow=-1;
230
231 // imgReference.open(reference_opt[0]);//,rmagicX_opt[0],rmagicY_opt[0]);
232 if(this->isGeoRef()){
233 assert(imgReference.isGeoRef());
234 // if(this->getProjection()!=imgReference.getProjection())
235 // << "Warning: projection of input image and reference image are different" << endl;
236 }
237 vector<double> lineReference(imgReference.nrOfCol());
238 if(confusion_opt[0]){
239 imgReference.getRange(referenceRange,band_opt[1]);
240 for(int iflag=0;iflag<nodata_opt.size();++iflag){
241 vector<short>::iterator fit;
242 fit=find(referenceRange.begin(),referenceRange.end(),static_cast<unsigned short>(nodata_opt[iflag]));
243 if(fit!=referenceRange.end())
244 referenceRange.erase(fit);
245 }
246 if(verbose_opt[0]){
247 cout << "reference range: " << endl;
248 for(int rc=0;rc<referenceRange.size();++rc)
249 cout << referenceRange[rc] << endl;
250 }
251 if(referenceRange.size()!=inputRange.size()){
252 if(confusion_opt[0]||output_opt.size()){
253 cout << "reference range is not equal to input range!" << endl;
254 cout << "Kappa: " << 0 << endl;
255 cout << "total weighted: " << 0 << endl;
256 }
257 else{
258 std::ostringstream errorStream;
259 errorStream << "reference range is not equal to input range!" << endl;
260 errorStream << "Images are different" << endl;
261 throw(errorStream.str());
262 }
263 }
264 }
265 double rmse=0;
266 // for(irow=0;irow<this->nrOfRow()&&!isDifferent;++irow){
267 for(irow=0;irow<this->nrOfRow();++irow){
268 if(isDifferent&&output_opt.empty())
269 break;
270 //read line in lineInput, lineReference and lineMask
271 this->readData(lineInput,irow,band_opt[0]);
272 double ireference,jreference;//image coordinates in reference image
273 double imask,jmask;//image coordinates in mask image
274 for(icol=0;icol<this->nrOfCol();++icol){
275 //find col in reference
276 this->image2geo(icol,irow,x,y);
277 imgReference.geo2image(x,y,ireference,jreference);
278 if(ireference<0||ireference>=imgReference.nrOfCol()){
279 if(rmse_opt[0]||regression_opt[0])
280 continue;
281 else{
282 std::ostringstream errorStream;
283 errorStream << ireference << " out of reference range!" << endl;
284 errorStream << x << " " << y << " " << icol << " " << irow << endl;
285 errorStream << x << " " << y << " " << ireference << " " << jreference << endl;
286 throw(errorStream.str());
287 }
288 }
289 if(jreference!=oldreferencerow){
290 if(jreference<0||jreference>=imgReference.nrOfRow()){
291 if(rmse_opt[0]||regression_opt[0])
292 continue;
293 else{
294 std::ostringstream errorStream;
295 errorStream << jreference << " out of reference range!" << endl;
296 errorStream << x << " " << y << " " << icol << " " << irow << endl;
297 errorStream << x << " " << y << " " << ireference << " " << jreference << endl;
298 throw(errorStream.str());
299 }
300 }
301 else{
302 imgReference.readData(lineReference,static_cast<int>(jreference),band_opt[1]);
303 oldreferencerow=jreference;
304 }
305 }
306 bool flagged=false;
307 for(int iflag=0;iflag<nodata_opt.size();++iflag){
308 if((lineInput[icol]==nodata_opt[iflag])||(lineReference[ireference]==nodata_opt[iflag])){
309 if(output_opt.size())
310 lineOutput[icol]=nodata_opt[iflag];
311 flagged=true;
312 break;
313 }
314 }
315 if(mask_opt.size()){
316 maskReader.geo2image(x,y,imask,jmask);
317 if(jmask>=0&&jmask<maskReader.nrOfRow()){
318 if(jmask!=oldmaskrow)
319 maskReader.readData(lineMask,jmask);
320 for(int ivalue=0;ivalue<msknodata_opt.size();++ivalue){
321 if(lineMask[icol]==msknodata_opt[ivalue]){
322 flagged=true;
323 break;
324 }
325 }
326 }
327 }
328 if(!flagged){
329 if(rmse_opt[0]){//divide by image size to prevent overflow. At the end we need to take care about flagged pixels by normalizing...
330 rmse+=static_cast<double>(lineInput[icol]-lineReference[ireference])*(lineInput[icol]-lineReference[ireference])/this->nrOfCol()/this->nrOfRow();
331 }
332 else if(regression_opt[0]){
333 bufferInput.push_back(lineInput[icol]);
334 bufferReference.push_back(lineReference[ireference]);
335 }
336 if(confusion_opt[0]){
337 ++ntotalValidation;
338 int rc=distance(referenceRange.begin(),find(referenceRange.begin(),referenceRange.end(),lineReference[ireference]));
339 int ic=distance(inputRange.begin(),find(inputRange.begin(),inputRange.end(),lineInput[icol]));
340 assert(rc<nclass);
341 assert(ic<nclass);
342 ++nvalidation[rc];
343 ++resultClass[rc][ic];
344 if(verbose_opt[0]>1)
345 cout << "increment: " << rc << " " << referenceRange[rc] << " " << ic << " " << inputRange[ic] << endl;
346 cm.incrementResult(cm.getClass(rc),cm.getClass(ic),1);
347 }
348 if(lineInput[icol]==lineReference[ireference]){//correct
349 if(output_opt.size()){
350 lineOutput[icol]=valueE_opt[0];
351 if(nodata_opt.size()){
352 if(valueE_opt[0]==nodata_opt[0])
353 lineOutput[icol]=lineInput[icol];
354 }
355 }
356 }
357 else{//error
358 if(output_opt.empty()&&!confusion_opt[0]&&!rmse_opt[0]&&!regression_opt[0]){
359 isDifferent=true;
360 break;
361 }
362 if(output_opt.size()){
363 if(lineInput[icol]>lineReference[ireference])
364 lineOutput[icol]=valueO_opt[0];//omission error
365 else
366 lineOutput[icol]=valueC_opt[0];//commission error
367 }
368 }
369 }
370 else{
371 ++nflagged;
372 if(output_opt.size()){
373 if(nodata_opt.size())
374 lineOutput[icol]=nodata_opt[0];
375 else //should never occur?
376 lineOutput[icol]=0;
377 }
378 }
379 }
380 if(output_opt.size()){
381 gdalWriter.writeData(lineOutput,irow);
382 }
383 else if(isDifferent&&!confusion_opt[0]&&!rmse_opt[0]&&!regression_opt[0]){//we can break off here, files are different...
384 if(!verbose_opt[0])
385 MyProgressFunc(1.0,pszMessage,pProgressArg);
386 break;
387 }
388 progress=static_cast<float>(irow+1.0)/this->nrOfRow();
389 if(!verbose_opt[0])
390 MyProgressFunc(progress,pszMessage,pProgressArg);
391 }
392 if(mask_opt.size())
393 maskReader.close();
394 if(output_opt.size())
395 gdalWriter.close();
396 else if(!confusion_opt[0]){
397 if(rmse_opt[0]){
398 double normalization=1.0*(this->nrOfCol())*(this->nrOfRow())/(this->nrOfCol()*(this->nrOfRow())-nflagged);
399 if(verbose_opt[0]){
400 cout << "normalization: " << normalization << endl;
401 cout << "rmse before sqrt and normalization: " << rmse << endl;
402 }
403 cout << "--rmse " << sqrt(rmse/normalization) << endl;
404 }
405 else if(regression_opt[0]){
406 double err=0;
407 double c0=0;
408 double c1=1;
409 statfactory::StatFactory stat;
410 if(bufferInput.size()&&bufferReference.size()){
411 err=stat.linear_regression_err(bufferInput,bufferReference,c0,c1);
412 }
413 if(verbose_opt[0]){
414 cout << "bufferInput.size(): " << bufferInput.size() << endl;
415 cout << "bufferReference.size(): " << bufferReference.size() << endl;
416 double theMin=0;
417 double theMax=0;
418 stat.minmax(bufferInput,bufferInput.begin(),bufferInput.end(),theMin,theMax);
419 cout << "min, max input: " << theMin << ", " << theMax << endl;
420 theMin=0;
421 theMax=0;
422 stat.minmax(bufferReference,bufferReference.begin(),bufferReference.end(),theMin,theMax);
423 cout << "min, max reference: " << theMin << ", " << theMax << endl;
424 }
425 cout << "--c0 " << c0 << "--c1 " << c1 << " --rmse: " << err << endl;
426
427 }
428 else if(isDifferent){
429 std::cout << "Images are different: (column,row)=(" << icol << "," << irow << "), (x,y)=(" << x << "," << y << ")" << std::endl;
430 return(CE_Failure);
431 }
432 else{
433 std::cout << "Images are identical" << std::endl;
434 return(CE_None);
435 }
436 }
437 // imgReference.close();
438 // this->close();
439
440 if(confusion_opt[0]){
441 cm.setFormat(cmformat_opt[0]);
442 cm.reportSE95(se95_opt[0]);
443 ofstream outputFile;
444 if(cmoutput_opt.size()){
445 outputFile.open(cmoutput_opt[0].c_str(),ios::out);
446 outputFile << cm << endl;
447 }
448 else
449 cout << cm << endl;
450 }
451 }
452 catch(string predefinedString){
453 std::cout << predefinedString << std::endl;
454 throw;
455 }
456 return(CE_None);
457 }