pktools  2.6.3
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 using namespace std;
29 
30 int main(int argc, char *argv[])
31 {
32  Optionpk<string> input_opt("i", "input", "Input image");
33  Optionpk<string> mask_opt("m", "mask", "Mask image(s)");
34  Optionpk<string> output_opt("o", "output", "Output mask file");
35  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);
36  Optionpk<int> nodata_opt("nodata", "nodata", "nodata value to put in image if not valid (0)", 0);
37  Optionpk<string> colorTable_opt("ct", "ct", "color table (file with 5 columns: id R G B ALFA (0: transparent, 255: solid)");
38  Optionpk<unsigned short> band_opt("b", "band", "band index(es) to replace (other bands are copied to output)", 0);
39  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", "");
40  Optionpk<string> code_opt("code", "code", "Recode text file (2 colums: from to)");
41  Optionpk<string> class_opt("c", "class", "list of classes to reclass (in combination with reclass option)");
42  Optionpk<string> reclass_opt("r", "reclass", "list of recoded classes (in combination with class option)");
43  Optionpk<string> fieldname_opt("n", "fname", "field name of the shape file to be replaced", "label");
44  Optionpk<string> option_opt("co", "co", "Creation option for output file. Multiple options can be specified.");
45  Optionpk<string> description_opt("d", "description", "Set image description");
46  Optionpk<short> verbose_opt("v", "verbose", "verbose", 0);
47 
48  bool doProcess;//stop process when program was invoked with help option (-h --help)
49  try{
50  doProcess=input_opt.retrieveOption(argc,argv);
51  mask_opt.retrieveOption(argc,argv);
52  masknodata_opt.retrieveOption(argc,argv);
53  nodata_opt.retrieveOption(argc,argv);
54  code_opt.retrieveOption(argc,argv);
55  class_opt.retrieveOption(argc,argv);
56  reclass_opt.retrieveOption(argc,argv);
57  colorTable_opt.retrieveOption(argc,argv);
58  output_opt.retrieveOption(argc,argv);
59  type_opt.retrieveOption(argc,argv);
60  band_opt.retrieveOption(argc,argv);
61  fieldname_opt.retrieveOption(argc,argv);
62  option_opt.retrieveOption(argc,argv);
63  description_opt.retrieveOption(argc,argv);
64  verbose_opt.retrieveOption(argc,argv);
65  }
66  catch(string predefinedString){
67  std::cout << predefinedString << std::endl;
68  exit(0);
69  }
70  if(!doProcess){
71  cout << endl;
72  cout << "Usage: pkreclass -i input [-c from -r to]* -o output" << endl;
73  cout << endl;
74  std::cout << "short option -h shows basic options only, use long option --help to show all options" << std::endl;
75  exit(0);//help was invoked, stop processing
76  }
77 
78  if(input_opt.empty()){
79  std::cerr << "No input file provided (use option -i). Use --help for help information" << std::endl;
80  exit(0);
81  }
82  if(output_opt.empty()){
83  std::cerr << "No output file provided (use option -o). Use --help for help information" << std::endl;
84  exit(0);
85  }
86 
87  // vector<short> bandVector;
88  // for(int iband=0;iband<band_opt.size();++iband)
89  // bandVector.push_back(band_opt[iband]);
90  map<string,string> codemapString;//map with codes: codemapString[theKey(from)]=theValue(to)
91  map<double,double> codemap;//map with codes: codemap[theKey(from)]=theValue(to)
92  if(code_opt.size()){
93  if(verbose_opt[0])
94  cout << "opening code text file " << code_opt[0] << endl;
95  ifstream codefile;
96  codefile.open(code_opt[0].c_str());
97  string theKey;
98  string theValue;
99  while(codefile>>theKey){
100  codefile >> theValue;
101  codemapString[theKey]=theValue;
102  codemap[string2type<double>(theKey)]=string2type<double>(theValue);
103  }
104  codefile.close();
105  }
106  else{//use combination of class_opt and reclass_opt
107  assert(class_opt.size()==reclass_opt.size());
108  for(int iclass=0;iclass<class_opt.size();++iclass){
109  codemapString[class_opt[iclass]]=reclass_opt[iclass];
110  codemap[string2type<double>(class_opt[iclass])]=string2type<double>(reclass_opt[iclass]);
111  }
112  }
113  assert(codemapString.size());
114  assert(codemap.size());
115  //if verbose true, print the codes to screen
116  if(verbose_opt[0]){
117  map<string,string>::iterator mit;
118  cout << codemapString.size() << " codes used: " << endl;
119  for(mit=codemapString.begin();mit!=codemapString.end();++mit)
120  cout << (*mit).first << " " << (*mit).second << endl;
121  }
122  bool refIsRaster=false;
123  ImgReaderOgr ogrReader;
124  try{
125  ogrReader.open(input_opt[0]);
126  }
127  catch(string errorString){
128  refIsRaster=true;
129  }
130  // if(input_opt[0].find(".shp")!=string::npos){//shape file
131  if(!refIsRaster){
132  if(verbose_opt[0])
133  cout << "opening " << input_opt[0] << " for reading " << endl;
134  // ImgReaderOgr ogrReader(input_opt[0]);
135  if(verbose_opt[0])
136  cout << "opening " << output_opt[0] << " for writing " << endl;
137  ImgWriterOgr ogrWriter(output_opt[0],ogrReader);
138  if(verbose_opt[0])
139  cout << "copied layer from " << input_opt[0] << endl << flush;
140  OGRFeatureDefn *poFDefn = ogrWriter.getLayer()->GetLayerDefn();
141  //start reading features from the layer
142  if(verbose_opt[0])
143  cout << "reset reading" << endl;
144  ogrReader.getLayer()->ResetReading();
145  unsigned long int ifeature=0;
146  if(verbose_opt[0])
147  cout << "going through features" << endl << flush;
148  while(true){
149 // while( (poFeature = ogrWriter.getLayer()->GetNextFeature()) != NULL ){
150  OGRFeature *poFeature;
151  poFeature=ogrReader.getLayer()->GetNextFeature();
152  if(poFeature== NULL)
153  break;
154  OGRFeatureDefn *poFDefn = ogrWriter.getLayer()->GetLayerDefn();
155  string featurename;
156  for(int iField=0;iField<poFDefn->GetFieldCount();++iField){
157  OGRFieldDefn *poFieldDefn = poFDefn->GetFieldDefn(iField);
158  string fieldname=poFieldDefn->GetNameRef();
159  if(fieldname==fieldname_opt[0]){
160  string fromClass=poFeature->GetFieldAsString(iField);
161  string toClass=fromClass;
162  if(codemapString.find(fromClass)!=codemapString.end())
163  toClass=codemapString[fromClass];
164  poFeature->SetField(iField,toClass.c_str());
165  if(verbose_opt[0])
166  cout << "feature " << ifeature << ": " << fromClass << "->" << poFeature->GetFieldAsInteger(iField) << endl << flush;
167 // cout << "feature " << ifeature << ": " << fromClass << "->" << toClass << endl << flush;
168  }
169  }
170  //do not forget to actually write feature to file!!!
171  ogrWriter.createFeature(poFeature);
172  OGRFeature::DestroyFeature( poFeature );
173  ++ifeature;
174  }
175  if(verbose_opt[0])
176  cout << "replaced " << ifeature << " features" << endl;
177  ogrReader.close();
178  ogrWriter.close();
179  }
180  else{//image file
181  ImgReaderGdal inputReader;
182  vector<ImgReaderGdal> maskReader(mask_opt.size());
183  ImgWriterGdal outputWriter;
184  if(verbose_opt[0])
185  cout << "opening input image file " << input_opt[0] << endl;
186  inputReader.open(input_opt[0]);
187  for(int imask=0;imask<mask_opt.size();++imask){
188  if(verbose_opt[0])
189  cout << "opening mask image file " << mask_opt[imask] << endl;
190  maskReader[imask].open(mask_opt[imask]);
191  }
192  if(verbose_opt[0]){
193  cout << "opening output image file " << output_opt[0] << endl;
194  cout << "data type: " << type_opt[0] << endl;
195  }
196  //create output image with user defined data type
197  GDALDataType theType=GDT_Unknown;
198  if(verbose_opt[0])
199  cout << "possible output data types: ";
200  for(int iType = 0; iType < GDT_TypeCount; ++iType){
201  if(verbose_opt[0])
202  cout << " " << GDALGetDataTypeName((GDALDataType)iType);
203  if( GDALGetDataTypeName((GDALDataType)iType) != NULL
204  && EQUAL(GDALGetDataTypeName((GDALDataType)iType),
205  type_opt[0].c_str()))
206  theType=(GDALDataType) iType;
207  }
208  if(theType==GDT_Unknown)
209  theType=inputReader.getDataType();
210  if(verbose_opt[0])
211  cout << endl << "Output pixel type: " << GDALGetDataTypeName(theType) << endl;
212  if(option_opt.findSubstring("INTERLEAVE=")==option_opt.end()){
213  string theInterleave="INTERLEAVE=";
214  theInterleave+=inputReader.getInterleave();
215  option_opt.push_back(theInterleave);
216  }
217  outputWriter.open(output_opt[0],inputReader.nrOfCol(),inputReader.nrOfRow(),inputReader.nrOfBand(),theType,inputReader.getImageType(),option_opt);
218  for(int iband=0;iband<inputReader.nrOfBand();++iband)
219  outputWriter.GDALSetNoDataValue(nodata_opt[0],iband);
220  if(description_opt.size())
221  outputWriter.setImageDescription(description_opt[0]);
222 
223  if(colorTable_opt.size()){
224  if(colorTable_opt[0]!="none")
225  outputWriter.setColorTable(colorTable_opt[0]);
226  }
227  else if (inputReader.getColorTable()!=NULL)//copy colorTable from input image
228  outputWriter.setColorTable(inputReader.getColorTable());
229 
230  //if input image is georeferenced, copy projection info to output image
231  if(inputReader.isGeoRef()){
232  for(int imask=0;imask<mask_opt.size();++imask)
233  assert(maskReader[imask].isGeoRef());
234  }
235  outputWriter.copyGeoTransform(inputReader);
236  outputWriter.setProjection(inputReader.getProjection());
237  double ulx,uly,lrx,lry;
238  inputReader.getBoundingBox(ulx,uly,lrx,lry);
239  outputWriter.copyGeoTransform(inputReader);
240  assert(nodata_opt.size()==masknodata_opt.size());
241  if(verbose_opt[0]&&mask_opt.size()){
242  for(int iv=0;iv<masknodata_opt.size();++iv)
243  cout << masknodata_opt[iv] << "->" << nodata_opt[iv] << endl;
244  }
245 
246  assert(outputWriter.nrOfCol()==inputReader.nrOfCol());
247  // Vector2d<int> lineInput(inputReader.nrOfBand(),inputReader.nrOfCol());
248  Vector2d<double> lineInput(inputReader.nrOfBand(),inputReader.nrOfCol());
249  Vector2d<short> lineMask(mask_opt.size());
250  for(int imask=0;imask<mask_opt.size();++imask)
251  lineMask[imask].resize(maskReader[imask].nrOfCol());
252  Vector2d<double> lineOutput(outputWriter.nrOfBand(),outputWriter.nrOfCol());
253  int irow=0;
254  int icol=0;
255  const char* pszMessage;
256  void* pProgressArg=NULL;
257  GDALProgressFunc pfnProgress=GDALTermProgress;
258  double progress=0;
259  pfnProgress(progress,pszMessage,pProgressArg);
260  double oldRowMask=-1;
261  for(irow=0;irow<inputReader.nrOfRow();++irow){
262  //read line in lineInput buffer
263  for(int iband=0;iband<inputReader.nrOfBand();++iband){
264  try{
265  // inputReader.readData(lineInput[iband],GDT_Int32,irow,iband);
266  inputReader.readData(lineInput[iband],GDT_Float64,irow,iband);
267  }
268  catch(string errorstring){
269  cerr << errorstring << endl;
270  exit(1);
271  }
272  }
273  double x,y;//geo coordinates
274  double colMask,rowMask;//image coordinates in mask image
275  for(icol=0;icol<inputReader.nrOfCol();++icol){
276  bool masked=false;
277  if(mask_opt.size()>1){//multiple masks
278  for(int imask=0;imask<mask_opt.size();++imask){
279  inputReader.image2geo(icol,irow,x,y);
280  maskReader[imask].geo2image(x,y,colMask,rowMask);
281  if(static_cast<int>(rowMask)!=static_cast<int>(oldRowMask)){
282  assert(rowMask>=0&&rowMask<maskReader[imask].nrOfRow());
283  try{
284  maskReader[imask].readData(lineMask[imask],GDT_Int16,static_cast<int>(rowMask));
285  }
286  catch(string errorstring){
287  cerr << errorstring << endl;
288  exit(1);
289  }
290  oldRowMask=rowMask;
291  }
292  short ivalue=0;
293  if(mask_opt.size()==masknodata_opt.size())//one invalid value for each mask
294  ivalue=masknodata_opt[imask];
295  else//use same invalid value for each mask
296  ivalue=masknodata_opt[0];
297  if(lineMask[imask][colMask]==ivalue){
298  for(int iband=0;iband<inputReader.nrOfBand();++iband)
299  lineInput[iband][icol]=nodata_opt[imask];
300  masked=true;
301  break;
302  }
303  }
304  }
305  else if(mask_opt.size()){//potentially more invalid values for single mask
306  inputReader.image2geo(icol,irow,x,y);
307  maskReader[0].geo2image(x,y,colMask,rowMask);
308  if(static_cast<int>(rowMask)!=static_cast<int>(oldRowMask)){
309  assert(rowMask>=0&&rowMask<maskReader[0].nrOfRow());
310  try{
311  maskReader[0].readData(lineMask[0],GDT_Int16,static_cast<int>(rowMask));
312  }
313  catch(string errorstring){
314  cerr << errorstring << endl;
315  exit(1);
316  }
317  oldRowMask=rowMask;
318  }
319  for(int ivalue=0;ivalue<masknodata_opt.size();++ivalue){
320  assert(masknodata_opt.size()==nodata_opt.size());
321  if(lineMask[0][colMask]==masknodata_opt[ivalue]){
322  for(int iband=0;iband<inputReader.nrOfBand();++iband)
323  lineInput[iband][icol]=nodata_opt[ivalue];
324  masked=true;
325  break;
326  }
327  }
328  }
329  for(int iband=0;iband<lineOutput.size();++iband){
330  lineOutput[iband][icol]=lineInput[iband][icol];
331  if(find(band_opt.begin(),band_opt.end(),iband)!=band_opt.end()){
332  if(!masked && codemap.find(lineInput[iband][icol])!=codemap.end()){
333  double toValue=codemap[lineInput[iband][icol]];
334  lineOutput[iband][icol]=toValue;
335  }
336  }
337  }
338  }
339  //write buffer lineOutput to output file
340  try{
341  for(int iband=0;iband<outputWriter.nrOfBand();++iband)
342  outputWriter.writeData(lineOutput[iband],GDT_Float64,irow,iband);
343  }
344  catch(string errorstring){
345  cerr << errorstring << endl;
346  exit(1);
347  }
348  //progress bar
349  progress=static_cast<float>((irow+1.0)/outputWriter.nrOfRow());
350  pfnProgress(progress,pszMessage,pProgressArg);
351  }
352  inputReader.close();
353  outputWriter.close();
354  }
355 }