pktools  2.6.5
Processing Kernel for geospatial data
pkreclass.cc
1 /**********************************************************************
2 pkreclass.cc: program to replace pixel values in raster image
3 Copyright (C) 2008-2014 Pieter Kempeneers
4 
5 This file is part of pktools
6 
7 pktools is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
11 
12 pktools is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16 
17 You should have received a copy of the GNU General Public License
18 along with pktools. If not, see <http://www.gnu.org/licenses/>.
19 ***********************************************************************/
20 #include <assert.h>
21 #include <map>
22 #include "base/Optionpk.h"
23 #include "imageclasses/ImgReaderOgr.h"
24 #include "imageclasses/ImgWriterOgr.h"
25 #include "imageclasses/ImgReaderGdal.h"
26 #include "imageclasses/ImgWriterGdal.h"
27 
28 /******************************************************************************/
67 using namespace std;
68 
69 int main(int argc, char *argv[])
70 {
71  Optionpk<string> input_opt("i", "input", "Input image");
72  Optionpk<string> mask_opt("m", "mask", "Mask image(s)");
73  Optionpk<string> output_opt("o", "output", "Output mask file");
74  Optionpk<unsigned short> masknodata_opt("msknodata", "msknodata", "Mask value(s) where image has nodata. Use one value for each mask, or multiple values for a single mask.", 1);
75  Optionpk<int> nodata_opt("nodata", "nodata", "nodata value to put in image if not valid (0)", 0);
76  Optionpk<string> colorTable_opt("ct", "ct", "color table (file with 5 columns: id R G B ALFA (0: transparent, 255: solid)");
77  Optionpk<unsigned short> band_opt("b", "band", "band index(es) to replace (other bands are copied to output)", 0);
78  Optionpk<string> type_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", "");
79  Optionpk<string> oformat_opt("of", "oformat", "Output image format (see also gdal_translate).","GTiff");
80  Optionpk<string> code_opt("code", "code", "Recode text file (2 colums: from to)");
81  Optionpk<string> class_opt("c", "class", "list of classes to reclass (in combination with reclass option)");
82  Optionpk<string> reclass_opt("r", "reclass", "list of recoded classes (in combination with class option)");
83  Optionpk<string> fieldname_opt("n", "fname", "field name of the shape file to be replaced", "label");
84  Optionpk<string> option_opt("co", "co", "Creation option for output file. Multiple options can be specified.");
85  Optionpk<string> description_opt("d", "description", "Set image description");
86  Optionpk<short> verbose_opt("v", "verbose", "verbose", 0);
87 
88  bool doProcess;//stop process when program was invoked with help option (-h --help)
89  try{
90  doProcess=input_opt.retrieveOption(argc,argv);
91  mask_opt.retrieveOption(argc,argv);
92  masknodata_opt.retrieveOption(argc,argv);
93  nodata_opt.retrieveOption(argc,argv);
94  code_opt.retrieveOption(argc,argv);
95  class_opt.retrieveOption(argc,argv);
96  reclass_opt.retrieveOption(argc,argv);
97  colorTable_opt.retrieveOption(argc,argv);
98  output_opt.retrieveOption(argc,argv);
99  type_opt.retrieveOption(argc,argv);
100  oformat_opt.retrieveOption(argc,argv);
101  band_opt.retrieveOption(argc,argv);
102  fieldname_opt.retrieveOption(argc,argv);
103  option_opt.retrieveOption(argc,argv);
104  description_opt.retrieveOption(argc,argv);
105  verbose_opt.retrieveOption(argc,argv);
106  }
107  catch(string predefinedString){
108  std::cout << predefinedString << std::endl;
109  exit(0);
110  }
111  if(!doProcess){
112  cout << endl;
113  cout << "Usage: pkreclass -i input [-c from -r to]* -o output" << endl;
114  cout << endl;
115  std::cout << "short option -h shows basic options only, use long option --help to show all options" << std::endl;
116  exit(0);//help was invoked, stop processing
117  }
118 
119  if(input_opt.empty()){
120  std::cerr << "No input file provided (use option -i). Use --help for help information" << std::endl;
121  exit(0);
122  }
123  if(output_opt.empty()){
124  std::cerr << "No output file provided (use option -o). Use --help for help information" << std::endl;
125  exit(0);
126  }
127 
128  // vector<short> bandVector;
129  // for(int iband=0;iband<band_opt.size();++iband)
130  // bandVector.push_back(band_opt[iband]);
131  map<string,string> codemapString;//map with codes: codemapString[theKey(from)]=theValue(to)
132  map<double,double> codemap;//map with codes: codemap[theKey(from)]=theValue(to)
133  if(code_opt.size()){
134  if(verbose_opt[0])
135  cout << "opening code text file " << code_opt[0] << endl;
136  ifstream codefile;
137  codefile.open(code_opt[0].c_str());
138  string theKey;
139  string theValue;
140  while(codefile>>theKey){
141  codefile >> theValue;
142  codemapString[theKey]=theValue;
143  codemap[string2type<double>(theKey)]=string2type<double>(theValue);
144  }
145  codefile.close();
146  }
147  else{//use combination of class_opt and reclass_opt
148  assert(class_opt.size()==reclass_opt.size());
149  for(int iclass=0;iclass<class_opt.size();++iclass){
150  codemapString[class_opt[iclass]]=reclass_opt[iclass];
151  codemap[string2type<double>(class_opt[iclass])]=string2type<double>(reclass_opt[iclass]);
152  }
153  }
154  assert(codemapString.size());
155  assert(codemap.size());
156  //if verbose true, print the codes to screen
157  if(verbose_opt[0]){
158  map<string,string>::iterator mit;
159  cout << codemapString.size() << " codes used: " << endl;
160  for(mit=codemapString.begin();mit!=codemapString.end();++mit)
161  cout << (*mit).first << " " << (*mit).second << endl;
162  }
163  bool refIsRaster=false;
164  ImgReaderOgr ogrReader;
165  try{
166  ogrReader.open(input_opt[0]);
167  }
168  catch(string errorString){
169  refIsRaster=true;
170  }
171  // if(input_opt[0].find(".shp")!=string::npos){//shape file
172  if(!refIsRaster){
173  if(verbose_opt[0])
174  cout << "opening " << input_opt[0] << " for reading " << endl;
175  // ImgReaderOgr ogrReader(input_opt[0]);
176  if(verbose_opt[0])
177  cout << "opening " << output_opt[0] << " for writing " << endl;
178  ImgWriterOgr ogrWriter(output_opt[0],ogrReader);
179  if(verbose_opt[0])
180  cout << "copied layer from " << input_opt[0] << endl << flush;
181  OGRFeatureDefn *poFDefn = ogrWriter.getLayer()->GetLayerDefn();
182  //start reading features from the layer
183  if(verbose_opt[0])
184  cout << "reset reading" << endl;
185  ogrReader.getLayer()->ResetReading();
186  unsigned long int ifeature=0;
187  if(verbose_opt[0])
188  cout << "going through features" << endl << flush;
189  while(true){
190 // while( (poFeature = ogrWriter.getLayer()->GetNextFeature()) != NULL ){
191  OGRFeature *poFeature;
192  poFeature=ogrReader.getLayer()->GetNextFeature();
193  if(poFeature== NULL)
194  break;
195  OGRFeatureDefn *poFDefn = ogrWriter.getLayer()->GetLayerDefn();
196  string featurename;
197  for(int iField=0;iField<poFDefn->GetFieldCount();++iField){
198  OGRFieldDefn *poFieldDefn = poFDefn->GetFieldDefn(iField);
199  string fieldname=poFieldDefn->GetNameRef();
200  if(fieldname==fieldname_opt[0]){
201  string fromClass=poFeature->GetFieldAsString(iField);
202  string toClass=fromClass;
203  if(codemapString.find(fromClass)!=codemapString.end())
204  toClass=codemapString[fromClass];
205  poFeature->SetField(iField,toClass.c_str());
206  if(verbose_opt[0])
207  cout << "feature " << ifeature << ": " << fromClass << "->" << poFeature->GetFieldAsInteger(iField) << endl << flush;
208 // cout << "feature " << ifeature << ": " << fromClass << "->" << toClass << endl << flush;
209  }
210  }
211  //do not forget to actually write feature to file!!!
212  ogrWriter.createFeature(poFeature);
213  OGRFeature::DestroyFeature( poFeature );
214  ++ifeature;
215  }
216  if(verbose_opt[0])
217  cout << "replaced " << ifeature << " features" << endl;
218  ogrReader.close();
219  ogrWriter.close();
220  }
221  else{//image file
222  ImgReaderGdal inputReader;
223  vector<ImgReaderGdal> maskReader(mask_opt.size());
224  ImgWriterGdal outputWriter;
225  if(verbose_opt[0])
226  cout << "opening input image file " << input_opt[0] << endl;
227  inputReader.open(input_opt[0]);
228  for(int imask=0;imask<mask_opt.size();++imask){
229  if(verbose_opt[0])
230  cout << "opening mask image file " << mask_opt[imask] << endl;
231  maskReader[imask].open(mask_opt[imask]);
232  }
233  if(verbose_opt[0]){
234  cout << "opening output image file " << output_opt[0] << endl;
235  cout << "data type: " << type_opt[0] << endl;
236  }
237  //create output image with user defined data type
238  GDALDataType theType=GDT_Unknown;
239  if(verbose_opt[0])
240  cout << "possible output data types: ";
241  for(int iType = 0; iType < GDT_TypeCount; ++iType){
242  if(verbose_opt[0])
243  cout << " " << GDALGetDataTypeName((GDALDataType)iType);
244  if( GDALGetDataTypeName((GDALDataType)iType) != NULL
245  && EQUAL(GDALGetDataTypeName((GDALDataType)iType),
246  type_opt[0].c_str()))
247  theType=(GDALDataType) iType;
248  }
249  if(theType==GDT_Unknown)
250  theType=inputReader.getDataType();
251  if(verbose_opt[0])
252  cout << endl << "Output pixel type: " << GDALGetDataTypeName(theType) << endl;
253  if(option_opt.findSubstring("INTERLEAVE=")==option_opt.end()){
254  string theInterleave="INTERLEAVE=";
255  theInterleave+=inputReader.getInterleave();
256  option_opt.push_back(theInterleave);
257  }
258  outputWriter.open(output_opt[0],inputReader.nrOfCol(),inputReader.nrOfRow(),inputReader.nrOfBand(),theType,oformat_opt[0],option_opt);
259  for(int iband=0;iband<inputReader.nrOfBand();++iband)
260  outputWriter.GDALSetNoDataValue(nodata_opt[0],iband);
261  if(description_opt.size())
262  outputWriter.setImageDescription(description_opt[0]);
263 
264  if(colorTable_opt.size()){
265  if(colorTable_opt[0]!="none")
266  outputWriter.setColorTable(colorTable_opt[0]);
267  }
268  else if (inputReader.getColorTable()!=NULL)//copy colorTable from input image
269  outputWriter.setColorTable(inputReader.getColorTable());
270 
271  //if input image is georeferenced, copy projection info to output image
272  if(inputReader.isGeoRef()){
273  for(int imask=0;imask<mask_opt.size();++imask)
274  assert(maskReader[imask].isGeoRef());
275  }
276  outputWriter.copyGeoTransform(inputReader);
277  outputWriter.setProjection(inputReader.getProjection());
278  double ulx,uly,lrx,lry;
279  inputReader.getBoundingBox(ulx,uly,lrx,lry);
280  outputWriter.copyGeoTransform(inputReader);
281  assert(nodata_opt.size()==masknodata_opt.size());
282  if(verbose_opt[0]&&mask_opt.size()){
283  for(int iv=0;iv<masknodata_opt.size();++iv)
284  cout << masknodata_opt[iv] << "->" << nodata_opt[iv] << endl;
285  }
286 
287  assert(outputWriter.nrOfCol()==inputReader.nrOfCol());
288  // Vector2d<int> lineInput(inputReader.nrOfBand(),inputReader.nrOfCol());
289  Vector2d<double> lineInput(inputReader.nrOfBand(),inputReader.nrOfCol());
290  Vector2d<short> lineMask(mask_opt.size());
291  for(int imask=0;imask<mask_opt.size();++imask)
292  lineMask[imask].resize(maskReader[imask].nrOfCol());
293  Vector2d<double> lineOutput(outputWriter.nrOfBand(),outputWriter.nrOfCol());
294  int irow=0;
295  int icol=0;
296  const char* pszMessage;
297  void* pProgressArg=NULL;
298  GDALProgressFunc pfnProgress=GDALTermProgress;
299  double progress=0;
300  pfnProgress(progress,pszMessage,pProgressArg);
301  double oldRowMask=-1;
302  for(irow=0;irow<inputReader.nrOfRow();++irow){
303  //read line in lineInput buffer
304  for(int iband=0;iband<inputReader.nrOfBand();++iband){
305  try{
306  // inputReader.readData(lineInput[iband],GDT_Int32,irow,iband);
307  inputReader.readData(lineInput[iband],GDT_Float64,irow,iband);
308  }
309  catch(string errorstring){
310  cerr << errorstring << endl;
311  exit(1);
312  }
313  }
314  double x,y;//geo coordinates
315  double colMask,rowMask;//image coordinates in mask image
316  for(icol=0;icol<inputReader.nrOfCol();++icol){
317  bool masked=false;
318  if(mask_opt.size()>1){//multiple masks
319  for(int imask=0;imask<mask_opt.size();++imask){
320  inputReader.image2geo(icol,irow,x,y);
321  maskReader[imask].geo2image(x,y,colMask,rowMask);
322  if(static_cast<int>(rowMask)!=static_cast<int>(oldRowMask)){
323  assert(rowMask>=0&&rowMask<maskReader[imask].nrOfRow());
324  try{
325  maskReader[imask].readData(lineMask[imask],GDT_Int16,static_cast<int>(rowMask));
326  }
327  catch(string errorstring){
328  cerr << errorstring << endl;
329  exit(1);
330  }
331  oldRowMask=rowMask;
332  }
333  short ivalue=0;
334  if(mask_opt.size()==masknodata_opt.size())//one invalid value for each mask
335  ivalue=masknodata_opt[imask];
336  else//use same invalid value for each mask
337  ivalue=masknodata_opt[0];
338  if(lineMask[imask][colMask]==ivalue){
339  for(int iband=0;iband<inputReader.nrOfBand();++iband)
340  lineInput[iband][icol]=nodata_opt[imask];
341  masked=true;
342  break;
343  }
344  }
345  }
346  else if(mask_opt.size()){//potentially more invalid values for single mask
347  inputReader.image2geo(icol,irow,x,y);
348  maskReader[0].geo2image(x,y,colMask,rowMask);
349  if(static_cast<int>(rowMask)!=static_cast<int>(oldRowMask)){
350  assert(rowMask>=0&&rowMask<maskReader[0].nrOfRow());
351  try{
352  maskReader[0].readData(lineMask[0],GDT_Int16,static_cast<int>(rowMask));
353  }
354  catch(string errorstring){
355  cerr << errorstring << endl;
356  exit(1);
357  }
358  oldRowMask=rowMask;
359  }
360  for(int ivalue=0;ivalue<masknodata_opt.size();++ivalue){
361  assert(masknodata_opt.size()==nodata_opt.size());
362  if(lineMask[0][colMask]==masknodata_opt[ivalue]){
363  for(int iband=0;iband<inputReader.nrOfBand();++iband)
364  lineInput[iband][icol]=nodata_opt[ivalue];
365  masked=true;
366  break;
367  }
368  }
369  }
370  for(int iband=0;iband<lineOutput.size();++iband){
371  lineOutput[iband][icol]=lineInput[iband][icol];
372  if(find(band_opt.begin(),band_opt.end(),iband)!=band_opt.end()){
373  if(!masked && codemap.find(lineInput[iband][icol])!=codemap.end()){
374  double toValue=codemap[lineInput[iband][icol]];
375  lineOutput[iband][icol]=toValue;
376  }
377  }
378  }
379  }
380  //write buffer lineOutput to output file
381  try{
382  for(int iband=0;iband<outputWriter.nrOfBand();++iband)
383  outputWriter.writeData(lineOutput[iband],GDT_Float64,irow,iband);
384  }
385  catch(string errorstring){
386  cerr << errorstring << endl;
387  exit(1);
388  }
389  //progress bar
390  progress=static_cast<float>((irow+1.0)/outputWriter.nrOfRow());
391  pfnProgress(progress,pszMessage,pProgressArg);
392  }
393  inputReader.close();
394  outputWriter.close();
395  }
396 }