Debian Codegraph @

src/imageclasses/jlcrop_lib.cc

raw symbols SCIP
1 /**********************************************************************
2 jlcrop_lib.cc: perform raster data operations on image such as crop, extract and stack bands
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 <string>
23 #include <iostream>
24 #include <algorithm>
25 #include <memory>
26 #include "imageclasses/Jim.h"
27 #include "imageclasses/VectorOgr.h"
28 #include "imageclasses/JimList.h"
29 #include "base/Optionjl.h"
30 #include "algorithms/Egcs.h"
31 #include "algorithms/StatFactory.h"
32 #include "apps/AppFactory.h"
33 #include "jlcrop_lib.h"
34
35 using namespace std;
36 using namespace app;
37
38 shared_ptr<Jim> Jim::convert(AppFactory& app){
39 shared_ptr<Jim> imgWriter=Jim::createImg();
40 convert(*imgWriter, app);
41 return(imgWriter);
42 }
43
44 shared_ptr<Jim> Jim::convertDataType(const GDALDataType& dataType){
45 shared_ptr<Jim> imgWriter=Jim::createImg();
46 convertDataType(*imgWriter, dataType);
47 return(imgWriter);
48 }
49
50 shared_ptr<Jim> Jim::crop(AppFactory& app){
51 shared_ptr<Jim> imgWriter=Jim::createImg();
52 crop(*imgWriter, app);
53 return(imgWriter);
54 }
55
56 shared_ptr<Jim> Jim::cropBand(AppFactory& app){
57 shared_ptr<Jim> imgWriter=Jim::createImg();
58 cropBand(*imgWriter, app);
59 return(imgWriter);
60 }
61
62 shared_ptr<Jim> Jim::cropPlane(AppFactory& app){
63 shared_ptr<Jim> imgWriter=Jim::createImg();
64 cropPlane(*imgWriter, app);
65 return(imgWriter);
66 }
67
68 shared_ptr<Jim> Jim::cropOgr(VectorOgr& sampleReader, AppFactory& app){
69 shared_ptr<Jim> imgWriter=Jim::createImg();
70 cropOgr(sampleReader, *imgWriter, app);
71 return(imgWriter);
72 }
73
74 // shared_ptr<Jim> Jim::crop(double ulx, double uly, double lrx, double lry, double dx, double dy, bool geo){
75 // shared_ptr<Jim> imgWriter=Jim::createImg();
76 // crop(*imgWriter, ulx, uly, lrx, lry, dx, dy, geo);
77 // return(imgWriter);
78 // }
79
80 // CPLErr Jim::crop(Jim& imgWriter, double ulx, double uly, double lrx, double lry){
81 // app::AppFactory app;
82 // app.setLongOption("ulx",ulx);
83 // app.setLongOption("uly",uly);
84 // app.setLongOption("lrx",lrx);
85 // app.setLongOption("lry",lry);
86 // return(crop(imgWriter,app));
87 // }
88
89 shared_ptr<Jim> Jim::stackBand(Jim& srcImg, AppFactory& app){
90 shared_ptr<Jim> imgWriter=Jim::createImg();
91 stackBand(srcImg, *imgWriter, app);
92 return(imgWriter);
93 }
94
95
96 // void Jim::d_convertType(AppFactory& app){
97 // 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");
98 // Optionjl<short> verbose_opt("v", "verbose", "verbose", 0,2);
99
100 // bool doProcess;//stop process when program was invoked with help option (-h --help)
101 // try{
102 // doProcess=otype_opt.retrieveOption(app);
103 // verbose_opt.retrieveOption(app);
104
105 // if(!doProcess){
106 // cout << endl;
107 // std::ostringstream helpStream;
108 // helpStream << "short option -h shows basic options only, use long option --help to show all options" << std::endl;
109 // throw(helpStream.str());//help was invoked, stop processing
110 // }
111
112 // std::vector<std::string> badKeys;
113 // app.badKeys(badKeys);
114 // if(badKeys.size()){
115 // std::ostringstream errorStream;
116 // if(badKeys.size()>1)
117 // errorStream << "Error: unknown keys: ";
118 // else
119 // errorStream << "Error: unknown key: ";
120 // for(int ikey=0;ikey<badKeys.size();++ikey){
121 // errorStream << badKeys[ikey] << " ";
122 // }
123 // errorStream << std::endl;
124 // throw(errorStream.str());
125 // }
126 // GDALDataType theType=getGDALDataType();
127 // if(otype_opt.size()){
128 // theType=string2GDAL(otype_opt[0]);
129 // if(theType==GDT_Unknown)
130 // std::cout << "Warning: unknown output pixel type: " << otype_opt[0] << ", using input type as default" << std::endl;
131 // }
132 // if(verbose_opt[0]>1)
133 // cout << "Output pixel type: " << GDALGetDataTypeName(theType) << endl;
134
135 // if(scale_opt.size()){
136 // while(scale_opt.size()<nrOfBand())
137 // scale_opt.push_back(scale_opt[0]);
138 // }
139 // if(offset_opt.size()){
140 // while(offset_opt.size()<nrOfBand())
141 // offset_opt.push_back(offset_opt[0]);
142 // }
143 // if(autoscale_opt.size()){
144 // assert(autoscale_opt.size()%2==0);
145 // }
146
147 // if(theType==GDT_Unknown){
148 // theType=this->getGDALDataType();
149 // if(verbose_opt[0]>1)
150 // cout << "Using data type from input image: " << GDALGetDataTypeName(theType) << endl;
151 // }
152 // Jim imgWriter(nrOfCol(),nrOfRow(),1,nrOfPlane(),getDataType());
153 // memcpy(imgWriter.getDataPointer(),m_data[0],getDataTypeSizeBytes()*nrOfCol()*nrOfRow*nrOfPlane());
154 // free(m_data[0]);
155 // m_data[0]=(void *) calloc(static_cast<size_t>(nrOfPlane()*nrOfCol()*nrOfRow()),getDataTypeSizeBytes(otype_opt[0]));
156
157 // for(size_t iband=0;iband<nrOfBand();++iband){
158 // memcpy(m_data[nrOfBand()],m_data[iband],getDataTypeSizeBytes()*nrOfCol()*m_blockSize*oldnplane);
159 // //allocate memory
160 // free(m_data[iband]);
161 // m_data[iband]=(void *) calloc(static_cast<size_t>(nrOfCol()*nrOfRow()*nrOfPlane()),getDataTypeSizeBytes());
162 // memcpy(m_data[iband],m_data[nrOfBand()],getDataTypeSizeBytes()*nrOfCol()*nrOfRow()*oldnplane);
163 // memcpy(m_data[iband]+getDataTypeSizeBytes()*nrOfCol()*nrOfRow()*oldnplane,imgSrc.getDataPointer(iband),imgSrc.getDataTypeSizeBytes()*imgSrc.nrOfCol()*imgSrc.nrOfRow()*imgSrc.nrOfPlane());
164 // }
165 // }
166 // catch(string predefinedString){
167 // std::cerr << predefinedString << std::endl;
168 // throw;
169 // }
170 // }
171
172 void Jim::convertDataType(Jim& imgWriter, const GDALDataType& dataType){
173 imgWriter.open(nrOfCol(),nrOfRow(),nrOfBand(),nrOfPlane(),dataType);
174 imgWriter.copyGeoTransform(*this);
175 imgWriter.setProjection(this->getProjection());
176 switch(getDataType()){
177 case(GDT_Byte):
178 switch(dataType){
179 case(GDT_Byte):
180 convertDataType_t<unsigned char,unsigned char>(imgWriter);
181 break;
182 case(GDT_Int16):
183 convertDataType_t<unsigned char,short>(imgWriter);
184 break;
185 case(GDT_UInt16):
186 convertDataType_t<unsigned char,unsigned short>(imgWriter);
187 break;
188 case(GDT_Int32):
189 convertDataType_t<unsigned char,int>(imgWriter);
190 break;
191 case(GDT_UInt32):
192 convertDataType_t<unsigned char,unsigned int>(imgWriter);
193 break;
194 case(GDT_Float32):
195 convertDataType_t<unsigned char,float>(imgWriter);
196 break;
197 case(GDT_Float64):
198 convertDataType_t<unsigned char,double>(imgWriter);
199 break;
200 default:
201 std::string errorString="Error: data type not supported";
202 throw(errorString);
203 break;
204 }
205 break;
206 case(GDT_Int16):
207 switch(dataType){
208 case(GDT_Byte):
209 convertDataType_t<short,unsigned char>(imgWriter);
210 break;
211 case(GDT_Int16):
212 convertDataType_t<short,short>(imgWriter);
213 break;
214 case(GDT_UInt16):
215 convertDataType_t<short,unsigned short>(imgWriter);
216 break;
217 case(GDT_Int32):
218 convertDataType_t<short,int>(imgWriter);
219 break;
220 case(GDT_UInt32):
221 convertDataType_t<short,unsigned int>(imgWriter);
222 break;
223 case(GDT_Float32):
224 convertDataType_t<short,float>(imgWriter);
225 break;
226 case(GDT_Float64):
227 convertDataType_t<short,double>(imgWriter);
228 break;
229 default:
230 std::string errorString="Error: data type not supported";
231 throw(errorString);
232 break;
233 }
234 break;
235 case(GDT_UInt16):
236 switch(dataType){
237 case(GDT_Byte):
238 convertDataType_t<unsigned short,unsigned char>(imgWriter);
239 break;
240 case(GDT_Int16):
241 convertDataType_t<unsigned short,short>(imgWriter);
242 break;
243 case(GDT_UInt16):
244 convertDataType_t<unsigned short,unsigned short>(imgWriter);
245 break;
246 case(GDT_Int32):
247 convertDataType_t<unsigned short,int>(imgWriter);
248 break;
249 case(GDT_UInt32):
250 convertDataType_t<unsigned short,unsigned int>(imgWriter);
251 break;
252 case(GDT_Float32):
253 convertDataType_t<unsigned short,float>(imgWriter);
254 break;
255 case(GDT_Float64):
256 convertDataType_t<unsigned short,double>(imgWriter);
257 break;
258 default:
259 std::string errorString="Error: data type not supported";
260 throw(errorString);
261 break;
262 }
263 break;
264 case(GDT_Int32):
265 switch(dataType){
266 case(GDT_Byte):
267 convertDataType_t<int,unsigned char>(imgWriter);
268 break;
269 case(GDT_Int16):
270 convertDataType_t<int,short>(imgWriter);
271 break;
272 case(GDT_UInt16):
273 convertDataType_t<int,unsigned short>(imgWriter);
274 break;
275 case(GDT_Int32):
276 convertDataType_t<int,int>(imgWriter);
277 break;
278 case(GDT_UInt32):
279 convertDataType_t<int,unsigned int>(imgWriter);
280 break;
281 case(GDT_Float32):
282 convertDataType_t<int,float>(imgWriter);
283 break;
284 case(GDT_Float64):
285 convertDataType_t<int,double>(imgWriter);
286 break;
287 default:
288 std::string errorString="Error: data type not supported";
289 throw(errorString);
290 break;
291 }
292 break;
293 case(GDT_UInt32):
294 switch(dataType){
295 case(GDT_Byte):
296 convertDataType_t<unsigned int,unsigned char>(imgWriter);
297 break;
298 case(GDT_Int16):
299 convertDataType_t<unsigned int,short>(imgWriter);
300 break;
301 case(GDT_UInt16):
302 convertDataType_t<unsigned int,unsigned short>(imgWriter);
303 break;
304 case(GDT_Int32):
305 convertDataType_t<unsigned int,int>(imgWriter);
306 break;
307 case(GDT_UInt32):
308 convertDataType_t<unsigned int,unsigned int>(imgWriter);
309 break;
310 case(GDT_Float32):
311 convertDataType_t<unsigned int,float>(imgWriter);
312 break;
313 case(GDT_Float64):
314 convertDataType_t<unsigned int,double>(imgWriter);
315 break;
316 default:
317 std::string errorString="Error: data type not supported";
318 throw(errorString);
319 break;
320 }
321 break;
322 case(GDT_Float32):
323 switch(dataType){
324 case(GDT_Byte):
325 convertDataType_t<float,unsigned char>(imgWriter);
326 break;
327 case(GDT_Int16):
328 convertDataType_t<float,short>(imgWriter);
329 break;
330 case(GDT_UInt16):
331 convertDataType_t<float,unsigned short>(imgWriter);
332 break;
333 case(GDT_Int32):
334 convertDataType_t<float,int>(imgWriter);
335 break;
336 case(GDT_UInt32):
337 convertDataType_t<float,unsigned int>(imgWriter);
338 break;
339 case(GDT_Float32):
340 convertDataType_t<float,float>(imgWriter);
341 break;
342 case(GDT_Float64):
343 convertDataType_t<float,double>(imgWriter);
344 break;
345 default:
346 std::string errorString="Error: data type not supported";
347 throw(errorString);
348 break;
349 }
350 break;
351 case(GDT_Float64):
352 switch(dataType){
353 case(GDT_Byte):
354 convertDataType_t<double,unsigned char>(imgWriter);
355 break;
356 case(GDT_Int16):
357 convertDataType_t<double,short>(imgWriter);
358 break;
359 case(GDT_UInt16):
360 convertDataType_t<double,unsigned short>(imgWriter);
361 break;
362 case(GDT_Int32):
363 convertDataType_t<double,int>(imgWriter);
364 break;
365 case(GDT_UInt32):
366 convertDataType_t<double,unsigned int>(imgWriter);
367 break;
368 case(GDT_Float32):
369 convertDataType_t<double,float>(imgWriter);
370 break;
371 case(GDT_Float64):
372 convertDataType_t<double,double>(imgWriter);
373 break;
374 default:
375 std::string errorString="Error: data type not supported";
376 throw(errorString);
377 break;
378 }
379 break;
380 default:
381 std::string errorString="Error: data type not supported";
382 throw(errorString);
383 break;
384 }
385 }
386
387 void Jim::convert(Jim& imgWriter, AppFactory& app){
388 Optionjl<string> projection_opt("a_srs", "a_srs", "Override the projection for the output file (leave blank to copy from input file, use epsg:3035 to use European projection and force to European grid");
389 Optionjl<double> autoscale_opt("as", "autoscale", "scale output to min and max, e.g., --autoscale 0 --autoscale 255");
390 Optionjl<double> scale_opt("scale", "scale", "output=scale*input+offset");
391 Optionjl<double> offset_opt("offset", "offset", "output=scale*input+offset");
392 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");
393 Optionjl<double> nodata_opt("nodata", "nodata", "No data value");
394 Optionjl<string> description_opt("d", "description", "Set image description");
395 Optionjl<short> verbose_opt("v", "verbose", "verbose", 0,2);
396
397 bool doProcess;//stop process when program was invoked with help option (-h --help)
398 try{
399 doProcess=projection_opt.retrieveOption(app);
400 autoscale_opt.retrieveOption(app);
401 otype_opt.retrieveOption(app);
402 scale_opt.retrieveOption(app);
403 offset_opt.retrieveOption(app);
404 nodata_opt.retrieveOption(app);
405 description_opt.retrieveOption(app);
406 verbose_opt.retrieveOption(app);
407
408 if(!doProcess){
409 cout << endl;
410 std::ostringstream helpStream;
411 helpStream << "short option -h shows basic options only, use long option --help to show all options" << std::endl;
412 throw(helpStream.str());//help was invoked, stop processing
413 }
414
415 std::vector<std::string> badKeys;
416 app.badKeys(badKeys);
417 if(badKeys.size()){
418 std::ostringstream errorStream;
419 if(badKeys.size()>1)
420 errorStream << "Error: unknown keys: ";
421 else
422 errorStream << "Error: unknown key: ";
423 for(int ikey=0;ikey<badKeys.size();++ikey){
424 errorStream << badKeys[ikey] << " ";
425 }
426 errorStream << std::endl;
427 throw(errorStream.str());
428 }
429
430 double nodataValue=nodata_opt.size()? nodata_opt[0] : 0;
431 GDALDataType theType=getGDALDataType();
432 if(otype_opt.size()){
433 theType=string2GDAL(otype_opt[0]);
434 if(theType==GDT_Unknown)
435 std::cout << "Warning: unknown output pixel type: " << otype_opt[0] << ", using input type as default" << std::endl;
436 }
437 if(verbose_opt[0]>1)
438 cout << "Output pixel type: " << GDALGetDataTypeName(theType) << endl;
439
440 if(scale_opt.size()){
441 while(scale_opt.size()<nrOfBand())
442 scale_opt.push_back(scale_opt[0]);
443 }
444 if(offset_opt.size()){
445 while(offset_opt.size()<nrOfBand())
446 offset_opt.push_back(offset_opt[0]);
447 }
448 if(autoscale_opt.size()){
449 assert(autoscale_opt.size()%2==0);
450 }
451
452 if(theType==GDT_Unknown){
453 theType=this->getGDALDataType();
454 if(verbose_opt[0]>1)
455 cout << "Using data type from input image: " << GDALGetDataTypeName(theType) << endl;
456 }
457 imgWriter.open(nrOfCol(),nrOfRow(),nrOfBand(),theType);
458 imgWriter.setNoData(nodata_opt);
459 if(nodata_opt.size())
460 imgWriter.GDALSetNoDataValue(nodata_opt[0]);
461 imgWriter.copyGeoTransform(*this);
462 imgWriter.setProjection(this->getProjection());
463
464 if(description_opt.size())
465 imgWriter.setImageDescription(description_opt[0]);
466
467 unsigned int nband=this->nrOfBand();
468
469 // const char* pszMessage;
470 // void* pProgressArg=NULL;
471 // GDALProgressFunc pfnProgress=GDALTermProgress;
472 // double progress=0;
473 // MyProgressFunc(progress,pszMessage,pProgressArg);
474
475 for(unsigned int iband=0;iband<nband;++iband){
476 unsigned int readBand=iband;
477 if(verbose_opt[0]>1){
478 cout << "extracting band " << readBand << endl;
479 // MyProgressFunc(progress,pszMessage,pProgressArg);
480 }
481 double theMin=0;
482 double theMax=0;
483 if(autoscale_opt.size()){
484 this->getMinMax(0,nrOfCol()-1,0,nrOfRow()-1,readBand,theMin,theMax);
485 if(verbose_opt[0]>1)
486 cout << "minmax: " << theMin << ", " << theMax << endl;
487 double theScale=(autoscale_opt[1]-autoscale_opt[0])/(theMax-theMin);
488 double theOffset=autoscale_opt[0]-theScale*theMin;
489 this->setScale(theScale,readBand);
490 this->setOffset(theOffset,readBand);
491 }
492 else{
493 if(scale_opt.size()){
494 if(scale_opt.size()>iband)
495 this->setScale(scale_opt[iband],readBand);
496 else
497 this->setScale(scale_opt[0],readBand);
498 }
499 if(offset_opt.size()){
500 if(offset_opt.size()>iband)
501 this->setOffset(offset_opt[iband],readBand);
502 else
503 this->setOffset(offset_opt[0],readBand);
504 }
505 }
506
507 double readRow=0;
508 double readCol=0;
509 double lowerCol=0;
510 double upperCol=0;
511 #if JIPLIB_PROCESS_IN_PARALLEL == 1
512 #pragma omp parallel for
513 #else
514 #endif
515 for(int irow=0;irow<imgWriter.nrOfRow();++irow){
516 vector<double> readBuffer(nrOfCol());
517 vector<double> writeBuffer(nrOfCol());
518 // readRow=irow;
519 readData(readBuffer,irow,readBand);
520 for(int icol=0;icol<imgWriter.nrOfCol();++icol)
521 writeBuffer[icol]=readBuffer[icol];
522 imgWriter.writeData(writeBuffer,irow,readBand);
523 // progress=(1.0+irow);
524 // progress+=(imgWriter.nrOfRow()*readBand);
525 // progress/=imgWriter.nrOfBand()*imgWriter.nrOfRow();
526 // assert(progress>=0);
527 // assert(progress<=1);
528 // MyProgressFunc(progress,pszMessage,pProgressArg);
529 }
530 }
531 }
532 catch(string predefinedString){
533 std::cerr << predefinedString << std::endl;
534 throw;
535 }
536 }
537
538 // CPLErr Jim::crop(Jim& imgWriter, double ulx, double uly, double lrx, double lry, double dx, double dy, bool geo){
539 void Jim::crop(Jim& imgWriter, AppFactory& app){
540 Optionjl<double> ulx_opt("ulx", "ulx", "Upper left x value bounding box", 0.0);
541 Optionjl<double> uly_opt("uly", "uly", "Upper left y value bounding box", 0.0);
542 Optionjl<double> lrx_opt("lrx", "lrx", "Lower right x value bounding box", 0.0);
543 Optionjl<double> lry_opt("lry", "lry", "Lower right y value bounding box", 0.0);
544 Optionjl<double> dx_opt("dx", "dx", "spatial resolution in x (in spatial reference system or pixels if nogeo is set)",0);
545 Optionjl<double> dy_opt("dy", "dy", "spatial resolution in y (in spatial reference system or piyels if nogeo is set)",0);
546 Optionjl<double> nodata_opt("nodata", "nodata", "Nodata value to put in image if out of bounds.", 0);
547 Optionjl<bool> align_opt("align", "align", "Align output bounding box to input image",false);
548 Optionjl<bool> nogeo_opt("nogeo", "nogeo", "use image coordinates instead of spatial reference system",false);
549 Optionjl<short> verbose_opt("v", "verbose", "verbose", 0,2);
550
551 bool doProcess;//stop process when program was invoked with help option (-h --help)
552 try{
553 doProcess=ulx_opt.retrieveOption(app);
554 ulx_opt.retrieveOption(app);
555 uly_opt.retrieveOption(app);
556 lrx_opt.retrieveOption(app);
557 lry_opt.retrieveOption(app);
558 dx_opt.retrieveOption(app);
559 dy_opt.retrieveOption(app);
560 nodata_opt.retrieveOption(app);
561 align_opt.retrieveOption(app);
562 nogeo_opt.retrieveOption(app);
563 verbose_opt.retrieveOption(app);
564
565 if(!doProcess){
566 cout << endl;
567 std::ostringstream helpStream;
568 helpStream << "short option -h shows basic options only, use long option --help to show all options" << std::endl;
569 throw(helpStream.str());//help was invoked, stop processing
570 }
571
572 std::vector<std::string> badKeys;
573 app.badKeys(badKeys);
574 if(badKeys.size()){
575 std::ostringstream errorStream;
576 if(badKeys.size()>1)
577 errorStream << "Error: unknown keys: ";
578 else
579 errorStream << "Error: unknown key: ";
580 for(int ikey=0;ikey<badKeys.size();++ikey){
581 errorStream << badKeys[ikey] << " ";
582 }
583 errorStream << std::endl;
584 throw(errorStream.str());
585 }
586 if(m_data.empty()){
587 std::ostringstream s;
588 s << "Error: Jim not initialized, m_data is empty";
589 std::cerr << s.str() << std::endl;
590 throw(s.str());
591 }
592 double cropuli=0;
593 double cropulj=0;
594 double croplri=0;
595 double croplrj=0;
596 double stridei=1;
597 double stridej=1;
598 double cropulx=ulx_opt[0];
599 double cropuly=uly_opt[0];
600 double croplrx=lrx_opt[0];
601 double croplry=lry_opt[0];
602 double dx=dx_opt[0];
603 double dy=dy_opt[0];
604 if(nogeo_opt[0]){
605 if(verbose_opt[0]>1){
606 std::cout << "crop in nogeo mode" << std::endl;
607 std::cout << "cropulx: " << cropulx << std::endl;
608 std::cout << "cropuly: " << cropuly << std::endl;
609 std::cout << "croplrx: " << croplrx << std::endl;
610 std::cout << "croplry: " << croplry << std::endl;
611 std::cout << "dx: " << dx << std::endl;
612 std::cout << "dy: " << dy << std::endl;
613 }
614 if(cropulx>=croplrx){
615 cropulx=0;
616 croplrx=nrOfCol();
617 }
618 if(cropuly>=croplry){
619 cropuly=0;
620 croplry=nrOfRow();
621 }
622 cropuli=cropulx;
623 cropulj=cropuly;
624 croplri=croplrx;
625 croplrj=croplry;
626 if(dx>0)
627 stridei=dx;
628 else
629 stridei=1;
630 dx=stridei*getDeltaX();
631 if(dy>0)
632 stridej=dy;
633 else
634 stridej=1;
635 dy=stridej*getDeltaY();
636
637 this->image2geo(cropuli,cropulj,cropulx,cropuly);
638 this->image2geo(croplri,croplrj,croplrx,croplry);
639
640 cropulx-=getDeltaX()/2;
641 cropuly+=getDeltaY()/2;
642
643 croplrx-=this->getDeltaX()/2.0;
644 croplry+=this->getDeltaY()/2.0;
645 }
646 else{
647 if(verbose_opt[0]>1){
648 std::cout << "crop in geo mode" << std::endl;
649 std::cout << "cropulx: " << cropulx << std::endl;
650 std::cout << "cropuly: " << cropuly << std::endl;
651 std::cout << "croplrx: " << croplrx << std::endl;
652 std::cout << "croplry: " << croplry << std::endl;
653 std::cout << "dx: " << dx << std::endl;
654 std::cout << "dy: " << dy << std::endl;
655 }
656 if(cropulx>=croplrx){
657 cropulx=getUlx();
658 croplrx=getLrx();
659 }
660 if(cropuly<=croplry){
661 cropuly=getUly();
662 croplry=getLry();
663 }
664 if(align_opt[0]){
665 if(verbose_opt[0]>1)
666 std::cout << "using align option" << std::endl;
667 //do align
668 if(dx>0){
669 if(cropulx>this->getUlx())
670 cropulx-=fmod(cropulx-this->getUlx(),dx);
671 else if(cropulx<this->getUlx())
672 cropulx+=fmod(this->getUlx()-cropulx,dx)-dx;
673 if(croplrx<this->getLrx())
674 croplrx+=fmod(this->getLrx()-croplrx,dx);
675 else if(croplrx>this->getLrx())
676 croplrx-=fmod(croplrx-this->getLrx(),dx)+dx;
677 }
678 if(dy>0){
679 if(croplry>this->getLry())
680 croplry-=fmod(croplry-this->getLry(),dy);
681 else if(croplry<this->getLry())
682 croplry+=fmod(this->getLry()-croplry,dy)-dy;
683 if(cropuly<this->getUly())
684 cropuly+=fmod(this->getUly()-cropuly,dy);
685 else if(cropuly>this->getUly())
686 cropuly-=fmod(cropuly-this->getUly(),dy)+dy;
687 }
688 }
689 else{
690 if(dx>0){
691 stridei=dx/getDeltaX();
692 // stridei=(croplrx-cropulx)/dx;
693 }
694 else{
695 stridei=1;
696 dx=getDeltaX();
697 }
698 if(dy>0){
699 stridej=dy/getDeltaY();
700 // stridej=(cropuly-croplry)/dy;
701 }
702 else{
703 stridej=1;
704 dy=getDeltaY();
705 }
706 }
707 this->geo2image(cropulx,cropuly,cropuli,cropulj);
708 this->geo2image(croplrx-this->getDeltaX(),croplry+this->getDeltaY(),croplri,croplrj);
709
710 cropuli=floor(cropuli);
711 cropulj=floor(cropulj);
712 croplri=floor(croplri)+1;
713 croplrj=floor(croplrj)+1;
714 // croplri=ceil(croplri);
715 // croplrj=ceil(croplrj);
716 }
717 // size_t ncropcol=(croplri-cropuli)/stridei;
718 // size_t ncroprow=(croplrj-cropulj)/stridej;
719 size_t ncropcol=(croplrx-cropulx)/dx;
720 size_t ncroprow=(cropuly-croplry)/dy;
721 if(verbose_opt[0]>1){
722 std::cout << "ncropcol: " << ncropcol << std::endl;
723 std::cout << "ncroprow: " << ncroprow << std::endl;
724 std::cout << "dx: " << dx << std::endl;
725 std::cout << "dy: " << dy << std::endl;
726 std::cout << "stridei: " << stridei << std::endl;
727 std::cout << "stridej: " << stridej << std::endl;
728 }
729 try{
730 imgWriter.open(ncropcol,ncroprow,nrOfBand(),this->getGDALDataType());
731 }
732 catch(string errorstring){
733 cerr << errorstring << endl;
734 throw;
735 }
736 double gt[6];
737 gt[0]=cropulx;
738 gt[1]=dx;
739 gt[2]=0;
740 gt[3]=cropuly;
741 gt[4]=0;
742 gt[5]=-dy;
743 imgWriter.setGeoTransform(gt);
744 imgWriter.setProjection(this->getProjection());
745 // double nodataValue=m_noDataValues.size() ? m_noDataValues[0] : 0;
746 std::ostringstream errorStream;
747
748 if(verbose_opt[0]>1){
749 std::cout << "cropuli: " << cropuli << std::endl;
750 std::cout << "cropulj: " << cropulj << std::endl;
751 std::cout << "stridei: " << stridei << std::endl;
752 std::cout << "stridej: " << stridej << std::endl;
753 }
754 if(cropuli+stridei/2 < 0 || cropuli+(ncropcol-1)*stridei+stridei/2 >= nrOfCol()){
755 errorStream << "Warning: columns requested out of bounding box" << std::endl;
756 errorStream << "cropuli+stridei/2: " << cropuli+stridei/2 << std::endl;
757 errorStream << "cropuli+(ncropcol-1)*stridei+stridei/2: " << cropuli+(ncropcol-1)*stridei+stridei/2 << std::endl;
758 if(verbose_opt[0]>1)
759 std::cerr << errorStream.str() << std::endl;
760 imgWriter.setNoDataValue(nodata_opt[0]);
761 }
762 if(cropulj+stridej/2<0 || cropulj+(ncroprow-1)*stridej+stridej/2 >= nrOfRow()){
763 errorStream << "Warning: rows requested out of bounding box" << std::endl;
764 errorStream << "cropulj+stridej/2: " << cropulj+stridej/2 << std::endl;
765 errorStream << "cropulj+(ncroprow-1)*stridej+stridej/2: " << cropulj+(ncroprow-1)*stridej+stridej/2 << std::endl;
766 if(verbose_opt[0]>1)
767 std::cerr << errorStream.str() << std::endl;
768 imgWriter.setNoDataValue(nodata_opt[0]);
769 }
770
771 for(size_t iband=0;iband<nrOfBand();++iband){
772 for(int irow=0;irow<imgWriter.nrOfRow();++irow){
773 double readRow=cropulj+irow*stridej+stridej/2;
774 if(readRow<0||readRow>=this->nrOfRow()){
775 for(int icol=0;icol<imgWriter.nrOfCol();++icol)
776 imgWriter.writeData(nodata_opt[0],icol,irow,iband);
777 }
778 else{
779 for(int icol=0;icol<imgWriter.nrOfCol();++icol){
780 double readCol=cropuli+icol*stridei+stridei/2;
781 if(readCol<0||readCol>=this->nrOfCol()){
782 imgWriter.writeData(nodata_opt[0],icol,irow,iband);
783 }
784 else{
785 double readValue=0;
786 this->readData(readValue,readCol,readRow,iband);
787 imgWriter.writeData(readValue,icol,irow,iband);
788 }
789 }
790 }
791 }
792 }
793 }
794 catch(string errorstring){
795 std::string errorString="String exception";
796 std::cerr << errorString << errorstring << std::endl;
797 throw(errorString);
798 }
799 catch(BadConversion conversion){
800 std::string errorString="Bad conversion in arguments exception";
801 std::cerr << errorString << std::endl;
802 app.showOptions();
803 throw(errorString);
804 }
805 catch(...){
806 std::string errorString="Unknown exception";
807 throw(errorString);
808 }
809 }
810
811 // CPLErr Jim::crop(Jim& imgWriter, AppFactory& app){
812 // Optionjl<string> projection_opt("a_srs", "a_srs", "Override the projection for the output file (leave blank to copy from input file, use epsg:3035 to use European projection and force to European grid");
813 // //todo: support layer names
814 // Optionjl<double> ulx_opt("ulx", "ulx", "Upper left x value bounding box", 0.0);
815 // Optionjl<double> uly_opt("uly", "uly", "Upper left y value bounding box", 0.0);
816 // Optionjl<double> lrx_opt("lrx", "lrx", "Lower right x value bounding box", 0.0);
817 // Optionjl<double> lry_opt("lry", "lry", "Lower right y value bounding box", 0.0);
818 // Optionjl<double> cx_opt("x", "x", "x-coordinate of image center to crop (in meter)");
819 // Optionjl<double> cy_opt("y", "y", "y-coordinate of image center to crop (in meter)");
820 // Optionjl<double> nx_opt("nx", "nx", "image size in x to crop (in meter)");
821 // Optionjl<double> ny_opt("ny", "ny", "image size in y to crop (in meter)");
822 // Optionjl<unsigned int> ns_opt("ns", "ns", "number of samples to crop (in pixels)");
823 // Optionjl<unsigned int> nl_opt("nl", "nl", "number of lines to crop (in pixels)");
824 // Optionjl<double> nodata_opt("nodata", "nodata", "Nodata value to put in image if out of bounds.");
825 // Optionjl<bool> align_opt("align", "align", "Align output bounding box to input image",false);
826 // Optionjl<short> verbose_opt("v", "verbose", "verbose", 0,2);
827
828 // bool doProcess;//stop process when program was invoked with help option (-h --help)
829 // try{
830 // doProcess=projection_opt.retrieveOption(app);
831 // ulx_opt.retrieveOption(app);
832 // uly_opt.retrieveOption(app);
833 // lrx_opt.retrieveOption(app);
834 // lry_opt.retrieveOption(app);
835 // cx_opt.retrieveOption(app);
836 // cy_opt.retrieveOption(app);
837 // nx_opt.retrieveOption(app);
838 // ny_opt.retrieveOption(app);
839 // ns_opt.retrieveOption(app);
840 // nl_opt.retrieveOption(app);
841 // nodata_opt.retrieveOption(app);
842 // align_opt.retrieveOption(app);
843 // verbose_opt.retrieveOption(app);
844
845 // if(!doProcess){
846 // cout << endl;
847 // std::ostringstream helpStream;
848 // helpStream << "short option -h shows basic options only, use long option --help to show all options" << std::endl;
849 // throw(helpStream.str());//help was invoked, stop processing
850 // }
851
852 // std::vector<std::string> badKeys;
853 // app.badKeys(badKeys);
854 // if(badKeys.size()){
855 // std::ostringstream errorStream;
856 // if(badKeys.size()>1)
857 // errorStream << "Error: unknown keys: ";
858 // else
859 // errorStream << "Error: unknown key: ";
860 // for(int ikey=0;ikey<badKeys.size();++ikey){
861 // errorStream << badKeys[ikey] << " ";
862 // }
863 // errorStream << std::endl;
864 // throw(errorStream.str());
865 // }
866
867 // double nodataValue=nodata_opt.size()? nodata_opt[0] : 0;
868 // bool isGeoRef=false;
869 // string projectionString;
870 // // for(int iimg=0;iimg<input_opt.size();++iimg){
871
872 // if(!isGeoRef)
873 // isGeoRef=this->isGeoRef();
874 // GDALDataType theType=getGDALDataType();
875 // if(verbose_opt[0])
876 // cout << "Output pixel type: " << GDALGetDataTypeName(theType) << endl;
877
878 // //bounding box of cropped image
879 // double cropulx=ulx_opt[0];
880 // double cropuly=uly_opt[0];
881 // double croplrx=lrx_opt[0];
882 // double croplry=lry_opt[0];
883 // double dx=getDeltaX();
884 // double dy=getDeltaY();
885 // // if(cx_opt.size()&&cy_opt.size()&&nx_opt.size()&&ny_opt.size()){
886 // if(nx_opt.size()&&ny_opt.size()){
887 // if(cx_opt.size()&&cy_opt.size()){
888 // ulx_opt[0]=cx_opt[0]-nx_opt[0]/2.0;
889 // uly_opt[0]=(isGeoRef) ? cy_opt[0]+ny_opt[0]/2.0 : cy_opt[0]-ny_opt[0]/2.0;
890 // lrx_opt[0]=cx_opt[0]+nx_opt[0]/2.0;
891 // lry_opt[0]=(isGeoRef) ? cy_opt[0]-ny_opt[0]/2.0 : cy_opt[0]+ny_opt[0]/2.0;
892 // }
893 // else if(ulx_opt.size()&&uly_opt.size()){
894 // lrx_opt[0]=ulx_opt[0]+nx_opt[0];
895 // lry_opt[0]=lry_opt[0]-ny_opt[0];
896 // }
897 // }
898 // else if(ns_opt.size()&&nl_opt.size()){
899 // if(cx_opt.size()&&cy_opt.size()){
900 // ulx_opt[0]=cx_opt[0]-ns_opt[0]*dx/2.0;
901 // uly_opt[0]=(isGeoRef) ? cy_opt[0]+nl_opt[0]*dy/2.0 : cy_opt[0]-nl_opt[0]*dy/2.0;
902 // lrx_opt[0]=cx_opt[0]+ns_opt[0]*dx/2.0;
903 // lry_opt[0]=(isGeoRef) ? cy_opt[0]-nl_opt[0]*dy/2.0 : cy_opt[0]+nl_opt[0]*dy/2.0;
904 // }
905 // else if(ulx_opt.size()&&uly_opt.size()){
906 // lrx_opt[0]=ulx_opt[0]+ns_opt[0]*dx;
907 // lry_opt[0]=uly_opt[0]-nl_opt[0]*dy;
908 // }
909 // }
910
911 // if(verbose_opt[0])
912 // cout << "--ulx=" << ulx_opt[0] << " --uly=" << uly_opt[0] << " --lrx=" << lrx_opt[0] << " --lry=" << lry_opt[0] << endl;
913
914 // int ncropcol=0;
915 // int ncroprow=0;
916
917 // double uli,ulj,lri,lrj;//image coordinates
918 // bool forceEUgrid=false;
919 // if(projection_opt.size())
920 // forceEUgrid=(!(projection_opt[0].compare("EPSG:3035"))||!(projection_opt[0].compare("EPSG:3035"))||projection_opt[0].find("ETRS-LAEA")!=string::npos);
921 // if(ulx_opt[0]>=lrx_opt[0]){//default bounding box: no cropping
922 // uli=0;
923 // lri=this->nrOfCol()-1;
924 // ulj=0;
925 // lrj=this->nrOfRow()-1;
926 // ncropcol=this->nrOfCol();
927 // ncroprow=this->nrOfRow();
928 // this->getBoundingBox(cropulx,cropuly,croplrx,croplry);
929 // double magicX=1,magicY=1;
930 // // this->getMagicPixel(magicX,magicY);
931 // if(forceEUgrid){
932 // //force to LAEA grid
933 // Egcs egcs;
934 // egcs.setLevel(egcs.res2level(dx));
935 // egcs.force2grid(cropulx,cropuly,croplrx,croplry);
936 // this->geo2image(cropulx+(magicX-1.0)*this->getDeltaX(),cropuly-(magicY-1.0)*this->getDeltaY(),uli,ulj);
937 // this->geo2image(croplrx+(magicX-2.0)*this->getDeltaX(),croplry-(magicY-2.0)*this->getDeltaY(),lri,lrj);
938 // }
939 // this->geo2image(cropulx+(magicX-1.0)*this->getDeltaX(),cropuly-(magicY-1.0)*this->getDeltaY(),uli,ulj);
940 // this->geo2image(croplrx+(magicX-2.0)*this->getDeltaX(),croplry-(magicY-2.0)*this->getDeltaY(),lri,lrj);
941 // // ncropcol=abs(static_cast<unsigned int>(ceil((croplrx-cropulx)/dx)));
942 // // ncroprow=abs(static_cast<unsigned int>(ceil((cropuly-croplry)/dy)));
943 // ncropcol=static_cast<unsigned int>(ceil((croplrx-cropulx)/dx));
944 // ncroprow=static_cast<unsigned int>(ceil((cropuly-croplry)/dy));
945 // std::cerr << "Warning: unexpected bounding box, using defaults "<< "--ulx=" << cropulx << " --uly=" << cropuly << " --lrx=" << croplrx << " --lry=" << croplry << std::endl;
946 // }
947 // else{
948 // double magicX=1,magicY=1;
949 // // this->getMagicPixel(magicX,magicY);
950 // cropulx=ulx_opt[0];
951 // cropuly=uly_opt[0];
952 // croplrx=lrx_opt[0];
953 // croplry=lry_opt[0];
954 // if(forceEUgrid){
955 // //force to LAEA grid
956 // Egcs egcs;
957 // egcs.setLevel(egcs.res2level(dx));
958 // egcs.force2grid(cropulx,cropuly,croplrx,croplry);
959 // }
960 // else if(align_opt[0]){
961 // if(cropulx>this->getUlx())
962 // cropulx-=fmod(cropulx-this->getUlx(),dx);
963 // else if(cropulx<this->getUlx())
964 // cropulx+=fmod(this->getUlx()-cropulx,dx)-dx;
965 // if(croplrx<this->getLrx())
966 // croplrx+=fmod(this->getLrx()-croplrx,dx);
967 // else if(croplrx>this->getLrx())
968 // croplrx-=fmod(croplrx-this->getLrx(),dx)+dx;
969 // if(croplry>this->getLry())
970 // croplry-=fmod(croplry-this->getLry(),dy);
971 // else if(croplry<this->getLry())
972 // croplry+=fmod(this->getLry()-croplry,dy)-dy;
973 // if(cropuly<this->getUly())
974 // cropuly+=fmod(this->getUly()-cropuly,dy);
975 // else if(cropuly>this->getUly())
976 // cropuly-=fmod(cropuly-this->getUly(),dy)+dy;
977 // }
978 // this->geo2image(cropulx+(magicX-1.0)*this->getDeltaX(),cropuly-(magicY-1.0)*this->getDeltaY(),uli,ulj);
979 // this->geo2image(croplrx+(magicX-2.0)*this->getDeltaX(),croplry-(magicY-2.0)*this->getDeltaY(),lri,lrj);
980
981 // ncropcol=static_cast<unsigned int>(ceil((croplrx-cropulx)/dx));
982 // ncroprow=static_cast<unsigned int>(ceil((cropuly-croplry)/dy));
983 // uli=floor(uli);
984 // ulj=floor(ulj);
985 // lri=floor(lri);
986 // lrj=floor(lrj);
987
988 // if(cropulx<getUlx() || cropuly>getUly() || croplrx>getLrx() || croplry<getLry()){
989 // std::cerr << "Warning: requested bounding box not within original bounding box, using "<< "--ulx=" << cropulx << " --uly=" << cropuly << " --lrx=" << croplrx << " --lry=" << croplry << std::endl;
990 // }
991 // }
992
993 // if(!imgWriter.nrOfBand()){//not opened yet
994 // if(verbose_opt[0]){
995 // cout << "cropulx: " << cropulx << endl;
996 // cout << "cropuly: " << cropuly << endl;
997 // cout << "croplrx: " << croplrx << endl;
998 // cout << "croplry: " << croplry << endl;
999 // cout << "ncropcol: " << ncropcol << endl;
1000 // cout << "ncroprow: " << ncroprow << endl;
1001 // cout << "cropulx+ncropcol*dx: " << cropulx+ncropcol*dx << endl;
1002 // cout << "cropuly-ncroprow*dy: " << cropuly-ncroprow*dy << endl;
1003 // cout << "upper left column of input image: " << uli << endl;
1004 // cout << "upper left row of input image: " << ulj << endl;
1005 // cout << "lower right column of input image: " << lri << endl;
1006 // cout << "lower right row of input image: " << lrj << endl;
1007 // cout << "new number of cols: " << ncropcol << endl;
1008 // cout << "new number of rows: " << ncroprow << endl;
1009 // cout << "new number of bands: " << nrOfBand()<< endl;
1010 // }
1011 // try{
1012 // imgWriter.open(ncropcol,ncroprow,nrOfBand(),theType);
1013 // imgWriter.setNoData(nodata_opt);
1014 // }
1015 // catch(string errorstring){
1016 // cout << errorstring << endl;
1017 // throw;
1018 // }
1019 // double gt[6];
1020 // gt[0]=cropulx;
1021 // gt[1]=getDeltaX();
1022 // gt[2]=0;
1023 // gt[3]=cropuly;
1024 // gt[4]=0;
1025 // gt[5]=-getDeltaY();
1026 // imgWriter.setGeoTransform(gt);
1027 // if(projection_opt.size()){
1028 // if(verbose_opt[0])
1029 // cout << "projection: " << projection_opt[0] << endl;
1030 // imgWriter.setProjectionProj4(projection_opt[0]);
1031 // }
1032 // else
1033 // imgWriter.setProjection(this->getProjection());
1034 // }
1035
1036 // // if(!covers(cropulx,cropuly,croplrx,croplry,true)){
1037 // // //todo: extend image in case of no full coverage
1038 // // std::cerr << "Error: no full coverage" << std::endl;
1039 // // throw;
1040 // // }
1041 // double startCol=uli;
1042 // double endCol=lri;
1043 // if(uli<0){
1044 // std::cerr << "Warning: upper left corner out of image boundaries, clipping to 0" << std::endl;
1045 // startCol=0;
1046 // }
1047 // else if(uli>=this->nrOfCol()){
1048 // std::cerr << "Warning: upper left corner out of image boundaries, clipping to " << this->nrOfCol()-1 << std::endl;
1049 // startCol=this->nrOfCol()-1;
1050 // }
1051 // if(lri<0){
1052 // std::cerr << "Warning: lower right corner out of image boundaries, clipping to " << 0 << std::endl;
1053 // endCol=0;
1054 // }
1055 // else if(lri>=this->nrOfCol()){
1056 // std::cerr << "Warning: lower right corner out of image boundaries, clipping to " << this->nrOfCol()-1 << std::endl;
1057 // endCol=this->nrOfCol()-1;
1058 // }
1059 // double startRow=ulj;
1060 // double endRow=lrj;
1061 // if(ulj<0){
1062 // std::cerr << "Warning: upper left corner out of image boundaries, clipping to 0" << std::endl;
1063 // startRow=0;
1064 // }
1065 // else if(ulj>=this->nrOfRow()){
1066 // std::cerr << "Warning: upper left corner out of image boundaries, clipping to " << this->nrOfRow()-1 << std::endl;
1067 // startRow=this->nrOfRow()-1;
1068 // }
1069 // if(lrj<0){
1070 // std::cerr << "Warning: lower right corner out of image boundaries, clipping to " << 0 << std::endl;
1071 // endRow=0;
1072 // }
1073 // else if(lrj>=this->nrOfRow()){
1074 // std::cerr << "Warning: lower right corner out of image boundaries, clipping to " << this->nrOfCol()-1 << std::endl;
1075 // endRow=this->nrOfRow()-1;
1076 // }
1077
1078 // vector<double> readBuffer;
1079 // double readValue=nodataValue;
1080 // unsigned int nband=this->nrOfBand();
1081 // const char* pszMessage;
1082 // void* pProgressArg=NULL;
1083 // GDALProgressFunc pfnProgress=GDALTermProgress;
1084 // double progress=0;
1085 // MyProgressFunc(progress,pszMessage,pProgressArg);
1086 // for(size_t iband=0;iband<nband;++iband){
1087 // if(verbose_opt[0]){
1088 // cout << "extracting band " << iband << endl;
1089 // MyProgressFunc(progress,pszMessage,pProgressArg);
1090 // }
1091 // for(int irow=0;irow<imgWriter.nrOfRow();++irow){
1092 // double readRow=ulj+irow;
1093 // if(readRow<0||readRow>=this->nrOfRow()){
1094 // if(verbose_opt[0])
1095 // std::cout << "Warning: readRow is " << readRow << std::endl;
1096 // for(int icol=0;icol<imgWriter.nrOfCol();++icol)
1097 // imgWriter.writeData(nodataValue,icol,irow,iband);
1098 // }
1099 // else{
1100 // for(int icol=0;icol<imgWriter.nrOfCol();++icol){
1101 // double readCol=uli+icol;
1102 // if(readCol<0||readCol>=this->nrOfCol()){
1103 // if(verbose_opt[0])
1104 // std::cout << "Warning: readCol is " << readCol << std::endl;
1105 // imgWriter.writeData(nodataValue,icol,irow,iband);
1106 // }
1107 // else{
1108 // this->readData(readValue,readCol,readRow,iband);
1109 // imgWriter.writeData(readValue,icol,irow,iband);
1110 // }
1111 // }
1112 // }
1113 // if(verbose_opt[0]){
1114 // progress=(1.0+irow);
1115 // progress/=imgWriter.nrOfRow();
1116 // MyProgressFunc(progress,pszMessage,pProgressArg);
1117 // }
1118 // else{
1119 // progress=(1.0+irow);
1120 // progress+=(imgWriter.nrOfRow()*iband);
1121 // progress/=imgWriter.nrOfBand()*imgWriter.nrOfRow();
1122 // assert(progress>=0);
1123 // assert(progress<=1);
1124 // MyProgressFunc(progress,pszMessage,pProgressArg);
1125 // }
1126 // }
1127 // }
1128 // return(CE_None);
1129 // }
1130 // catch(string predefinedString){
1131 // std::cout << predefinedString << std::endl;
1132 // throw;
1133 // }
1134 // }
1135
1136 // CPLErr Jim::crop(Jim& imgWriter, AppFactory& app){
1137 // Optionjl<string> projection_opt("a_srs", "a_srs", "Override the projection for the output file (leave blank to copy from input file, use epsg:3035 to use European projection and force to European grid");
1138 // //todo: support layer names
1139 // Optionjl<string> extent_opt("e", "extent", "get boundary from extent from polygons in vector file");
1140 // Optionjl<string> layer_opt("ln", "ln", "layer name of extent to crop");
1141 // Optionjl<bool> cut_to_cutline_opt("crop_to_cutline", "crop_to_cutline", "Crop the extent of the target dataset to the extent of the cutline, setting the outside area to nodata.",false);
1142 // Optionjl<bool> cut_in_cutline_opt("crop_in_cutline", "crop_in_cutline", "Crop the extent of the target dataset to the extent of the cutline, setting the inner area to nodata.",false);
1143 // 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");
1144 // Optionjl<string> mask_opt("m", "mask", "Use the the specified file as a validity mask (0 is nodata).");
1145 // Optionjl<double> msknodata_opt("msknodata", "msknodata", "Mask value not to consider for crop.", 0);
1146 // Optionjl<unsigned int> mskband_opt("mskband", "mskband", "Mask band to read (0 indexed)", 0);
1147 // Optionjl<double> ulx_opt("ulx", "ulx", "Upper left x value bounding box", 0.0);
1148 // Optionjl<double> uly_opt("uly", "uly", "Upper left y value bounding box", 0.0);
1149 // Optionjl<double> lrx_opt("lrx", "lrx", "Lower right x value bounding box", 0.0);
1150 // Optionjl<double> lry_opt("lry", "lry", "Lower right y value bounding box", 0.0);
1151 // Optionjl<double> dx_opt("dx", "dx", "Output resolution in x (in meter) (empty: keep original resolution)");
1152 // Optionjl<double> dy_opt("dy", "dy", "Output resolution in y (in meter) (empty: keep original resolution)");
1153 // Optionjl<double> cx_opt("x", "x", "x-coordinate of image center to crop (in meter)");
1154 // Optionjl<double> cy_opt("y", "y", "y-coordinate of image center to crop (in meter)");
1155 // Optionjl<double> nx_opt("nx", "nx", "image size in x to crop (in meter)");
1156 // Optionjl<double> ny_opt("ny", "ny", "image size in y to crop (in meter)");
1157 // Optionjl<unsigned int> ns_opt("ns", "ns", "number of samples to crop (in pixels)");
1158 // Optionjl<unsigned int> nl_opt("nl", "nl", "number of lines to crop (in pixels)");
1159 // Optionjl<unsigned int> band_opt("b", "band", "band index to crop (leave empty to retain all bands)");
1160 // Optionjl<unsigned int> bstart_opt("sband", "startband", "Start band sequence number");
1161 // Optionjl<unsigned int> bend_opt("eband", "endband", "End band sequence number");
1162 // Optionjl<double> autoscale_opt("as", "autoscale", "scale output to min and max, e.g., --autoscale 0 --autoscale 255");
1163 // Optionjl<double> scale_opt("scale", "scale", "output=scale*input+offset");
1164 // Optionjl<double> offset_opt("offset", "offset", "output=scale*input+offset");
1165 // 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");
1166 // // Optionjl<string> oformat_opt("of", "oformat", "Output image format (see also gdal_translate).","GTiff");
1167 // // Optionjl<string> option_opt("co", "co", "Creation option for output file. Multiple options can be specified.");
1168 // Optionjl<string> colorTable_opt("ct", "ct", "color table (file with 5 columns: id R G B ALFA (0: transparent, 255: solid)");
1169 // Optionjl<double> nodata_opt("nodata", "nodata", "Nodata value to put in image if out of bounds.");
1170 // Optionjl<string> resample_opt("r", "resampling-method", "Resampling method (near: nearest neighbor, bilinear: bi-linear interpolation).", "near");
1171 // Optionjl<string> description_opt("d", "description", "Set image description");
1172 // Optionjl<bool> align_opt("align", "align", "Align output bounding box to input image",false);
1173 // Optionjl<short> verbose_opt("v", "verbose", "verbose", 0,2);
1174
1175 // extent_opt.setHide(1);
1176 // layer_opt.setHide(1);
1177 // cut_to_cutline_opt.setHide(1);
1178 // cut_in_cutline_opt.setHide(1);
1179 // eoption_opt.setHide(1);
1180 // bstart_opt.setHide(1);
1181 // bend_opt.setHide(1);
1182 // mask_opt.setHide(1);
1183 // msknodata_opt.setHide(1);
1184 // mskband_opt.setHide(1);
1185 // // option_opt.setHide(1);
1186 // cx_opt.setHide(1);
1187 // cy_opt.setHide(1);
1188 // nx_opt.setHide(1);
1189 // ny_opt.setHide(1);
1190 // ns_opt.setHide(1);
1191 // nl_opt.setHide(1);
1192 // scale_opt.setHide(1);
1193 // offset_opt.setHide(1);
1194 // nodata_opt.setHide(1);
1195 // description_opt.setHide(1);
1196
1197 // bool doProcess;//stop process when program was invoked with help option (-h --help)
1198 // try{
1199 // doProcess=projection_opt.retrieveOption(app);
1200 // ulx_opt.retrieveOption(app);
1201 // uly_opt.retrieveOption(app);
1202 // lrx_opt.retrieveOption(app);
1203 // lry_opt.retrieveOption(app);
1204 // band_opt.retrieveOption(app);
1205 // bstart_opt.retrieveOption(app);
1206 // bend_opt.retrieveOption(app);
1207 // autoscale_opt.retrieveOption(app);
1208 // otype_opt.retrieveOption(app);
1209 // // oformat_opt.retrieveOption(app);
1210 // colorTable_opt.retrieveOption(app);
1211 // dx_opt.retrieveOption(app);
1212 // dy_opt.retrieveOption(app);
1213 // resample_opt.retrieveOption(app);
1214 // extent_opt.retrieveOption(app);
1215 // layer_opt.retrieveOption(app);
1216 // cut_to_cutline_opt.retrieveOption(app);
1217 // cut_in_cutline_opt.retrieveOption(app);
1218 // eoption_opt.retrieveOption(app);
1219 // mask_opt.retrieveOption(app);
1220 // msknodata_opt.retrieveOption(app);
1221 // mskband_opt.retrieveOption(app);
1222 // // option_opt.retrieveOption(app);
1223 // cx_opt.retrieveOption(app);
1224 // cy_opt.retrieveOption(app);
1225 // nx_opt.retrieveOption(app);
1226 // ny_opt.retrieveOption(app);
1227 // ns_opt.retrieveOption(app);
1228 // nl_opt.retrieveOption(app);
1229 // scale_opt.retrieveOption(app);
1230 // offset_opt.retrieveOption(app);
1231 // nodata_opt.retrieveOption(app);
1232 // description_opt.retrieveOption(app);
1233 // align_opt.retrieveOption(app);
1234 // verbose_opt.retrieveOption(app);
1235
1236 // if(!doProcess){
1237 // cout << endl;
1238 // std::ostringstream helpStream;
1239 // helpStream << "short option -h shows basic options only, use long option --help to show all options" << std::endl;
1240 // throw(helpStream.str());//help was invoked, stop processing
1241 // }
1242
1243 // std::vector<std::string> badKeys;
1244 // app.badKeys(badKeys);
1245 // if(badKeys.size()){
1246 // std::ostringstream errorStream;
1247 // if(badKeys.size()>1)
1248 // errorStream << "Error: unknown keys: ";
1249 // else
1250 // errorStream << "Error: unknown key: ";
1251 // for(int ikey=0;ikey<badKeys.size();++ikey){
1252 // errorStream << badKeys[ikey] << " ";
1253 // }
1254 // errorStream << std::endl;
1255 // throw(errorStream.str());
1256 // }
1257
1258 // double nodataValue=nodata_opt.size()? nodata_opt[0] : 0;
1259 // RESAMPLE theResample;
1260 // if(resample_opt[0]=="near"){
1261 // theResample=NEAR;
1262 // if(verbose_opt[0])
1263 // cout << "resampling: nearest neighbor" << endl;
1264 // }
1265 // else if(resample_opt[0]=="bilinear"){
1266 // theResample=BILINEAR;
1267 // if(verbose_opt[0])
1268 // cout << "resampling: bilinear interpolation" << endl;
1269 // }
1270 // else{
1271 // std::cout << "Error: resampling method " << resample_opt[0] << " not supported" << std::endl;
1272 // return(CE_Failure);
1273 // }
1274
1275 // // ImgReaderGdal imgReader;
1276 // // ImgWriterGdal imgWriter;
1277 // //open input images to extract number of bands and spatial resolution
1278 // int ncropband=0;//total number of bands to write
1279 // double dx=0;
1280 // double dy=0;
1281 // if(dx_opt.size())
1282 // dx=dx_opt[0];
1283 // if(dy_opt.size())
1284 // dy=dy_opt[0];
1285
1286 // try{
1287 // //convert start and end band options to vector of band indexes
1288 // if(bstart_opt.size()){
1289 // if(bend_opt.size()!=bstart_opt.size()){
1290 // string errorstring="Error: options for start and end band indexes must be provided as pairs, missing end band";
1291 // throw(errorstring);
1292 // }
1293 // band_opt.clear();
1294 // for(int ipair=0;ipair<bstart_opt.size();++ipair){
1295 // if(bend_opt[ipair]<=bstart_opt[ipair]){
1296 // string errorstring="Error: index for end band must be smaller then start band";
1297 // throw(errorstring);
1298 // }
1299 // for(unsigned int iband=bstart_opt[ipair];iband<=bend_opt[ipair];++iband)
1300 // band_opt.push_back(iband);
1301 // }
1302 // }
1303 // }
1304 // catch(string error){
1305 // cerr << error << std::endl;
1306 // throw;
1307 // }
1308
1309
1310 // bool isGeoRef=false;
1311 // string projectionString;
1312 // // for(int iimg=0;iimg<input_opt.size();++iimg){
1313
1314 // if(!isGeoRef)
1315 // isGeoRef=this->isGeoRef();
1316 // if(this->isGeoRef()&&projection_opt.empty())
1317 // projectionString=this->getProjection();
1318 // if(dx_opt.empty()){
1319 // dx=this->getDeltaX();
1320 // }
1321
1322 // if(dy_opt.empty()){
1323 // dy=this->getDeltaY();
1324 // }
1325 // if(band_opt.size())
1326 // ncropband+=band_opt.size();
1327 // else
1328 // ncropband+=this->nrOfBand();
1329
1330 // GDALDataType theType=getGDALDataType();
1331 // if(otype_opt.size()){
1332 // theType=string2GDAL(otype_opt[0]);
1333 // if(theType==GDT_Unknown)
1334 // std::cout << "Warning: unknown output pixel type: " << otype_opt[0] << ", using input type as default" << std::endl;
1335 // }
1336 // if(verbose_opt[0])
1337 // cout << "Output pixel type: " << GDALGetDataTypeName(theType) << endl;
1338
1339 // //bounding box of cropped image
1340 // double cropulx=ulx_opt[0];
1341 // double cropuly=uly_opt[0];
1342 // double croplrx=lrx_opt[0];
1343 // double croplry=lry_opt[0];
1344 // //get bounding box from extentReader if defined
1345 // VectorOgr extentReader;
1346
1347 // OGRSpatialReference gdsSpatialRef(getProjectionRef().c_str());
1348 // if(extent_opt.size()){
1349 // //image must be georeferenced
1350 // if(!this->isGeoRef()){
1351 // string errorstring="Warning: input image is not georeferenced using extent";
1352 // std::cerr << errorstring << std::endl;
1353 // throw(errorstring);
1354 // }
1355 // statfactory::StatFactory stat;
1356 // double e_ulx;
1357 // double e_uly;
1358 // double e_lrx;
1359 // double e_lry;
1360 // for(int iextent=0;iextent<extent_opt.size();++iextent){
1361 // extentReader.open(extent_opt[iextent],layer_opt,true);//noread=true
1362
1363 // OGRSpatialReference *vectorSpatialRef=extentReader.getLayer(0)->GetSpatialRef();
1364 // OGRCoordinateTransformation *vector2raster=0;
1365 // vector2raster = OGRCreateCoordinateTransformation(vectorSpatialRef, &gdsSpatialRef);
1366 // if(gdsSpatialRef.IsSame(vectorSpatialRef)){
1367 // vector2raster=0;
1368 // }
1369 // else{
1370 // if(!vector2raster){
1371 // std::ostringstream errorStream;
1372 // errorStream << "Error: cannot create OGRCoordinateTransformation vector to GDAL raster dataset" << std::endl;
1373 // throw(errorStream.str());
1374 // }
1375 // }
1376 // extentReader.getExtent(e_ulx,e_uly,e_lrx,e_lry,vector2raster);
1377 // ulx_opt.push_back(e_ulx);
1378 // uly_opt.push_back(e_uly);
1379 // lrx_opt.push_back(e_lrx);
1380 // lry_opt.push_back(e_lry);
1381 // extentReader.close();
1382 // }
1383 // e_ulx=stat.mymin(ulx_opt);
1384 // e_uly=stat.mymax(uly_opt);
1385 // e_lrx=stat.mymax(lrx_opt);
1386 // e_lry=stat.mymin(lry_opt);
1387 // ulx_opt.clear();
1388 // uly_opt.clear();
1389 // lrx_opt.clear();
1390 // lrx_opt.clear();
1391 // ulx_opt.push_back(e_ulx);
1392 // uly_opt.push_back(e_uly);
1393 // lrx_opt.push_back(e_lrx);
1394 // lry_opt.push_back(e_lry);
1395 // if(cut_to_cutline_opt.size()||cut_in_cutline_opt.size()||eoption_opt.size())
1396 // extentReader.open(extent_opt[0],layer_opt,true);
1397 // }
1398 // else if(cx_opt.size()&&cy_opt.size()&&nx_opt.size()&&ny_opt.size()){
1399 // ulx_opt[0]=cx_opt[0]-nx_opt[0]/2.0;
1400 // uly_opt[0]=(isGeoRef) ? cy_opt[0]+ny_opt[0]/2.0 : cy_opt[0]-ny_opt[0]/2.0;
1401 // lrx_opt[0]=cx_opt[0]+nx_opt[0]/2.0;
1402 // lry_opt[0]=(isGeoRef) ? cy_opt[0]-ny_opt[0]/2.0 : cy_opt[0]+ny_opt[0]/2.0;
1403 // }
1404 // else if(cx_opt.size()&&cy_opt.size()&&ns_opt.size()&&nl_opt.size()){
1405 // ulx_opt[0]=cx_opt[0]-ns_opt[0]*dx/2.0;
1406 // uly_opt[0]=(isGeoRef) ? cy_opt[0]+nl_opt[0]*dy/2.0 : cy_opt[0]-nl_opt[0]*dy/2.0;
1407 // lrx_opt[0]=cx_opt[0]+ns_opt[0]*dx/2.0;
1408 // lry_opt[0]=(isGeoRef) ? cy_opt[0]-nl_opt[0]*dy/2.0 : cy_opt[0]+nl_opt[0]*dy/2.0;
1409 // }
1410
1411 // if(verbose_opt[0])
1412 // cout << "--ulx=" << ulx_opt[0] << " --uly=" << uly_opt[0] << " --lrx=" << lrx_opt[0] << " --lry=" << lry_opt[0] << endl;
1413
1414 // int ncropcol=0;
1415 // int ncroprow=0;
1416
1417 // Jim maskReader;
1418 // //todo: support transform of extent with cutline
1419 // if(extent_opt.size()&&(cut_to_cutline_opt[0]||cut_in_cutline_opt[0]||eoption_opt.size())){
1420 // if(mask_opt.size()){
1421 // string errorString="Error: can only either mask or extent extent with cut_to_cutline / cut_in_cutline, not both";
1422 // throw(errorString);
1423 // }
1424 // try{
1425 // // ncropcol=abs(static_cast<unsigned int>(ceil((lrx_opt[0]-ulx_opt[0])/dx)));
1426 // // ncroprow=abs(static_cast<unsigned int>(ceil((uly_opt[0]-lry_opt[0])/dy)));
1427 // ncropcol=static_cast<unsigned int>(ceil((lrx_opt[0]-ulx_opt[0])/dx));
1428 // ncroprow=static_cast<unsigned int>(ceil((uly_opt[0]-lry_opt[0])/dy));
1429 // maskReader.open(ncropcol,ncroprow,1,GDT_Float64);
1430 // double gt[6];
1431 // gt[0]=ulx_opt[0];
1432 // gt[1]=dx;
1433 // gt[2]=0;
1434 // gt[3]=uly_opt[0];
1435 // gt[4]=0;
1436 // gt[5]=-dy;
1437 // maskReader.setGeoTransform(gt);
1438 // if(projection_opt.size())
1439 // maskReader.setProjectionProj4(projection_opt[0]);
1440 // else if(projectionString.size())
1441 // maskReader.setProjection(projectionString);
1442
1443 // // maskReader.rasterizeBuf(extentReader,msknodata_opt[0],eoption_opt,layer_opt);
1444 // maskReader.rasterizeBuf(extentReader,1,eoption_opt,layer_opt);
1445 // }
1446 // catch(string error){
1447 // cerr << error << std::endl;
1448 // throw;
1449 // }
1450 // }
1451 // else if(mask_opt.size()==1){
1452 // try{
1453 // //there is only a single mask
1454 // maskReader.open(mask_opt[0]);
1455 // if(mskband_opt[0]>=maskReader.nrOfBand()){
1456 // string errorString="Error: illegal mask band";
1457 // throw;
1458 // }
1459 // }
1460 // catch(string error){
1461 // cerr << error << std::endl;
1462 // throw;
1463 // }
1464 // }
1465
1466 // //determine number of output bands
1467 // int writeBand=0;//write band
1468
1469 // if(scale_opt.size()){
1470 // while(scale_opt.size()<band_opt.size())
1471 // scale_opt.push_back(scale_opt[0]);
1472 // }
1473 // if(offset_opt.size()){
1474 // while(offset_opt.size()<band_opt.size())
1475 // offset_opt.push_back(offset_opt[0]);
1476 // }
1477 // if(autoscale_opt.size()){
1478 // assert(autoscale_opt.size()%2==0);
1479 // }
1480
1481 // if(theType==GDT_Unknown){
1482 // theType=this->getGDALDataType();
1483 // if(verbose_opt[0])
1484 // cout << "Using data type from input image: " << GDALGetDataTypeName(theType) << endl;
1485 // }
1486 // // if(option_opt.findSubstring("INTERLEAVE=")==option_opt.end()){
1487 // // string theInterleave="INTERLEAVE=";
1488 // // theInterleave+=this->getInterleave();
1489 // // option_opt.push_back(theInterleave);
1490 // // }
1491 // // if(verbose_opt[0])
1492 // // cout << "size of " << input_opt[iimg] << ": " << ncol << " cols, "<< nrow << " rows" << endl;
1493 // double uli,ulj,lri,lrj;//image coordinates
1494 // bool forceEUgrid=false;
1495 // if(projection_opt.size())
1496 // forceEUgrid=(!(projection_opt[0].compare("EPSG:3035"))||!(projection_opt[0].compare("EPSG:3035"))||projection_opt[0].find("ETRS-LAEA")!=string::npos);
1497 // if(ulx_opt[0]>=lrx_opt[0]){//default bounding box: no cropping
1498 // uli=0;
1499 // lri=this->nrOfCol()-1;
1500 // ulj=0;
1501 // lrj=this->nrOfRow()-1;
1502 // ncropcol=this->nrOfCol();
1503 // ncroprow=this->nrOfRow();
1504 // this->getBoundingBox(cropulx,cropuly,croplrx,croplry);
1505 // double magicX=1,magicY=1;
1506 // // this->getMagicPixel(magicX,magicY);
1507 // if(forceEUgrid){
1508 // //force to LAEA grid
1509 // Egcs egcs;
1510 // egcs.setLevel(egcs.res2level(dx));
1511 // egcs.force2grid(cropulx,cropuly,croplrx,croplry);
1512 // this->geo2image(cropulx+(magicX-1.0)*this->getDeltaX(),cropuly-(magicY-1.0)*this->getDeltaY(),uli,ulj);
1513 // this->geo2image(croplrx+(magicX-2.0)*this->getDeltaX(),croplry-(magicY-2.0)*this->getDeltaY(),lri,lrj);
1514 // }
1515 // this->geo2image(cropulx+(magicX-1.0)*this->getDeltaX(),cropuly-(magicY-1.0)*this->getDeltaY(),uli,ulj);
1516 // this->geo2image(croplrx+(magicX-2.0)*this->getDeltaX(),croplry-(magicY-2.0)*this->getDeltaY(),lri,lrj);
1517 // // ncropcol=abs(static_cast<unsigned int>(ceil((croplrx-cropulx)/dx)));
1518 // // ncroprow=abs(static_cast<unsigned int>(ceil((cropuly-croplry)/dy)));
1519 // ncropcol=static_cast<unsigned int>(ceil((croplrx-cropulx)/dx));
1520 // ncroprow=static_cast<unsigned int>(ceil((cropuly-croplry)/dy));
1521 // std::cerr << "Warning: unexpected bounding box, using defaults "<< "--ulx=" << cropulx << " --uly=" << cropuly << " --lrx=" << croplrx << " --lry=" << croplry << std::endl;
1522 // }
1523 // else{
1524 // double magicX=1,magicY=1;
1525 // // this->getMagicPixel(magicX,magicY);
1526 // cropulx=ulx_opt[0];
1527 // cropuly=uly_opt[0];
1528 // croplrx=lrx_opt[0];
1529 // croplry=lry_opt[0];
1530 // if(forceEUgrid){
1531 // //force to LAEA grid
1532 // Egcs egcs;
1533 // egcs.setLevel(egcs.res2level(dx));
1534 // egcs.force2grid(cropulx,cropuly,croplrx,croplry);
1535 // }
1536 // else if(align_opt[0]){
1537 // if(cropulx>this->getUlx())
1538 // cropulx-=fmod(cropulx-this->getUlx(),dx);
1539 // else if(cropulx<this->getUlx())
1540 // cropulx+=fmod(this->getUlx()-cropulx,dx)-dx;
1541 // if(croplrx<this->getLrx())
1542 // croplrx+=fmod(this->getLrx()-croplrx,dx);
1543 // else if(croplrx>this->getLrx())
1544 // croplrx-=fmod(croplrx-this->getLrx(),dx)+dx;
1545 // if(croplry>this->getLry())
1546 // croplry-=fmod(croplry-this->getLry(),dy);
1547 // else if(croplry<this->getLry())
1548 // croplry+=fmod(this->getLry()-croplry,dy)-dy;
1549 // if(cropuly<this->getUly())
1550 // cropuly+=fmod(this->getUly()-cropuly,dy);
1551 // else if(cropuly>this->getUly())
1552 // cropuly-=fmod(cropuly-this->getUly(),dy)+dy;
1553 // }
1554 // this->geo2image(cropulx+(magicX-1.0)*this->getDeltaX(),cropuly-(magicY-1.0)*this->getDeltaY(),uli,ulj);
1555 // this->geo2image(croplrx+(magicX-2.0)*this->getDeltaX(),croplry-(magicY-2.0)*this->getDeltaY(),lri,lrj);
1556
1557 // ncropcol=static_cast<unsigned int>(ceil((croplrx-cropulx)/dx));
1558 // ncroprow=static_cast<unsigned int>(ceil((cropuly-croplry)/dy));
1559 // uli=floor(uli);
1560 // ulj=floor(ulj);
1561 // lri=floor(lri);
1562 // lrj=floor(lrj);
1563
1564 // if(cropulx<getUlx() || cropuly>getUly() || croplrx>getLrx() || croplry<getLry())
1565 // std::cerr << "Warning: requested bounding box not within original bounding box, using "<< "--ulx=" << cropulx << " --uly=" << cropuly << " --lrx=" << croplrx << " --lry=" << croplry << std::endl;
1566 // }
1567
1568 // // double deltaX=this->getDeltaX();
1569 // // double deltaY=this->getDeltaY();
1570 // if(!imgWriter.nrOfBand()){//not opened yet
1571 // if(verbose_opt[0]){
1572 // cout << "cropulx: " << cropulx << endl;
1573 // cout << "cropuly: " << cropuly << endl;
1574 // cout << "croplrx: " << croplrx << endl;
1575 // cout << "croplry: " << croplry << endl;
1576 // cout << "ncropcol: " << ncropcol << endl;
1577 // cout << "ncroprow: " << ncroprow << endl;
1578 // cout << "cropulx+ncropcol*dx: " << cropulx+ncropcol*dx << endl;
1579 // cout << "cropuly-ncroprow*dy: " << cropuly-ncroprow*dy << endl;
1580 // cout << "upper left column of input image: " << uli << endl;
1581 // cout << "upper left row of input image: " << ulj << endl;
1582 // cout << "lower right column of input image: " << lri << endl;
1583 // cout << "lower right row of input image: " << lrj << endl;
1584 // cout << "new number of cols: " << ncropcol << endl;
1585 // cout << "new number of rows: " << ncroprow << endl;
1586 // cout << "new number of bands: " << ncropband << endl;
1587 // }
1588 // // string imageType;//=this->getImageType();
1589 // // if(oformat_opt.size())//default
1590 // // imageType=oformat_opt[0];
1591 // try{
1592 // imgWriter.open(ncropcol,ncroprow,ncropband,theType);
1593 // imgWriter.setNoData(nodata_opt);
1594 // // if(nodata_opt.size()){
1595 // // imgWriter.setNoData(nodata_opt);
1596 // // }
1597 // }
1598 // catch(string errorstring){
1599 // cout << errorstring << endl;
1600 // throw;
1601 // }
1602 // if(description_opt.size())
1603 // imgWriter.setImageDescription(description_opt[0]);
1604 // double gt[6];
1605 // gt[0]=cropulx;
1606 // gt[1]=dx;
1607 // gt[2]=0;
1608 // gt[3]=cropuly;
1609 // gt[4]=0;
1610 // gt[5]=(this->isGeoRef())? -dy : dy;
1611 // imgWriter.setGeoTransform(gt);
1612 // if(projection_opt.size()){
1613 // if(verbose_opt[0])
1614 // cout << "projection: " << projection_opt[0] << endl;
1615 // imgWriter.setProjectionProj4(projection_opt[0]);
1616 // }
1617 // else
1618 // imgWriter.setProjection(this->getProjection());
1619 // if(imgWriter.getDataType()==GDT_Byte){
1620 // if(colorTable_opt.size()){
1621 // if(colorTable_opt[0]!="none")
1622 // imgWriter.setColorTable(colorTable_opt[0]);
1623 // }
1624 // else if (this->getColorTable()!=NULL)//copy colorTable from input image
1625 // imgWriter.setColorTable(this->getColorTable());
1626 // }
1627 // }
1628
1629 // double startCol=uli;
1630 // double endCol=lri;
1631 // if(uli<0)
1632 // startCol=0;
1633 // else if(uli>=this->nrOfCol())
1634 // startCol=this->nrOfCol()-1;
1635 // if(lri<0)
1636 // endCol=0;
1637 // else if(lri>=this->nrOfCol())
1638 // endCol=this->nrOfCol()-1;
1639 // double startRow=ulj;
1640 // double endRow=lrj;
1641 // if(ulj<0)
1642 // startRow=0;
1643 // else if(ulj>=this->nrOfRow())
1644 // startRow=this->nrOfRow()-1;
1645 // if(lrj<0)
1646 // endRow=0;
1647 // else if(lrj>=this->nrOfRow())
1648 // endRow=this->nrOfRow()-1;
1649
1650 // vector<double> readBuffer;
1651 // unsigned int nband=(band_opt.size())?band_opt.size() : this->nrOfBand();
1652 // const char* pszMessage;
1653 // void* pProgressArg=NULL;
1654 // GDALProgressFunc pfnProgress=GDALTermProgress;
1655 // double progress=0;
1656 // MyProgressFunc(progress,pszMessage,pProgressArg);
1657 // for(unsigned int iband=0;iband<nband;++iband){
1658 // unsigned int readBand=(band_opt.size()>iband)?band_opt[iband]:iband;
1659 // if(verbose_opt[0]){
1660 // cout << "extracting band " << readBand << endl;
1661 // MyProgressFunc(progress,pszMessage,pProgressArg);
1662 // }
1663 // double theMin=0;
1664 // double theMax=0;
1665 // if(autoscale_opt.size()){
1666 // try{
1667 // this->getMinMax(static_cast<unsigned int>(startCol),static_cast<unsigned int>(endCol),static_cast<unsigned int>(startRow),static_cast<unsigned int>(endRow),readBand,theMin,theMax);
1668 // }
1669 // catch(string errorString){
1670 // cout << errorString << endl;
1671 // }
1672 // if(verbose_opt[0])
1673 // cout << "minmax: " << theMin << ", " << theMax << endl;
1674 // double theScale=(autoscale_opt[1]-autoscale_opt[0])/(theMax-theMin);
1675 // double theOffset=autoscale_opt[0]-theScale*theMin;
1676 // this->setScale(theScale,readBand);
1677 // this->setOffset(theOffset,readBand);
1678 // }
1679 // else{
1680 // if(scale_opt.size()){
1681 // if(scale_opt.size()>iband)
1682 // this->setScale(scale_opt[iband],readBand);
1683 // else
1684 // this->setScale(scale_opt[0],readBand);
1685 // }
1686 // if(offset_opt.size()){
1687 // if(offset_opt.size()>iband)
1688 // this->setOffset(offset_opt[iband],readBand);
1689 // else
1690 // this->setOffset(offset_opt[0],readBand);
1691 // }
1692 // }
1693
1694 // double readRow=0;
1695 // double readCol=0;
1696 // double lowerCol=0;
1697 // double upperCol=0;
1698 // for(int irow=0;irow<imgWriter.nrOfRow();++irow){
1699 // vector<double> lineMask;
1700 // double x=0;
1701 // double y=0;
1702 // //convert irow to geo
1703 // imgWriter.image2geo(0,irow,x,y);
1704 // //lookup corresponding row for irow in this file
1705 // this->geo2image(x,y,readCol,readRow);
1706 // vector<double> writeBuffer;
1707 // if(readRow<0||readRow>=this->nrOfRow()){
1708 // for(int icol=0;icol<imgWriter.nrOfCol();++icol)
1709 // writeBuffer.push_back(nodataValue);
1710 // }
1711 // else{
1712 // try{
1713 // if(endCol<this->nrOfCol()-1){
1714 // this->readData(readBuffer,startCol,endCol+1,readRow,readBand,theResample);
1715 // }
1716 // else{
1717 // this->readData(readBuffer,startCol,endCol,readRow,readBand,theResample);
1718 // }
1719 // double oldRowMask=-1;//keep track of row mask to optimize number of line readings
1720 // for(int icol=0;icol<imgWriter.nrOfCol();++icol){
1721 // imgWriter.image2geo(icol,irow,x,y);
1722 // //lookup corresponding row for irow in this file
1723 // this->geo2image(x,y,readCol,readRow);
1724 // if(readCol<0||readCol>=this->nrOfCol()){
1725 // writeBuffer.push_back(nodataValue);
1726 // }
1727 // else{
1728 // bool valid=true;
1729 // double geox=0;
1730 // double geoy=0;
1731 // if(maskReader.isInit()){
1732 // //read mask
1733 // double colMask=0;
1734 // double rowMask=0;
1735
1736 // imgWriter.image2geo(icol,irow,geox,geoy);
1737 // maskReader.geo2image(geox,geoy,colMask,rowMask);
1738 // colMask=static_cast<unsigned int>(colMask);
1739 // rowMask=static_cast<unsigned int>(rowMask);
1740 // if(rowMask>=0&&rowMask<maskReader.nrOfRow()&&colMask>=0&&colMask<maskReader.nrOfCol()){
1741 // if(static_cast<unsigned int>(rowMask)!=static_cast<unsigned int>(oldRowMask)){
1742
1743 // try{
1744 // maskReader.readData(lineMask,static_cast<unsigned int>(rowMask),mskband_opt[0]);
1745 // }
1746 // catch(string errorstring){
1747 // cerr << errorstring << endl;
1748 // throw;
1749 // }
1750 // catch(...){
1751 // cerr << "error caught" << std::endl;
1752 // throw;
1753 // }
1754 // oldRowMask=rowMask;
1755 // }
1756 // if(cut_to_cutline_opt[0]){
1757 // if(lineMask[colMask]!=1){
1758 // nodataValue=nodata_opt[0];
1759 // valid=false;
1760 // }
1761 // }
1762 // else if(cut_in_cutline_opt[0]){
1763 // if(lineMask[colMask]==1){
1764 // nodataValue=nodata_opt[0];
1765 // valid=false;
1766 // }
1767 // }
1768 // else{
1769 // for(int ivalue=0;ivalue<msknodata_opt.size();++ivalue){
1770 // if(lineMask[colMask]==msknodata_opt[ivalue]){
1771 // if(nodata_opt.size()>ivalue)
1772 // nodataValue=nodata_opt[ivalue];
1773 // valid=false;
1774 // break;
1775 // }
1776 // }
1777 // }
1778 // }
1779 // }
1780 // if(!valid)
1781 // writeBuffer.push_back(nodataValue);
1782 // else{
1783 // switch(theResample){
1784 // case(BILINEAR):
1785 // lowerCol=readCol-0.5;
1786 // lowerCol=static_cast<unsigned int>(lowerCol);
1787 // upperCol=readCol+0.5;
1788 // upperCol=static_cast<unsigned int>(upperCol);
1789 // if(lowerCol<0)
1790 // lowerCol=0;
1791 // if(upperCol>=this->nrOfCol())
1792 // upperCol=this->nrOfCol()-1;
1793 // writeBuffer.push_back((readCol-0.5-lowerCol)*readBuffer[upperCol-startCol]+(1-readCol+0.5+lowerCol)*readBuffer[lowerCol-startCol]);
1794 // break;
1795 // default:
1796 // readCol=static_cast<unsigned int>(readCol);
1797 // readCol-=startCol;//we only start reading from startCol
1798 // writeBuffer.push_back(readBuffer[readCol]);
1799 // break;
1800 // }
1801 // }
1802 // }
1803 // }
1804 // }
1805 // catch(string errorstring){
1806 // cout << errorstring << endl;
1807 // throw;
1808 // }
1809 // }
1810 // if(writeBuffer.size()!=imgWriter.nrOfCol())
1811 // cout << "writeBuffer.size()=" << writeBuffer.size() << ", imgWriter.nrOfCol()=" << imgWriter.nrOfCol() << endl;
1812
1813 // assert(writeBuffer.size()==imgWriter.nrOfCol());
1814 // try{
1815 // imgWriter.writeData(writeBuffer,irow,writeBand);
1816 // }
1817 // catch(string errorstring){
1818 // cout << errorstring << endl;
1819 // throw;
1820 // }
1821 // if(verbose_opt[0]){
1822 // progress=(1.0+irow);
1823 // progress/=imgWriter.nrOfRow();
1824 // MyProgressFunc(progress,pszMessage,pProgressArg);
1825 // }
1826 // else{
1827 // progress=(1.0+irow);
1828 // progress+=(imgWriter.nrOfRow()*writeBand);
1829 // progress/=imgWriter.nrOfBand()*imgWriter.nrOfRow();
1830 // assert(progress>=0);
1831 // assert(progress<=1);
1832 // MyProgressFunc(progress,pszMessage,pProgressArg);
1833 // }
1834 // }
1835 // ++writeBand;
1836 // }
1837 // if(extent_opt.size()&&(cut_to_cutline_opt[0]||cut_in_cutline_opt[0]||eoption_opt.size())){
1838 // extentReader.close();
1839 // }
1840 // if(maskReader.isInit())
1841 // maskReader.close();
1842 // return(CE_None);
1843 // }
1844 // catch(string predefinedString){
1845 // std::cout << predefinedString << std::endl;
1846 // throw;
1847 // }
1848 // }
1849
1850 void Jim::cropBand(Jim& imgWriter, AppFactory& app){
1851 Optionjl<unsigned int> band_opt("b", "band", "band index to crop (leave empty to retain all bands)");
1852 Optionjl<unsigned int> bstart_opt("sband", "startband", "Start band sequence number");
1853 Optionjl<unsigned int> bend_opt("eband", "endband", "End band sequence number");
1854 Optionjl<short> verbose_opt("v", "verbose", "verbose", 0,2);
1855
1856 bool doProcess;//stop process when program was invoked with help option (-h --help)
1857 try{
1858 doProcess=band_opt.retrieveOption(app);
1859 bstart_opt.retrieveOption(app);
1860 bend_opt.retrieveOption(app);
1861 verbose_opt.retrieveOption(app);
1862
1863 if(!doProcess){
1864 cout << endl;
1865 std::ostringstream helpStream;
1866 helpStream << "short option -h shows basic options only, use long option --help to show all options" << std::endl;
1867 throw(helpStream.str());//help was invoked, stop processing
1868 }
1869
1870 std::vector<std::string> badKeys;
1871 app.badKeys(badKeys);
1872 if(badKeys.size()){
1873 std::ostringstream errorStream;
1874 if(badKeys.size()>1)
1875 errorStream << "Error: unknown keys: ";
1876 else
1877 errorStream << "Error: unknown key: ";
1878 for(int ikey=0;ikey<badKeys.size();++ikey){
1879 errorStream << badKeys[ikey] << " ";
1880 }
1881 errorStream << std::endl;
1882 throw(errorStream.str());
1883 }
1884 }
1885 catch(string predefinedString){
1886 std::cerr << predefinedString << std::endl;
1887 throw;
1888 }
1889 std::vector<unsigned int> vband=band_opt;
1890 if(bstart_opt.size()!=bend_opt.size()){
1891 std::cerr << "Error: size of start band is not equal to size of end band" << std::endl;
1892 throw;
1893 }
1894 for(size_t ipair=0;ipair<bstart_opt.size();++ipair){
1895 if(bend_opt[ipair]<bstart_opt[ipair]){
1896 string errorstring="Error: index for start band must be smaller then end band";
1897 throw(errorstring);
1898 }
1899 for(size_t iband=bstart_opt[ipair];iband<=bend_opt[ipair];++iband)
1900 vband.push_back(iband);
1901 }
1902 if(vband.empty()){
1903 for(size_t iband=0;iband<nrOfBand();++iband)
1904 vband.push_back(iband);
1905 }
1906 if(vband.empty()){
1907 std::cerr << "Error: no bands selected" << std::endl;
1908 throw;
1909 }
1910 for(size_t iband=0;iband<vband.size();++iband){
1911 if(vband[iband]>=nrOfBand()){
1912 std::ostringstream errorStream;
1913 errorStream << "Error: selected band " << vband[iband] << " is out of range";
1914 std::cerr << errorStream.str() << std::endl;
1915 throw(errorStream.str());
1916 }
1917 }
1918 imgWriter.open(nrOfCol(),nrOfRow(),vband.size(),nrOfPlane(),getGDALDataType());
1919 imgWriter.copyGeoTransform(*this);
1920 imgWriter.setProjection(this->getProjection());
1921 for(size_t iband=0;iband<vband.size();++iband){
1922 copyData(imgWriter.getDataPointer(iband),vband[iband]);
1923 }
1924 }
1925
1926 ///destructive version of cropBand
1927 void Jim::d_cropBand(AppFactory& app){
1928 Optionjl<unsigned int> band_opt("b", "band", "band index to crop (leave empty to retain all bands)");
1929 Optionjl<unsigned int> bstart_opt("sband", "startband", "Start band sequence number");
1930 Optionjl<unsigned int> bend_opt("eband", "endband", "End band sequence number");
1931 Optionjl<short> verbose_opt("v", "verbose", "verbose", 0,2);
1932
1933 bool doProcess;//stop process when program was invoked with help option (-h --help)
1934 try{
1935 doProcess=band_opt.retrieveOption(app);
1936 bstart_opt.retrieveOption(app);
1937 bend_opt.retrieveOption(app);
1938 verbose_opt.retrieveOption(app);
1939
1940 if(!doProcess){
1941 cout << endl;
1942 std::ostringstream helpStream;
1943 helpStream << "short option -h shows basic options only, use long option --help to show all options" << std::endl;
1944 throw(helpStream.str());//help was invoked, stop processing
1945 }
1946
1947 std::vector<std::string> badKeys;
1948 app.badKeys(badKeys);
1949 if(badKeys.size()){
1950 std::ostringstream errorStream;
1951 if(badKeys.size()>1)
1952 errorStream << "Error: unknown keys: ";
1953 else
1954 errorStream << "Error: unknown key: ";
1955 for(int ikey=0;ikey<badKeys.size();++ikey){
1956 errorStream << badKeys[ikey] << " ";
1957 }
1958 errorStream << std::endl;
1959 throw(errorStream.str());
1960 }
1961 }
1962 catch(string predefinedString){
1963 std::cerr << predefinedString << std::endl;
1964 throw;
1965 }
1966 std::vector<unsigned int> vband=band_opt;
1967 if(bstart_opt.size()!=bend_opt.size()){
1968 std::cerr << "Error: size of start band is not equal to size of end band" << std::endl;
1969 throw;
1970 }
1971 for(size_t ipair=0;ipair<bstart_opt.size();++ipair){
1972 if(bend_opt[ipair]<bstart_opt[ipair]){
1973 string errorstring="Error: index for start band must be smaller then end band";
1974 throw(errorstring);
1975 }
1976 for(size_t iband=bstart_opt[ipair];iband<=bend_opt[ipair];++iband)
1977 vband.push_back(iband);
1978 }
1979 if(vband.empty()){
1980 for(size_t iband=0;iband<nrOfBand();++iband)
1981 vband.push_back(iband);
1982 }
1983 if(vband.empty()){
1984 std::cerr << "Error: no bands selected" << std::endl;
1985 throw;
1986 }
1987 for(size_t iband=0;iband<vband.size();++iband){
1988 if(vband[iband]>=nrOfBand()){
1989 std::ostringstream errorStream;
1990 errorStream << "Error: selected band " << vband[iband] << " is out of range";
1991 std::cerr << errorStream.str() << std::endl;
1992 throw(errorStream.str());
1993 }
1994 }
1995 //re-order bands
1996 std::vector<size_t> allbands(vband.begin(),vband.end());
1997 for(int iband=0;iband<nrOfBand();++iband){
1998 if(find(allbands.begin(),allbands.end(),iband)==allbands.end()){
1999 allbands.push_back(iband);
2000 }
2001 }
2002 // for all elements to put in place
2003 for( size_t i = 0; i < m_data.size(); ++i ){
2004 // while vOrder[i] is not yet in place
2005 // every swap places at least one element in it's proper place
2006 while( allbands[i] != allbands[allbands[i]] ){
2007 swap( m_data[allbands[i]], m_data[allbands[allbands[i]]] );
2008 swap( allbands[i], allbands[allbands[i]] );
2009 }
2010 }
2011 for( size_t i = 0; i < m_begin.size(); ++i ){
2012 // while vOrder[i] is not yet in place
2013 // every swap places at least one element in it's proper place
2014 while( allbands[i] != allbands[allbands[i]] ){
2015 swap( m_begin[allbands[i]], m_begin[allbands[allbands[i]]] );
2016 swap( allbands[i], allbands[allbands[i]] );
2017 }
2018 }
2019 for( size_t i = 0; i < m_end.size(); ++i ){
2020 // while vOrder[i] is not yet in place
2021 // every swap places at least one element in it's proper place
2022 while( allbands[i] != allbands[allbands[i]] ){
2023 swap( m_end[allbands[i]], m_end[allbands[allbands[i]]] );
2024 swap( allbands[i], allbands[allbands[i]] );
2025 }
2026 }
2027 for( size_t i = 0; i < m_scale.size(); ++i ){
2028 // while vOrder[i] is not yet in place
2029 // every swap places at least one element in it's proper place
2030 while( allbands[i] != allbands[allbands[i]] ){
2031 swap( m_scale[allbands[i]], m_scale[allbands[allbands[i]]] );
2032 swap( allbands[i], allbands[allbands[i]] );
2033 }
2034 }
2035 for( size_t i = 0; i < m_offset.size(); ++i ){
2036 // while vOrder[i] is not yet in place
2037 // every swap places at least one element in it's proper place
2038 while( allbands[i] != allbands[allbands[i]] ){
2039 swap( m_offset[allbands[i]], m_offset[allbands[allbands[i]]] );
2040 swap( allbands[i], allbands[allbands[i]] );
2041 }
2042 }
2043 while(m_begin.size()>vband.size())
2044 m_begin.pop_back();
2045 while(m_end.size()>vband.size())
2046 m_end.pop_back();
2047 while(m_scale.size()>vband.size())
2048 m_scale.pop_back();
2049 while(m_offset.size()>vband.size())
2050 m_offset.pop_back();
2051 while(m_scale.size()>vband.size())
2052 m_scale.pop_back();
2053 while(m_data.size()>vband.size()){
2054 free(m_data.back());
2055 m_data.pop_back();
2056 }
2057 m_nband=m_data.size();
2058 }
2059
2060 void Jim::cropPlane(Jim& imgWriter, AppFactory& app){
2061 Optionjl<unsigned int> plane_opt("p", "plane", "plane index to crop (leave empty to retain all planes)");
2062 Optionjl<unsigned int> bstart_opt("splane", "startplane", "Start plane sequence number");
2063 Optionjl<unsigned int> bend_opt("eplane", "endplane", "End plane sequence number");
2064 Optionjl<short> verbose_opt("v", "verbose", "verbose", 0,2);
2065
2066 bool doProcess;//stop process when program was invoked with help option (-h --help)
2067 try{
2068 doProcess=plane_opt.retrieveOption(app);
2069 bstart_opt.retrieveOption(app);
2070 bend_opt.retrieveOption(app);
2071 verbose_opt.retrieveOption(app);
2072
2073 if(!doProcess){
2074 cout << endl;
2075 std::ostringstream helpStream;
2076 helpStream << "short option -h shows basic options only, use long option --help to show all options" << std::endl;
2077 throw(helpStream.str());//help was invoked, stop processing
2078 }
2079
2080 std::vector<std::string> badKeys;
2081 app.badKeys(badKeys);
2082 if(badKeys.size()){
2083 std::ostringstream errorStream;
2084 if(badKeys.size()>1)
2085 errorStream << "Error: unknown keys: ";
2086 else
2087 errorStream << "Error: unknown key: ";
2088 for(int ikey=0;ikey<badKeys.size();++ikey){
2089 errorStream << badKeys[ikey] << " ";
2090 }
2091 errorStream << std::endl;
2092 throw(errorStream.str());
2093 }
2094 }
2095 catch(string predefinedString){
2096 std::cerr << predefinedString << std::endl;
2097 throw;
2098 }
2099 std::vector<unsigned int> vplane=plane_opt;
2100 if(bstart_opt.size()!=bend_opt.size()){
2101 std::cerr << "Error: size of start plane is not equal to size of end plane" << std::endl;
2102 throw;
2103 }
2104 for(size_t ipair=0;ipair<bstart_opt.size();++ipair){
2105 if(bend_opt[ipair]<bstart_opt[ipair]){
2106 string errorstring="Error: index for start plane must be smaller then end plane";
2107 throw(errorstring);
2108 }
2109 for(size_t iplane=bstart_opt[ipair];iplane<=bend_opt[ipair];++iplane)
2110 vplane.push_back(iplane);
2111 }
2112 if(vplane.empty()){
2113 for(size_t iplane=0;iplane<nrOfPlane();++iplane)
2114 vplane.push_back(iplane);
2115 }
2116 if(vplane.empty()){
2117 std::cerr << "Error: no planes selected" << std::endl;
2118 throw;
2119 }
2120 for(size_t iplane=0;iplane<vplane.size();++iplane){
2121 if(vplane[iplane]>=nrOfPlane()){
2122 std::ostringstream errorStream;
2123 errorStream << "Error: selected plane " << vplane[iplane] << " is out of range";
2124 std::cerr << errorStream.str() << std::endl;
2125 throw(errorStream.str());
2126 }
2127 if(vplane[iplane]<0){
2128 std::ostringstream errorStream;
2129 errorStream << "Error: selected plane " << vplane[iplane] << " is out of range";
2130 std::cerr << errorStream.str() << std::endl;
2131 throw(errorStream.str());
2132 }
2133 }
2134 // m_data[nrOfBand()]=(void *) calloc(static_cast<size_t>(nrOfCol()*nrOfRow()*vplane.size()),getDataTypeSizeBytes());
2135 // for(size_t iband=0;iband<nrOfBand();++iband){
2136 // for(size_t iplane=0;iplane<vplane.size();++iplane){
2137 // memcpy(m_data[nrOfBand()]+getDataTypeSizeBytes()*nrOfCol()*nrOfRow()*iplane,m_data[iband]+getDataTypeSizeBytes()*nrOfCol()*nrOfRow()*vplane[iplane],getDataTypeSizeBytes()*nrOfCol()*nrOfRow());
2138 // }
2139 // memcpy(m_data[iband],m_data[nrOfBand()],getDataTypeSizeBytes()*nrOfCol()*nrOfRow()*vplane.size());
2140 // }
2141
2142 imgWriter.open(nrOfCol(),nrOfRow(),nrOfBand(),vplane.size(),getGDALDataType());
2143 imgWriter.copyGeoTransform(*this);
2144 imgWriter.setProjection(this->getProjection());
2145 for(size_t iband=0;iband<nrOfBand();++iband){
2146 for(size_t iplane=0;iplane<vplane.size();++iplane){
2147 memcpy((uint_least8_t*)(imgWriter.getDataPointer(iband))+getDataTypeSizeBytes()*nrOfCol()*nrOfRow()*iplane,(uint_least8_t*)(m_data[iband])+getDataTypeSizeBytes()*nrOfCol()*nrOfRow()*vplane[iplane],getDataTypeSizeBytes()*nrOfCol()*nrOfRow());
2148 }
2149 }
2150 }
2151
2152 ///destructive version of cropPlane
2153 void Jim::d_cropPlane(AppFactory& app){
2154 Optionjl<unsigned int> plane_opt("p", "plane", "plane index to crop (leave empty to retain all planes)");
2155 Optionjl<unsigned int> bstart_opt("splane", "startplane", "Start plane sequence number");
2156 Optionjl<unsigned int> bend_opt("eplane", "endplane", "End plane sequence number");
2157 Optionjl<short> verbose_opt("v", "verbose", "verbose", 0,2);
2158
2159 bool doProcess;//stop process when program was invoked with help option (-h --help)
2160 try{
2161 doProcess=plane_opt.retrieveOption(app);
2162 bstart_opt.retrieveOption(app);
2163 bend_opt.retrieveOption(app);
2164 verbose_opt.retrieveOption(app);
2165
2166 if(!doProcess){
2167 cout << endl;
2168 std::ostringstream helpStream;
2169 helpStream << "short option -h shows basic options only, use long option --help to show all options" << std::endl;
2170 throw(helpStream.str());//help was invoked, stop processing
2171 }
2172
2173 std::vector<std::string> badKeys;
2174 app.badKeys(badKeys);
2175 if(badKeys.size()){
2176 std::ostringstream errorStream;
2177 if(badKeys.size()>1)
2178 errorStream << "Error: unknown keys: ";
2179 else
2180 errorStream << "Error: unknown key: ";
2181 for(int ikey=0;ikey<badKeys.size();++ikey){
2182 errorStream << badKeys[ikey] << " ";
2183 }
2184 errorStream << std::endl;
2185 throw(errorStream.str());
2186 }
2187 }
2188 catch(string predefinedString){
2189 std::cerr << predefinedString << std::endl;
2190 throw;
2191 }
2192 std::vector<unsigned int> vplane=plane_opt;
2193 if(bstart_opt.size()!=bend_opt.size()){
2194 std::cerr << "Error: size of start plane is not equal to size of end plane" << std::endl;
2195 throw;
2196 }
2197 for(size_t ipair=0;ipair<bstart_opt.size();++ipair){
2198 if(bend_opt[ipair]<bstart_opt[ipair]){
2199 string errorstring="Error: index for start plane must be smaller then end plane";
2200 throw(errorstring);
2201 }
2202 for(size_t iplane=bstart_opt[ipair];iplane<=bend_opt[ipair];++iplane)
2203 vplane.push_back(iplane);
2204 }
2205 if(vplane.empty()){
2206 for(size_t iplane=0;iplane<nrOfPlane();++iplane)
2207 vplane.push_back(iplane);
2208 }
2209 if(vplane.empty()){
2210 std::cerr << "Error: no planes selected" << std::endl;
2211 throw;
2212 }
2213 for(size_t iplane=0;iplane<vplane.size();++iplane){
2214 if(vplane[iplane]>=nrOfPlane()||vplane[iplane]<0){
2215 std::ostringstream errorStream;
2216 errorStream << "Error: selected plane " << vplane[iplane] << " is out of range";
2217 std::cerr << errorStream.str() << std::endl;
2218 throw(errorStream.str());
2219 }
2220 }
2221 if(nrOfPlane() > 1){
2222 void* newpointer=(void *) calloc(static_cast<size_t>(nrOfCol())*nrOfRow()*vplane.size(),getDataTypeSizeBytes());
2223 for(size_t iband=0;iband<nrOfBand();++iband){
2224 for(size_t iplane=0;iplane<vplane.size();++iplane){
2225 memcpy((uint_least8_t*)(newpointer)+static_cast<size_t>(getDataTypeSizeBytes())*nrOfCol()*nrOfRow()*iplane,(uint_least8_t*)(m_data[iband])+static_cast<size_t>(getDataTypeSizeBytes())*nrOfCol()*nrOfRow()*vplane[iplane],static_cast<size_t>(getDataTypeSizeBytes())*nrOfCol()*nrOfRow());
2226 }
2227 //free m_data[iband] and re-allocate to avoid memory leak
2228 free(m_data[iband]);
2229 m_data[iband]=(void *) calloc(static_cast<size_t>(nrOfCol()*nrOfRow())*vplane.size(),getDataTypeSizeBytes());
2230 memcpy((uint_least8_t*)(m_data[iband]),(uint_least8_t*)(newpointer),static_cast<size_t>(getDataTypeSizeBytes())*nrOfCol()*nrOfRow()*vplane.size());
2231 }
2232 free(newpointer);
2233 m_nplane=vplane.size();
2234 }
2235 }
2236
2237 void Jim::cropOgr(VectorOgr& sampleReader, Jim& imgWriter, AppFactory& app){
2238 Optionjl<string> projection_opt("a_srs", "a_srs", "Override the projection for the output file (leave blank to copy from input file, use epsg:3035 to use European projection and force to European grid");
2239 //todo: support layer names
2240 Optionjl<string> layer_opt("ln", "ln", "layer name of extent to crop");
2241 Optionjl<bool> cut_to_cutline_opt(
2242 "cut_to_cutline", "crop_to_cutline", "Crop the extent of the target dataset to the extent of the cutline, setting the outside area to nodata.",false);
2243 Optionjl<bool> cut_in_cutline_opt("cut_in_cutline", "crop_in_cutline", "Crop the extent of the target dataset to the extent of the cutline, setting the inner area to nodata.",false);
2244 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");
2245 Optionjl<double> msknodata_opt("msknodata", "msknodata", "Mask value not to consider for crop.", 0);
2246 Optionjl<double> ulx_opt("ulx", "ulx", "Upper left x value bounding box", 0.0);
2247 Optionjl<double> uly_opt("uly", "uly", "Upper left y value bounding box", 0.0);
2248 Optionjl<double> lrx_opt("lrx", "lrx", "Lower right x value bounding box", 0.0);
2249 Optionjl<double> lry_opt("lry", "lry", "Lower right y value bounding box", 0.0);
2250 Optionjl<double> dx_opt("dx", "dx", "Output resolution in x (in meter) (empty: keep original resolution)");
2251 Optionjl<double> dy_opt("dy", "dy", "Output resolution in y (in meter) (empty: keep original resolution)");
2252 Optionjl<unsigned int> band_opt("b", "band", "band index to crop (leave empty to retain all bands)");
2253 Optionjl<unsigned int> bstart_opt("sband", "startband", "Start band sequence number");
2254 Optionjl<unsigned int> bend_opt("eband", "endband", "End band sequence number");
2255 Optionjl<double> autoscale_opt("as", "autoscale", "scale output to min and max, e.g., --autoscale 0 --autoscale 255");
2256 Optionjl<double> scale_opt("scale", "scale", "output=scale*input+offset");
2257 Optionjl<double> offset_opt("offset", "offset", "output=scale*input+offset");
2258 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");
2259 Optionjl<string> colorTable_opt("ct", "ct", "color table (file with 5 columns: id R G B ALFA (0: transparent, 255: solid)");
2260 Optionjl<double> nodata_opt("nodata", "nodata", "Nodata value to put in image if out of bounds.");
2261 Optionjl<string> resample_opt("r", "resampling-method", "Resampling method (near: nearest neighbor, bilinear: bi-linear interpolation).", "near");
2262 Optionjl<string> description_opt("d", "description", "Set image description");
2263 Optionjl<bool> align_opt("align", "align", "Align output bounding box to input image",false);
2264 Optionjl<short> verbose_opt("v", "verbose", "verbose", 0,2);
2265
2266 layer_opt.setHide(1);
2267 cut_to_cutline_opt.setHide(1);
2268 cut_in_cutline_opt.setHide(1);
2269 eoption_opt.setHide(1);
2270 msknodata_opt.setHide(1);
2271 bstart_opt.setHide(1);
2272 bend_opt.setHide(1);
2273 scale_opt.setHide(1);
2274 offset_opt.setHide(1);
2275 nodata_opt.setHide(1);
2276 description_opt.setHide(1);
2277
2278 bool doProcess;//stop process when program was invoked with help option (-h --help)
2279 try{
2280 doProcess=projection_opt.retrieveOption(app);
2281 ulx_opt.retrieveOption(app);
2282 uly_opt.retrieveOption(app);
2283 lrx_opt.retrieveOption(app);
2284 lry_opt.retrieveOption(app);
2285 band_opt.retrieveOption(app);
2286 bstart_opt.retrieveOption(app);
2287 bend_opt.retrieveOption(app);
2288 autoscale_opt.retrieveOption(app);
2289 otype_opt.retrieveOption(app);
2290 colorTable_opt.retrieveOption(app);
2291 dx_opt.retrieveOption(app);
2292 dy_opt.retrieveOption(app);
2293 resample_opt.retrieveOption(app);
2294 layer_opt.retrieveOption(app);
2295 cut_to_cutline_opt.retrieveOption(app);
2296 cut_in_cutline_opt.retrieveOption(app);
2297 eoption_opt.retrieveOption(app);
2298 msknodata_opt.retrieveOption(app);
2299 scale_opt.retrieveOption(app);
2300 offset_opt.retrieveOption(app);
2301 nodata_opt.retrieveOption(app);
2302 description_opt.retrieveOption(app);
2303 align_opt.retrieveOption(app);
2304 verbose_opt.retrieveOption(app);
2305
2306 if(!doProcess){
2307 cout << endl;
2308 std::ostringstream helpStream;
2309 helpStream << "short option -h shows basic options only, use long option --help to show all options" << std::endl;
2310 throw(helpStream.str());//help was invoked, stop processing
2311 }
2312
2313 std::vector<std::string> badKeys;
2314 app.badKeys(badKeys);
2315 if(badKeys.size()){
2316 std::ostringstream errorStream;
2317 if(badKeys.size()>1)
2318 errorStream << "Error: unknown keys: ";
2319 else
2320 errorStream << "Error: unknown key: ";
2321 for(int ikey=0;ikey<badKeys.size();++ikey){
2322 errorStream << badKeys[ikey] << " ";
2323 }
2324 errorStream << std::endl;
2325 throw(errorStream.str());
2326 }
2327
2328 double nodataValue=nodata_opt.size()? nodata_opt[0] : 0;
2329 RESAMPLE theResample;
2330 if(resample_opt[0]=="near"){
2331 theResample=NEAR;
2332 if(verbose_opt[0]>1)
2333 cout << "resampling: nearest neighbor" << endl;
2334 }
2335 else if(resample_opt[0]=="bilinear"){
2336 theResample=BILINEAR;
2337 if(verbose_opt[0]>1)
2338 cout << "resampling: bilinear interpolation" << endl;
2339 }
2340 else{
2341 std::ostringstream errorStream;
2342 errorStream << "Error: resampling method " << resample_opt[0] << " not supported";
2343 throw(errorStream.str());
2344 }
2345
2346 const char* pszMessage;
2347 void* pProgressArg=NULL;
2348 GDALProgressFunc pfnProgress=GDALTermProgress;
2349 double progress=0;
2350 if(verbose_opt[0])
2351 MyProgressFunc(progress,pszMessage,pProgressArg);
2352 // ImgReaderGdal imgReader;
2353 // ImgWriterGdal imgWriter;
2354 //open input images to extract number of bands and spatial resolution
2355 int ncropband=0;//total number of bands to write
2356 double dx=0;
2357 double dy=0;
2358 if(dx_opt.size())
2359 dx=dx_opt[0];
2360 if(dy_opt.size())
2361 dy=dy_opt[0];
2362
2363 std::vector<unsigned int> vband=band_opt;
2364 try{
2365 //convert start and end band options to vector of band indexes
2366 if(bstart_opt.size()){
2367 if(bend_opt.size()!=bstart_opt.size()){
2368 string errorstring="Error: options for start and end band indexes must be provided as pairs, missing end band";
2369 throw(errorstring);
2370 }
2371 vband.clear();
2372 for(int ipair=0;ipair<bstart_opt.size();++ipair){
2373 if(bend_opt[ipair]<bstart_opt[ipair]){
2374 string errorstring="Error: index for start band must be smaller then end band";
2375 throw(errorstring);
2376 }
2377 for(unsigned int iband=bstart_opt[ipair];iband<=bend_opt[ipair];++iband)
2378 vband.push_back(iband);
2379 }
2380 }
2381 //image must be georeferenced
2382 if(!this->isGeoRef()){
2383 string errorstring="Warning: input image is not georeferenced using start and end band options";
2384 if(verbose_opt[0]>1)
2385 std::cerr << errorstring << std::endl;
2386 // throw(errorstring);
2387 }
2388 }
2389 catch(string error){
2390 cerr << error << std::endl;
2391 throw;
2392 }
2393
2394
2395 bool isGeoRef=false;
2396 string projectionString;
2397 // for(int iimg=0;iimg<input_opt.size();++iimg){
2398
2399 if(!isGeoRef)
2400 isGeoRef=this->isGeoRef();
2401 if(this->isGeoRef()&&projection_opt.empty())
2402 projectionString=this->getProjection();
2403 if(dx_opt.empty()){
2404 dx=this->getDeltaX();
2405 }
2406
2407 if(dy_opt.empty()){
2408 dy=this->getDeltaY();
2409 }
2410 if(vband.size())
2411 ncropband+=vband.size();
2412 else
2413 ncropband+=this->nrOfBand();
2414
2415 GDALDataType theType=getGDALDataType();
2416 if(otype_opt.size()){
2417 theType=string2GDAL(otype_opt[0]);
2418 if(theType==GDT_Unknown && verbose_opt[0]>1)
2419 std::cerr << "Warning: unknown output pixel type: " << otype_opt[0] << ", using input type as default" << std::endl;
2420 }
2421 if(verbose_opt[0]>1)
2422 cout << "Output pixel type: " << GDALGetDataTypeName(theType) << endl;
2423
2424 //bounding box of cropped image
2425 double cropulx=ulx_opt[0];
2426 double cropuly=uly_opt[0];
2427 double croplrx=lrx_opt[0];
2428 double croplry=lry_opt[0];
2429 //get bounding box from extentReader if defined
2430
2431 bool doInit=true;
2432 for(int ilayer=0;ilayer<sampleReader.getLayerCount();++ilayer){
2433 std::string currentLayername=sampleReader.getLayer(ilayer)->GetName();
2434 if(layer_opt.size())
2435 if(find(layer_opt.begin(),layer_opt.end(),currentLayername)==layer_opt.end())
2436 continue;
2437 if(verbose_opt[0]>1)
2438 std::cout << "getLayer " << std::endl;
2439 OGRLayer *readLayer=sampleReader.getLayer(ilayer);
2440 if(!readLayer){
2441 ostringstream ess;
2442 ess << "Error: could not get layer of sampleReader" << endl;
2443 throw(ess.str());
2444 }
2445 OGRSpatialReference thisSpatialRef(getProjectionRef().c_str());
2446 #if GDAL_VERSION_MAJOR > 2
2447 thisSpatialRef.SetAxisMappingStrategy(OSRAxisMappingStrategy::OAMS_TRADITIONAL_GIS_ORDER);
2448 #endif
2449 OGRSpatialReference sampleSpatialRef(sampleReader.getSpatialRef());
2450 #if GDAL_VERSION_MAJOR > 2
2451 sampleSpatialRef.SetAxisMappingStrategy(OSRAxisMappingStrategy::OAMS_TRADITIONAL_GIS_ORDER);
2452 #endif
2453
2454 OGRCoordinateTransformation *sample2img = OGRCreateCoordinateTransformation(&sampleSpatialRef, &thisSpatialRef);
2455 OGRCoordinateTransformation *img2sample = OGRCreateCoordinateTransformation(&thisSpatialRef, &sampleSpatialRef);
2456 // if(!sampleSpatialRef){
2457 // sample2img=0;
2458 // img2sample=0;
2459 // }
2460 // else if(thisSpatialRef.IsSame(sampleSpatialRef)){
2461 if(thisSpatialRef.IsSame(&sampleSpatialRef)){
2462 sample2img=0;
2463 img2sample=0;
2464 }
2465 else{
2466 if(cut_to_cutline_opt[0]||cut_in_cutline_opt[0]||eoption_opt.size()){
2467 string errorString="Error: projection of vector and raster should be identical when using cut_to_cutline, cut_in_cutline or eoption";
2468 throw(errorString);
2469 }
2470 if(!sample2img){
2471 std::ostringstream errorStream;
2472 errorStream << "Error: cannot create OGRCoordinateTransformation sample to image" << std::endl;
2473 throw(errorStream.str());
2474 }
2475 if(!img2sample){
2476 std::ostringstream errorStream;
2477 errorStream << "Error: cannot create OGRCoordinateTransformation image to sample" << std::endl;
2478 throw(errorStream.str());
2479 }
2480 }
2481 double layer_ulx;
2482 double layer_uly;
2483 double layer_lrx;
2484 double layer_lry;
2485 sampleReader.getExtent(layer_ulx,layer_uly,layer_lrx,layer_lry,ilayer,sample2img);
2486 if(verbose_opt[0]>1)
2487 std::cout << "getExtent: " << layer_ulx << ", " << layer_uly << ", " << layer_lrx << ", " << layer_lry << std::endl;
2488
2489 if(doInit){
2490 ulx_opt[0]=layer_ulx;
2491 uly_opt[0]=layer_uly;
2492 lrx_opt[0]=layer_lrx;
2493 lry_opt[0]=layer_lry;
2494 doInit=false;
2495 }
2496 else{
2497 if(layer_ulx<ulx_opt[0])
2498 ulx_opt[0]=layer_ulx;
2499 if(layer_uly>uly_opt[0])
2500 uly_opt[0]=layer_uly;
2501 if(layer_lrx>lrx_opt[0])
2502 lrx_opt[0]=layer_lrx;
2503 if(layer_lry<lry_opt[0])
2504 lry_opt[0]=layer_lry;
2505 }
2506 }
2507
2508 //ulx_opt[0],uly_opt[0],lrx_opt[0],lry_opt[0] now is maximum extent over all selected layers
2509 if(croplrx>cropulx&&cropulx>ulx_opt[0])
2510 ulx_opt[0]=cropulx;
2511 if(croplrx>cropulx&&croplrx<lrx_opt[0])
2512 lrx_opt[0]=croplrx;
2513 if(cropuly>croplry&&cropuly<uly_opt[0])
2514 uly_opt[0]=cropuly;
2515 if(croplry<cropuly&&croplry>lry_opt[0])
2516 lry_opt[0]=croplry;
2517 //ulx_opt[0],uly_opt[0],lrx_opt[0],lry_opt[0] now is minimum extent over all selected layers and user defined bounding box
2518 if(verbose_opt[0]>1)
2519 cout << "--ulx=" << ulx_opt[0] << " --uly=" << uly_opt[0] << " --lrx=" << lrx_opt[0] << " --lry=" << lry_opt[0] << endl;
2520
2521 if(doInit){//should have been set to false
2522 std::ostringstream errorStream;
2523 if(layer_opt.size())
2524 errorStream << "Error: no layer found with specified name" << std::endl;
2525 else
2526 errorStream << "Error: no layer found" << std::endl;
2527 throw(errorStream.str());//help was invoked, stop processing
2528 }
2529 if(ulx_opt[0]>=lrx_opt[0] || uly_opt[0] <= lry_opt[0]){
2530 std::ostringstream errorStream;
2531 errorStream << "Error: bounding box not properly defined" << std::endl;
2532 throw(errorStream.str());//help was invoked, stop processing
2533 }
2534
2535 int ncropcol=0;
2536 int ncroprow=0;
2537
2538 Jim maskReader;
2539 if(cut_to_cutline_opt[0]||cut_in_cutline_opt[0]||eoption_opt.size()){
2540 try{
2541 if(sampleReader.getLayerCount()>1&&(layer_opt.size()>1||layer_opt.empty())){
2542 std::ostringstream errorStream;
2543 errorStream << "Error: multiple layers not supported with cut_to_cutline or cut_to cutline, please specify a single layer" << std::endl;
2544 throw(errorStream.str());//help was invoked, stop processing
2545 }
2546
2547 ncropcol=static_cast<unsigned int>(ceil((lrx_opt[0]-ulx_opt[0])/dx));
2548 ncroprow=static_cast<unsigned int>(ceil((uly_opt[0]-lry_opt[0])/dy));
2549 maskReader.open(ncropcol,ncroprow,1,GDT_Float64);
2550 double gt[6];
2551 gt[0]=ulx_opt[0];
2552 gt[1]=dx;
2553 gt[2]=0;
2554 gt[3]=uly_opt[0];
2555 gt[4]=0;
2556 gt[5]=-dy;
2557 maskReader.setGeoTransform(gt);
2558 if(projection_opt.size())
2559 maskReader.setProjectionProj4(projection_opt[0]);
2560 else if(projectionString.size())
2561 maskReader.setProjection(projectionString);
2562
2563 // maskReader.rasterizeBuf(sampleReader,msknodata_opt[0],eoption_opt,layer_opt);
2564 maskReader.d_rasterizeBuf(sampleReader,1,eoption_opt,layer_opt);
2565 }
2566 catch(string error){
2567 cerr << error << std::endl;
2568 throw;
2569 }
2570 }
2571 //determine number of output bands
2572 int writeBand=0;//write band
2573
2574 if(scale_opt.size()){
2575 while(scale_opt.size()<vband.size())
2576 scale_opt.push_back(scale_opt[0]);
2577 }
2578 if(offset_opt.size()){
2579 while(offset_opt.size()<vband.size())
2580 offset_opt.push_back(offset_opt[0]);
2581 }
2582 if(autoscale_opt.size()){
2583 assert(autoscale_opt.size()%2==0);
2584 }
2585
2586 if(theType==GDT_Unknown){
2587 theType=this->getGDALDataType();
2588 if(verbose_opt[0]>1)
2589 cout << "Using data type from input image: " << GDALGetDataTypeName(theType) << endl;
2590 }
2591 // if(option_opt.findSubstring("INTERLEAVE=")==option_opt.end()){
2592 // string theInterleave="INTERLEAVE=";
2593 // theInterleave+=this->getInterleave();
2594 // option_opt.push_back(theInterleave);
2595 // }
2596 // if(verbose_opt[0])
2597 // cout << "size of " << input_opt[iimg] << ": " << ncol << " cols, "<< nrow << " rows" << endl;
2598 double uli,ulj,lri,lrj;//image coordinates
2599 bool forceEUgrid=false;
2600 if(projection_opt.size())
2601 forceEUgrid=(!(projection_opt[0].compare("EPSG:3035"))||!(projection_opt[0].compare("EPSG:3035"))||projection_opt[0].find("ETRS-LAEA")!=string::npos);
2602 if(ulx_opt[0]>=lrx_opt[0]){//default bounding box: no cropping
2603 uli=0;
2604 lri=this->nrOfCol()-1;
2605 ulj=0;
2606 lrj=this->nrOfRow()-1;
2607 ncropcol=this->nrOfCol();
2608 ncroprow=this->nrOfRow();
2609 this->getBoundingBox(cropulx,cropuly,croplrx,croplry);
2610 double magicX=1,magicY=1;
2611 // this->getMagicPixel(magicX,magicY);
2612 if(forceEUgrid){
2613 //force to LAEA grid
2614 Egcs egcs;
2615 egcs.setLevel(egcs.res2level(dx));
2616 egcs.force2grid(cropulx,cropuly,croplrx,croplry);
2617 this->geo2image(cropulx+(magicX-1.0)*this->getDeltaX(),cropuly-(magicY-1.0)*this->getDeltaY(),uli,ulj);
2618 this->geo2image(croplrx+(magicX-2.0)*this->getDeltaX(),croplry-(magicY-2.0)*this->getDeltaY(),lri,lrj);
2619 }
2620 this->geo2image(cropulx+(magicX-1.0)*this->getDeltaX(),cropuly-(magicY-1.0)*this->getDeltaY(),uli,ulj);
2621 this->geo2image(croplrx+(magicX-2.0)*this->getDeltaX(),croplry-(magicY-2.0)*this->getDeltaY(),lri,lrj);
2622 // ncropcol=abs(static_cast<unsigned int>(ceil((croplrx-cropulx)/dx)));
2623 // ncroprow=abs(static_cast<unsigned int>(ceil((cropuly-croplry)/dy)));
2624 ncropcol=static_cast<unsigned int>(ceil((croplrx-cropulx)/dx));
2625 ncroprow=static_cast<unsigned int>(ceil((cropuly-croplry)/dy));
2626 }
2627 else{
2628 double magicX=1,magicY=1;
2629 // this->getMagicPixel(magicX,magicY);
2630 cropulx=ulx_opt[0];
2631 cropuly=uly_opt[0];
2632 croplrx=lrx_opt[0];
2633 croplry=lry_opt[0];
2634 if(forceEUgrid){
2635 //force to LAEA grid
2636 Egcs egcs;
2637 egcs.setLevel(egcs.res2level(dx));
2638 egcs.force2grid(cropulx,cropuly,croplrx,croplry);
2639 }
2640 else if(align_opt[0]){
2641 if(cropulx>this->getUlx())
2642 cropulx-=fmod(cropulx-this->getUlx(),dx);
2643 else if(cropulx<this->getUlx())
2644 cropulx+=fmod(this->getUlx()-cropulx,dx)-dx;
2645 if(croplrx<this->getLrx())
2646 croplrx+=fmod(this->getLrx()-croplrx,dx);
2647 else if(croplrx>this->getLrx())
2648 croplrx-=fmod(croplrx-this->getLrx(),dx)+dx;
2649 if(croplry>this->getLry())
2650 croplry-=fmod(croplry-this->getLry(),dy);
2651 else if(croplry<this->getLry())
2652 croplry+=fmod(this->getLry()-croplry,dy)-dy;
2653 if(cropuly<this->getUly())
2654 cropuly+=fmod(this->getUly()-cropuly,dy);
2655 else if(cropuly>this->getUly())
2656 cropuly-=fmod(cropuly-this->getUly(),dy)+dy;
2657 }
2658 this->geo2image(cropulx+(magicX-1.0)*this->getDeltaX(),cropuly-(magicY-1.0)*this->getDeltaY(),uli,ulj);
2659 this->geo2image(croplrx+(magicX-2.0)*this->getDeltaX(),croplry-(magicY-2.0)*this->getDeltaY(),lri,lrj);
2660
2661 // ncropcol=abs(static_cast<unsigned int>(ceil((croplrx-cropulx)/dx)));
2662 // ncroprow=abs(static_cast<unsigned int>(ceil((cropuly-croplry)/dy)));
2663 ncropcol=static_cast<unsigned int>(ceil((croplrx-cropulx)/dx));
2664 ncroprow=static_cast<unsigned int>(ceil((cropuly-croplry)/dy));
2665 uli=floor(uli);
2666 ulj=floor(ulj);
2667 lri=floor(lri);
2668 lrj=floor(lrj);
2669 }
2670
2671 // double deltaX=this->getDeltaX();
2672 // double deltaY=this->getDeltaY();
2673 if(!imgWriter.nrOfBand()){//not opened yet
2674 if(verbose_opt[0]>1){
2675 cout << "cropulx: " << cropulx << endl;
2676 cout << "cropuly: " << cropuly << endl;
2677 cout << "croplrx: " << croplrx << endl;
2678 cout << "croplry: " << croplry << endl;
2679 cout << "ncropcol: " << ncropcol << endl;
2680 cout << "ncroprow: " << ncroprow << endl;
2681 cout << "cropulx+ncropcol*dx: " << cropulx+ncropcol*dx << endl;
2682 cout << "cropuly-ncroprow*dy: " << cropuly-ncroprow*dy << endl;
2683 cout << "upper left column of input image: " << uli << endl;
2684 cout << "upper left row of input image: " << ulj << endl;
2685 cout << "lower right column of input image: " << lri << endl;
2686 cout << "lower right row of input image: " << lrj << endl;
2687 cout << "new number of cols: " << ncropcol << endl;
2688 cout << "new number of rows: " << ncroprow << endl;
2689 cout << "new number of bands: " << ncropband << endl;
2690 }
2691 // string imageType;//=this->getImageType();
2692 // if(oformat_opt.size())//default
2693 // imageType=oformat_opt[0];
2694 try{
2695 imgWriter.open(ncropcol,ncroprow,ncropband,theType);
2696 imgWriter.setNoData(nodata_opt);
2697 // if(nodata_opt.size()){
2698 // imgWriter.setNoData(nodata_opt);
2699 // }
2700 }
2701 catch(string errorstring){
2702 cout << errorstring << endl;
2703 throw;
2704 }
2705 if(description_opt.size())
2706 imgWriter.setImageDescription(description_opt[0]);
2707 double gt[6];
2708 gt[0]=cropulx;
2709 gt[1]=dx;
2710 gt[2]=0;
2711 gt[3]=cropuly;
2712 gt[4]=0;
2713 gt[5]=(this->isGeoRef())? -dy : dy;
2714 imgWriter.setGeoTransform(gt);
2715 if(projection_opt.size()){
2716 if(verbose_opt[0]>1)
2717 cout << "projection: " << projection_opt[0] << endl;
2718 imgWriter.setProjectionProj4(projection_opt[0]);
2719 }
2720 else
2721 imgWriter.setProjection(this->getProjection());
2722 if(imgWriter.getDataType()==GDT_Byte){
2723 if(colorTable_opt.size()){
2724 if(colorTable_opt[0]!="none")
2725 imgWriter.setColorTable(colorTable_opt[0]);
2726 }
2727 else if (this->getColorTable()!=NULL)//copy colorTable from input image
2728 imgWriter.setColorTable(this->getColorTable());
2729 }
2730 }
2731
2732 double startCol=uli;
2733 double endCol=lri;
2734 if(uli<0)
2735 startCol=0;
2736 else if(uli>=this->nrOfCol())
2737 startCol=this->nrOfCol()-1;
2738 if(lri<0)
2739 endCol=0;
2740 else if(lri>=this->nrOfCol())
2741 endCol=this->nrOfCol()-1;
2742 double startRow=ulj;
2743 double endRow=lrj;
2744 if(ulj<0)
2745 startRow=0;
2746 else if(ulj>=this->nrOfRow())
2747 startRow=this->nrOfRow()-1;
2748 if(lrj<0)
2749 endRow=0;
2750 else if(lrj>=this->nrOfRow())
2751 endRow=this->nrOfRow()-1;
2752
2753 vector<double> readBuffer;
2754 unsigned int nband=(vband.size())?vband.size() : this->nrOfBand();
2755 for(unsigned int iband=0;iband<nband;++iband){
2756 unsigned int readBand=(vband.size()>iband)?vband[iband]:iband;
2757 if(verbose_opt[0]>1){
2758 cout << "extracting band " << readBand << endl;
2759 MyProgressFunc(progress,pszMessage,pProgressArg);
2760 }
2761 double theMin=0;
2762 double theMax=0;
2763 if(autoscale_opt.size()){
2764 try{
2765 this->getMinMax(static_cast<unsigned int>(startCol),static_cast<unsigned int>(endCol),static_cast<unsigned int>(startRow),static_cast<unsigned int>(endRow),readBand,theMin,theMax);
2766 }
2767 catch(string errorString){
2768 cout << errorString << endl;
2769 }
2770 if(verbose_opt[0]>1)
2771 cout << "minmax: " << theMin << ", " << theMax << endl;
2772 double theScale=(autoscale_opt[1]-autoscale_opt[0])/(theMax-theMin);
2773 double theOffset=autoscale_opt[0]-theScale*theMin;
2774 this->setScale(theScale,readBand);
2775 this->setOffset(theOffset,readBand);
2776 }
2777 else{
2778 if(scale_opt.size()){
2779 if(scale_opt.size()>iband)
2780 this->setScale(scale_opt[iband],readBand);
2781 else
2782 this->setScale(scale_opt[0],readBand);
2783 }
2784 if(offset_opt.size()){
2785 if(offset_opt.size()>iband)
2786 this->setOffset(offset_opt[iband],readBand);
2787 else
2788 this->setOffset(offset_opt[0],readBand);
2789 }
2790 }
2791
2792 double readRow=0;
2793 double readCol=0;
2794 double lowerCol=0;
2795 double upperCol=0;
2796 for(int irow=0;irow<imgWriter.nrOfRow();++irow){
2797 vector<double> lineMask;
2798 double x=0;
2799 double y=0;
2800 //convert irow to geo
2801 imgWriter.image2geo(0,irow,x,y);
2802 //lookup corresponding row for irow in this file
2803 this->geo2image(x,y,readCol,readRow);
2804 vector<double> writeBuffer;
2805 if(readRow<0||readRow>=this->nrOfRow()){
2806 for(int icol=0;icol<imgWriter.nrOfCol();++icol)
2807 writeBuffer.push_back(nodataValue);
2808 }
2809 else{
2810 try{
2811 if(endCol<this->nrOfCol()-1){
2812 this->readData(readBuffer,startCol,endCol+1,readRow,readBand,theResample);
2813 }
2814 else{
2815 this->readData(readBuffer,startCol,endCol,readRow,readBand,theResample);
2816 }
2817 double oldRowMask=-1;//keep track of row mask to optimize number of line readings
2818 for(int icol=0;icol<imgWriter.nrOfCol();++icol){
2819 imgWriter.image2geo(icol,irow,x,y);
2820 //lookup corresponding row for irow in this file
2821 this->geo2image(x,y,readCol,readRow);
2822 if(readCol<0||readCol>=this->nrOfCol()){
2823 writeBuffer.push_back(nodataValue);
2824 }
2825 else{
2826 bool valid=true;
2827 double geox=0;
2828 double geoy=0;
2829 if(maskReader.isInit()){
2830 //read mask
2831 double colMask=0;
2832 double rowMask=0;
2833
2834 imgWriter.image2geo(icol,irow,geox,geoy);
2835 maskReader.geo2image(geox,geoy,colMask,rowMask);
2836 colMask=static_cast<unsigned int>(colMask);
2837 rowMask=static_cast<unsigned int>(rowMask);
2838 if(rowMask>=0&&rowMask<maskReader.nrOfRow()&&colMask>=0&&colMask<maskReader.nrOfCol()){
2839 if(static_cast<unsigned int>(rowMask)!=static_cast<unsigned int>(oldRowMask)){
2840
2841 try{
2842 maskReader.readData(lineMask,static_cast<unsigned int>(rowMask),0);
2843 }
2844 catch(string errorstring){
2845 cerr << errorstring << endl;
2846 throw;
2847 }
2848 catch(...){
2849 cerr << "error caught" << std::endl;
2850 throw;
2851 }
2852 oldRowMask=rowMask;
2853 }
2854 if(cut_to_cutline_opt[0]){
2855 if(lineMask[colMask]!=1){
2856 nodataValue=nodata_opt[0];
2857 valid=false;
2858 }
2859 }
2860 else if(cut_in_cutline_opt[0]){
2861 if(lineMask[colMask]==1){
2862 nodataValue=nodata_opt[0];
2863 valid=false;
2864 }
2865 }
2866 else{
2867 for(int ivalue=0;ivalue<msknodata_opt.size();++ivalue){
2868 if(lineMask[colMask]==msknodata_opt[ivalue]){
2869 if(nodata_opt.size()>ivalue)
2870 nodataValue=nodata_opt[ivalue];
2871 valid=false;
2872 break;
2873 }
2874 }
2875 }
2876 }
2877 }
2878 if(!valid)
2879 writeBuffer.push_back(nodataValue);
2880 else{
2881 switch(theResample){
2882 case(BILINEAR):
2883 lowerCol=readCol-0.5;
2884 lowerCol=static_cast<unsigned int>(lowerCol);
2885 upperCol=readCol+0.5;
2886 upperCol=static_cast<unsigned int>(upperCol);
2887 if(lowerCol<0)
2888 lowerCol=0;
2889 if(upperCol>=this->nrOfCol())
2890 upperCol=this->nrOfCol()-1;
2891 writeBuffer.push_back((readCol-0.5-lowerCol)*readBuffer[upperCol-startCol]+(1-readCol+0.5+lowerCol)*readBuffer[lowerCol-startCol]);
2892 break;
2893 default:
2894 readCol=static_cast<unsigned int>(readCol);
2895 readCol-=startCol;//we only start reading from startCol
2896 writeBuffer.push_back(readBuffer[readCol]);
2897 break;
2898 }
2899 }
2900 }
2901 }
2902 }
2903 catch(string errorstring){
2904 cout << errorstring << endl;
2905 throw;
2906 }
2907 }
2908 if(writeBuffer.size()!=imgWriter.nrOfCol())
2909 cout << "writeBuffer.size()=" << writeBuffer.size() << ", imgWriter.nrOfCol()=" << imgWriter.nrOfCol() << endl;
2910
2911 assert(writeBuffer.size()==imgWriter.nrOfCol());
2912 try{
2913 imgWriter.writeData(writeBuffer,irow,writeBand);
2914 }
2915 catch(string errorstring){
2916 cout << errorstring << endl;
2917 throw;
2918 }
2919 if(verbose_opt[0]){
2920 progress=(1.0+irow);
2921 progress/=imgWriter.nrOfRow();
2922 MyProgressFunc(progress,pszMessage,pProgressArg);
2923 }
2924 else{
2925 progress=(1.0+irow);
2926 progress+=(imgWriter.nrOfRow()*writeBand);
2927 progress/=imgWriter.nrOfBand()*imgWriter.nrOfRow();
2928 assert(progress>=0);
2929 assert(progress<=1);
2930 if(verbose_opt[0])
2931 MyProgressFunc(progress,pszMessage,pProgressArg);
2932 }
2933 }
2934 ++writeBand;
2935 }
2936 if(maskReader.isInit())
2937 maskReader.close();
2938 }
2939 catch(string predefinedString){
2940 std::cout << predefinedString << std::endl;
2941 throw;
2942 }
2943 }
2944
2945 /**
2946 * read the data of the current raster dataset assuming it has not been read yet (otherwise use crop instead). Typically used when current dataset was opened with argument noRead true.
2947 * @param app application options
2948 **/
2949 void Jim::cropDS(Jim& imgWriter, AppFactory& app){
2950 Optionjl<std::string> resample_opt("r", "resample", "resample: GRIORA_NearestNeighbour|GRIORA_Bilinear|GRIORA_Cubic|GRIORA_CubicSpline|GRIORA_Lanczos|GRIORA_Average|GRIORA_Average|GRIORA_Gauss (check http://www.gdal.org/gdal_8h.html#a640ada511cbddeefac67c548e009d5a)","GRIORA_NearestNeighbour");
2951 Optionjl<string> projection_opt("a_srs", "a_srs", "Override the projection for the output file (leave blank to copy from input file, use epsg:3035 to use European projection and force to European grid");
2952 //todo: support layer names
2953 Optionjl<string> extent_opt("e", "extent", "get boundary from extent from polygons in vector file");
2954 Optionjl<string> layer_opt("ln", "ln", "layer name of extent to crop");
2955 Optionjl<double> ulx_opt("ulx", "ulx", "Upper left x value bounding box", 0.0);
2956 Optionjl<double> uly_opt("uly", "uly", "Upper left y value bounding box", 0.0);
2957 Optionjl<double> lrx_opt("lrx", "lrx", "Lower right x value bounding box", 0.0);
2958 Optionjl<double> lry_opt("lry", "lry", "Lower right y value bounding box", 0.0);
2959 Optionjl<double> dx_opt("dx", "dx", "Output resolution in x (in meter) (empty: keep original resolution)");
2960 Optionjl<double> dy_opt("dy", "dy", "Output resolution in y (in meter) (empty: keep original resolution)");
2961 Optionjl<double> cx_opt("x", "x", "x-coordinate of image center to crop (in meter)");
2962 Optionjl<double> cy_opt("y", "y", "y-coordinate of image center to crop (in meter)");
2963 Optionjl<double> nx_opt("nx", "nx", "image size in x to crop (in meter)");
2964 Optionjl<double> ny_opt("ny", "ny", "image size in y to crop (in meter)");
2965 Optionjl<unsigned int> ns_opt("ns", "ns", "number of samples to crop (in pixels)");
2966 Optionjl<unsigned int> nl_opt("nl", "nl", "number of lines to crop (in pixels)");
2967 Optionjl<unsigned int> band_opt("b", "band", "band index to crop (leave empty to retain all bands)");
2968 Optionjl<unsigned int> bstart_opt("sband", "startband", "Start band sequence number");
2969 Optionjl<unsigned int> bend_opt("eband", "endband", "End band sequence number");
2970 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");
2971 // Optionjl<string> oformat_opt("of", "oformat", "Output image format (see also gdal_translate).","GTiff");
2972 // Optionjl<string> option_opt("co", "co", "Creation option for output file. Multiple options can be specified.");
2973 Optionjl<string> colorTable_opt("ct", "ct", "color table (file with 5 columns: id R G B ALFA (0: transparent, 255: solid)");
2974 Optionjl<double> nodata_opt("nodata", "nodata", "Nodata value to put in image if out of bounds.");
2975 Optionjl<string> description_opt("d", "description", "Set image description");
2976 Optionjl<bool> align_opt("align", "align", "Align output bounding box to input image",false);
2977 Optionjl<short> verbose_opt("v", "verbose", "verbose", 0,2);
2978
2979 extent_opt.setHide(1);
2980 layer_opt.setHide(1);
2981 bstart_opt.setHide(1);
2982 bend_opt.setHide(1);
2983 // option_opt.setHide(1);
2984 cx_opt.setHide(1);
2985 cy_opt.setHide(1);
2986 nx_opt.setHide(1);
2987 ny_opt.setHide(1);
2988 ns_opt.setHide(1);
2989 nl_opt.setHide(1);
2990 nodata_opt.setHide(1);
2991 description_opt.setHide(1);
2992
2993 bool doProcess;//stop process when program was invoked with help option (-h --help)
2994 try{
2995 doProcess=projection_opt.retrieveOption(app);
2996 ulx_opt.retrieveOption(app);
2997 uly_opt.retrieveOption(app);
2998 lrx_opt.retrieveOption(app);
2999 lry_opt.retrieveOption(app);
3000 band_opt.retrieveOption(app);
3001 bstart_opt.retrieveOption(app);
3002 bend_opt.retrieveOption(app);
3003 otype_opt.retrieveOption(app);
3004 // oformat_opt.retrieveOption(app);
3005 colorTable_opt.retrieveOption(app);
3006 dx_opt.retrieveOption(app);
3007 dy_opt.retrieveOption(app);
3008 resample_opt.retrieveOption(app);
3009 extent_opt.retrieveOption(app);
3010 layer_opt.retrieveOption(app);
3011 // option_opt.retrieveOption(app);
3012 cx_opt.retrieveOption(app);
3013 cy_opt.retrieveOption(app);
3014 nx_opt.retrieveOption(app);
3015 ny_opt.retrieveOption(app);
3016 ns_opt.retrieveOption(app);
3017 nl_opt.retrieveOption(app);
3018 nodata_opt.retrieveOption(app);
3019 description_opt.retrieveOption(app);
3020 align_opt.retrieveOption(app);
3021 verbose_opt.retrieveOption(app);
3022
3023 if(!doProcess){
3024 cout << endl;
3025 std::ostringstream helpStream;
3026 helpStream << "short option -h shows basic options only, use long option --help to show all options" << std::endl;
3027 throw(helpStream.str());//help was invoked, stop processing
3028 }
3029
3030 std::vector<std::string> badKeys;
3031 app.badKeys(badKeys);
3032 if(badKeys.size()){
3033 std::ostringstream errorStream;
3034 if(badKeys.size()>1)
3035 errorStream << "Error: unknown keys: ";
3036 else
3037 errorStream << "Error: unknown key: ";
3038 for(int ikey=0;ikey<badKeys.size();++ikey){
3039 errorStream << badKeys[ikey] << " ";
3040 }
3041 errorStream << std::endl;
3042 throw(errorStream.str());
3043 }
3044
3045 double nodataValue=nodata_opt.size()? nodata_opt[0] : 0;
3046 RESAMPLE theResample;
3047 if(resample_opt[0]=="near"){
3048 theResample=NEAR;
3049 if(verbose_opt[0])
3050 cout << "resampling: nearest neighbor" << endl;
3051 }
3052 else if(resample_opt[0]=="bilinear"){
3053 theResample=BILINEAR;
3054 if(verbose_opt[0])
3055 cout << "resampling: bilinear interpolation" << endl;
3056 }
3057 else{
3058 std::ostringstream errorStream;
3059 errorStream << "Error: resampling method " << resample_opt[0] << " not supported";
3060 throw(errorStream.str());
3061 }
3062
3063 const char* pszMessage;
3064 void* pProgressArg=NULL;
3065 GDALProgressFunc pfnProgress=GDALTermProgress;
3066 double progress=0;
3067 if(verbose_opt[0])
3068 MyProgressFunc(progress,pszMessage,pProgressArg);
3069 // ImgReaderGdal imgReader;
3070 // ImgWriterGdal imgWriter;
3071 //open input images to extract number of bands and spatial resolution
3072 int ncropband=0;//total number of bands to write
3073 double dx=0;
3074 double dy=0;
3075 if(dx_opt.size())
3076 dx=dx_opt[0];
3077 if(dy_opt.size())
3078 dy=dy_opt[0];
3079
3080 std::vector<unsigned int> vband=band_opt;
3081 try{
3082 //convert start and end band options to vector of band indexes
3083 if(bstart_opt.size()){
3084 if(bend_opt.size()!=bstart_opt.size()){
3085 string errorstring="Error: options for start and end band indexes must be provided as pairs, missing end band";
3086 throw(errorstring);
3087 }
3088 vband.clear();
3089 for(int ipair=0;ipair<bstart_opt.size();++ipair){
3090 if(bend_opt[ipair]<bstart_opt[ipair]){
3091 string errorstring="Error: index for start band must be smaller then end band";
3092 throw(errorstring);
3093 }
3094 for(unsigned int iband=bstart_opt[ipair];iband<=bend_opt[ipair];++iband)
3095 vband.push_back(iband);
3096 }
3097 }
3098 //image must be georeferenced
3099 if(!this->isGeoRef()){
3100 string errorstring="Warning: input image is not georeferenced in cropDS";
3101 if(verbose_opt[0])
3102 std::cerr << errorstring << std::endl;
3103 // throw(errorstring);
3104 }
3105 }
3106 catch(string error){
3107 cerr << error << std::endl;
3108 throw;
3109 }
3110
3111
3112 bool isGeoRef=false;
3113 string projectionString;
3114 // for(int iimg=0;iimg<input_opt.size();++iimg){
3115
3116 if(!isGeoRef)
3117 isGeoRef=this->isGeoRef();
3118 if(this->isGeoRef()&&projection_opt.empty())
3119 projectionString=this->getProjection();
3120 if(dx_opt.empty()){
3121 dx=this->getDeltaX();
3122 }
3123
3124 if(dy_opt.empty()){
3125 dy=this->getDeltaY();
3126 }
3127 if(vband.size())
3128 ncropband+=vband.size();
3129 else
3130 ncropband+=this->nrOfBand();
3131
3132 GDALDataType theType=getGDALDataType();
3133 if(otype_opt.size()){
3134 theType=string2GDAL(otype_opt[0]);
3135 if(theType==GDT_Unknown && verbose_opt[0])
3136 std::cerr << "Warning: unknown output pixel type: " << otype_opt[0] << ", using input type as default" << std::endl;
3137 }
3138 if(verbose_opt[0])
3139 cout << "Output pixel type: " << GDALGetDataTypeName(theType) << endl;
3140
3141 //bounding box of cropped image
3142 double cropulx=ulx_opt[0];
3143 double cropuly=uly_opt[0];
3144 double croplrx=lrx_opt[0];
3145 double croplry=lry_opt[0];
3146 //get bounding box from extentReader if defined
3147 VectorOgr extentReader;
3148
3149 if(extent_opt.size()){
3150 double e_ulx;
3151 double e_uly;
3152 double e_lrx;
3153 double e_lry;
3154 for(int iextent=0;iextent<extent_opt.size();++iextent){
3155 extentReader.open(extent_opt[iextent],layer_opt,true);//noread=true
3156 extentReader.getExtent(e_ulx,e_uly,e_lrx,e_lry);
3157 if(!iextent){
3158 ulx_opt[0]=e_ulx;
3159 uly_opt[0]=e_uly;
3160 lrx_opt[0]=e_lrx;
3161 lry_opt[0]=e_lry;
3162 }
3163 else{
3164 if(e_ulx<ulx_opt[0])
3165 ulx_opt[0]=e_ulx;
3166 if(e_uly>uly_opt[0])
3167 uly_opt[0]=e_uly;
3168 if(e_lrx>lrx_opt[0])
3169 lrx_opt[0]=e_lrx;
3170 if(e_lry<lry_opt[0])
3171 lry_opt[0]=e_lry;
3172 }
3173 extentReader.close();
3174 }
3175 if(croplrx>cropulx&&cropulx>ulx_opt[0])
3176 ulx_opt[0]=cropulx;
3177 if(croplrx>cropulx&&croplrx<lrx_opt[0])
3178 lrx_opt[0]=croplrx;
3179 if(cropuly>croplry&&cropuly<uly_opt[0])
3180 uly_opt[0]=cropuly;
3181 if(croplry<cropuly&&croplry>lry_opt[0])
3182 lry_opt[0]=croplry;
3183 }
3184 else if(cx_opt.size()&&cy_opt.size()&&nx_opt.size()&&ny_opt.size()){
3185 ulx_opt[0]=cx_opt[0]-nx_opt[0]/2.0;
3186 uly_opt[0]=(isGeoRef) ? cy_opt[0]+ny_opt[0]/2.0 : cy_opt[0]-ny_opt[0]/2.0;
3187 lrx_opt[0]=cx_opt[0]+nx_opt[0]/2.0;
3188 lry_opt[0]=(isGeoRef) ? cy_opt[0]-ny_opt[0]/2.0 : cy_opt[0]+ny_opt[0]/2.0;
3189 }
3190 else if(cx_opt.size()&&cy_opt.size()&&ns_opt.size()&&nl_opt.size()){
3191 ulx_opt[0]=cx_opt[0]-ns_opt[0]*dx/2.0;
3192 uly_opt[0]=(isGeoRef) ? cy_opt[0]+nl_opt[0]*dy/2.0 : cy_opt[0]-nl_opt[0]*dy/2.0;
3193 lrx_opt[0]=cx_opt[0]+ns_opt[0]*dx/2.0;
3194 lry_opt[0]=(isGeoRef) ? cy_opt[0]-nl_opt[0]*dy/2.0 : cy_opt[0]+nl_opt[0]*dy/2.0;
3195 }
3196
3197 if(verbose_opt[0])
3198 cout << "--ulx=" << ulx_opt[0] << " --uly=" << uly_opt[0] << " --lrx=" << lrx_opt[0] << " --lry=" << lry_opt[0] << endl;
3199
3200 int ncropcol=0;
3201 int ncroprow=0;
3202
3203 //determine number of output bands
3204 int writeBand=0;//write band
3205
3206 if(theType==GDT_Unknown){
3207 theType=this->getGDALDataType();
3208 if(verbose_opt[0])
3209 cout << "Using data type from input image: " << GDALGetDataTypeName(theType) << endl;
3210 }
3211 // if(option_opt.findSubstring("INTERLEAVE=")==option_opt.end()){
3212 // string theInterleave="INTERLEAVE=";
3213 // theInterleave+=this->getInterleave();
3214 // option_opt.push_back(theInterleave);
3215 // }
3216 // if(verbose_opt[0])
3217 // cout << "size of " << input_opt[iimg] << ": " << ncol << " cols, "<< nrow << " rows" << endl;
3218 // double uli,ulj,lri,lrj;//image coordinates
3219 bool forceEUgrid=false;
3220 if(projection_opt.size())
3221 forceEUgrid=(!(projection_opt[0].compare("EPSG:3035"))||!(projection_opt[0].compare("EPSG:3035"))||projection_opt[0].find("ETRS-LAEA")!=string::npos);
3222 if(ulx_opt[0]>=lrx_opt[0]){//default bounding box: no cropping
3223 // uli=0;
3224 // lri=this->nrOfCol()-1;
3225 // ulj=0;
3226 // lrj=this->nrOfRow()-1;
3227 ncropcol=this->nrOfCol();
3228 ncroprow=this->nrOfRow();
3229 this->getBoundingBox(cropulx,cropuly,croplrx,croplry);
3230 double magicX=1,magicY=1;
3231 // this->getMagicPixel(magicX,magicY);
3232 if(forceEUgrid){
3233 //force to LAEA grid
3234 Egcs egcs;
3235 egcs.setLevel(egcs.res2level(dx));
3236 egcs.force2grid(cropulx,cropuly,croplrx,croplry);
3237 // this->geo2image(cropulx+(magicX-1.0)*this->getDeltaX(),cropuly-(magicY-1.0)*this->getDeltaY(),uli,ulj);
3238 // this->geo2image(croplrx+(magicX-2.0)*this->getDeltaX(),croplry-(magicY-2.0)*this->getDeltaY(),lri,lrj);
3239 }
3240 // this->geo2image(cropulx+(magicX-1.0)*this->getDeltaX(),cropuly-(magicY-1.0)*this->getDeltaY(),uli,ulj);
3241 // this->geo2image(croplrx+(magicX-2.0)*this->getDeltaX(),croplry-(magicY-2.0)*this->getDeltaY(),lri,lrj);
3242 // ncropcol=abs(static_cast<unsigned int>(ceil((croplrx-cropulx)/dx)));
3243 // ncroprow=abs(static_cast<unsigned int>(ceil((cropuly-croplry)/dy)));
3244 ncropcol=static_cast<unsigned int>(ceil((croplrx-cropulx)/dx));
3245 ncroprow=static_cast<unsigned int>(ceil((cropuly-croplry)/dy));
3246 }
3247 else{
3248 double magicX=1,magicY=1;
3249 // this->getMagicPixel(magicX,magicY);
3250 cropulx=ulx_opt[0];
3251 cropuly=uly_opt[0];
3252 croplrx=lrx_opt[0];
3253 croplry=lry_opt[0];
3254 if(forceEUgrid){
3255 //force to LAEA grid
3256 Egcs egcs;
3257 egcs.setLevel(egcs.res2level(dx));
3258 egcs.force2grid(cropulx,cropuly,croplrx,croplry);
3259 }
3260 else if(align_opt[0]){
3261 if(cropulx>this->getUlx())
3262 cropulx-=fmod(cropulx-this->getUlx(),dx);
3263 else if(cropulx<this->getUlx())
3264 cropulx+=fmod(this->getUlx()-cropulx,dx)-dx;
3265 if(croplrx<this->getLrx())
3266 croplrx+=fmod(this->getLrx()-croplrx,dx);
3267 else if(croplrx>this->getLrx())
3268 croplrx-=fmod(croplrx-this->getLrx(),dx)+dx;
3269 if(croplry>this->getLry())
3270 croplry-=fmod(croplry-this->getLry(),dy);
3271 else if(croplry<this->getLry())
3272 croplry+=fmod(this->getLry()-croplry,dy)-dy;
3273 if(cropuly<this->getUly())
3274 cropuly+=fmod(this->getUly()-cropuly,dy);
3275 else if(cropuly>this->getUly())
3276 cropuly-=fmod(cropuly-this->getUly(),dy)+dy;
3277 }
3278 // this->geo2image(cropulx+(magicX-1.0)*this->getDeltaX(),cropuly-(magicY-1.0)*this->getDeltaY(),uli,ulj);
3279 // this->geo2image(croplrx+(magicX-2.0)*this->getDeltaX(),croplry-(magicY-2.0)*this->getDeltaY(),lri,lrj);
3280
3281 // ncropcol=abs(static_cast<unsigned int>(ceil((croplrx-cropulx)/dx)));
3282 // ncropcol=abs(static_cast<unsigned int>(ceil((croplrx-cropulx)/dx)));
3283 ncroprow=static_cast<unsigned int>(ceil((cropuly-croplry)/dy));
3284 ncroprow=static_cast<unsigned int>(ceil((cropuly-croplry)/dy));
3285 // uli=floor(uli);
3286 // ulj=floor(ulj);
3287 // lri=floor(lri);
3288 // lrj=floor(lrj);
3289 }
3290
3291 // double deltaX=this->getDeltaX();
3292 // double deltaY=this->getDeltaY();
3293 if(!imgWriter.nrOfBand()){//not opened yet
3294 if(verbose_opt[0]){
3295 cout << "cropulx: " << cropulx << endl;
3296 cout << "cropuly: " << cropuly << endl;
3297 cout << "croplrx: " << croplrx << endl;
3298 cout << "croplry: " << croplry << endl;
3299 cout << "ncropcol: " << ncropcol << endl;
3300 cout << "ncroprow: " << ncroprow << endl;
3301 cout << "cropulx+ncropcol*dx: " << cropulx+ncropcol*dx << endl;
3302 cout << "cropuly-ncroprow*dy: " << cropuly-ncroprow*dy << endl;
3303 // cout << "upper left column of input image: " << uli << endl;
3304 // cout << "upper left row of input image: " << ulj << endl;
3305 // cout << "lower right column of input image: " << lri << endl;
3306 // cout << "lower right row of input image: " << lrj << endl;
3307 cout << "new number of cols: " << ncropcol << endl;
3308 cout << "new number of rows: " << ncroprow << endl;
3309 cout << "new number of bands: " << ncropband << endl;
3310 }
3311 // string imageType;//=this->getImageType();
3312 // if(oformat_opt.size())//default
3313 // imageType=oformat_opt[0];
3314 try{
3315 imgWriter.open(ncropcol,ncroprow,ncropband,theType);
3316 imgWriter.setNoData(nodata_opt);
3317 // if(nodata_opt.size()){
3318 // imgWriter.setNoData(nodata_opt);
3319 // }
3320 }
3321 catch(string errorstring){
3322 cout << errorstring << endl;
3323 throw;
3324 }
3325 if(description_opt.size())
3326 imgWriter.setImageDescription(description_opt[0]);
3327 double gt[6];
3328 gt[0]=cropulx;
3329 gt[1]=dx;
3330 gt[2]=0;
3331 gt[3]=cropuly;
3332 gt[4]=0;
3333 gt[5]=(this->isGeoRef())? -dy : dy;
3334 imgWriter.setGeoTransform(gt);
3335 if(projection_opt.size()){
3336 if(verbose_opt[0])
3337 cout << "projection: " << projection_opt[0] << endl;
3338 imgWriter.setProjectionProj4(projection_opt[0]);
3339 }
3340 else
3341 imgWriter.setProjection(this->getProjection());
3342 if(imgWriter.getDataType()==GDT_Byte){
3343 if(colorTable_opt.size()){
3344 if(colorTable_opt[0]!="none")
3345 imgWriter.setColorTable(colorTable_opt[0]);
3346 }
3347 else if (this->getColorTable()!=NULL)//copy colorTable from input image
3348 imgWriter.setColorTable(this->getColorTable());
3349 }
3350 }
3351
3352 // double startCol=uli;
3353 // double endCol=lri;
3354 // if(uli<0)
3355 // startCol=0;
3356 // else if(uli>=this->nrOfCol())
3357 // startCol=this->nrOfCol()-1;
3358 // if(lri<0)
3359 // endCol=0;
3360 // else if(lri>=this->nrOfCol())
3361 // endCol=this->nrOfCol()-1;
3362 // double startRow=ulj;
3363 // double endRow=lrj;
3364 // if(ulj<0)
3365 // startRow=0;
3366 // else if(ulj>=this->nrOfRow())
3367 // startRow=this->nrOfRow()-1;
3368 // if(lrj<0)
3369 // endRow=0;
3370 // else if(lrj>=this->nrOfRow())
3371 // endRow=this->nrOfRow()-1;
3372
3373 //todo: readDS here
3374 if(m_gds == NULL){
3375 std::string errorString="Error in readNewBlock";
3376 throw(errorString);
3377 }
3378 // if(m_end[iband]<m_blockSize)//first time
3379 // m_end[iband]=m_blockSize;
3380 // while(row>=m_end[iband]&&m_begin[iband]<nrOfRow()){
3381 // m_begin[iband]+=m_blockSize;
3382 // m_end[iband]=m_begin[iband]+m_blockSize;
3383 // }
3384 // if(m_end[iband]>nrOfRow())
3385 // m_end[iband]=nrOfRow();
3386
3387 int gds_ncol=m_gds->GetRasterXSize();
3388 int gds_nrow=m_gds->GetRasterYSize();
3389 int gds_nband=m_gds->GetRasterCount();
3390 double gds_gt[6];
3391 m_gds->GetGeoTransform(gds_gt);
3392 double gds_ulx=gds_gt[0];
3393 double gds_uly=gds_gt[3];
3394 double gds_lrx=gds_gt[0]+gds_ncol*gds_gt[1]+gds_nrow*gds_gt[2];
3395 double gds_lry=gds_gt[3]+gds_ncol*gds_gt[4]+gds_nrow*gds_gt[5];
3396 double gds_dx=gds_gt[1];
3397 double gds_dy=-gds_gt[5];
3398 double diffXm=getUlx()-gds_ulx;
3399 // double diffYm=gds_uly-getUly();
3400
3401 // double dfXSize=diffXm/gds_dx;
3402 double dfXSize=(getLrx()-getUlx())/gds_dx;//x-size in pixels of region to read in original image
3403 double dfXOff=diffXm/gds_dx;
3404 // double dfYSize=diffYm/gds_dy;
3405 // double dfYSize=(getUly()-getLry())/gds_dy;//y-size in piyels of region to read in original image
3406 // double dfYOff=diffYm/gds_dy;
3407 // int nYOff=static_cast<int>(dfYOff);
3408 // int nXSize=abs(static_cast<unsigned int>(ceil((getLrx()-getUlx())/gds_dx)));//x-size in pixels of region to read in original image
3409 int nXSize=static_cast<unsigned int>(ceil((getLrx()-getUlx())/gds_dx));//x-size in pixels of region to read in original image
3410 int nXOff=static_cast<int>(dfXOff);
3411 if(nXSize>gds_ncol)
3412 nXSize=gds_ncol;
3413
3414 double dfYSize=0;
3415 double dfYOff=0;
3416 int nYSize=0;
3417 int nYOff=0;
3418
3419 GDALRasterIOExtraArg sExtraArg;
3420 INIT_RASTERIO_EXTRA_ARG(sExtraArg);
3421 sExtraArg.eResampleAlg = m_resample;
3422 for(int iband=0;iband<m_nband;++iband){
3423 //fetch raster band
3424 GDALRasterBand *poBand;
3425 if(nrOfBand()<=iband){
3426 std::string errorString="Error: band number exceeds available bands in readNewBlock";
3427 throw(errorString);
3428 }
3429 poBand = m_gds->GetRasterBand(iband+1);//GDAL uses 1 based index
3430
3431 dfYSize=(m_end[iband]-m_begin[iband])*getDeltaY()/gds_dy;//y-size in pixels of region to read in original image
3432 // nYSize=abs(static_cast<unsigned int>(ceil((m_end[iband]-m_begin[iband])*getDeltaY()/gds_dy)));//y-size in pixels of region to read in original image
3433 nYSize=static_cast<unsigned int>(ceil((m_end[iband]-m_begin[iband])*getDeltaY()/gds_dy));//y-size in pixels of region to read in original image
3434 if(nYSize>gds_nrow)
3435 nYSize=gds_nrow;
3436 dfYOff=(gds_uly-getUly())/gds_dy+m_begin[iband]*getDeltaY()/gds_dy;
3437 nYOff=static_cast<int>(dfYOff);
3438 if(poBand->GetOverviewCount()){
3439 //calculate number of desired samples in overview
3440 // int nDesiredSamples=abs(static_cast<unsigned int>(ceil((gds_lrx-gds_ulx)/getDeltaX()))*static_cast<unsigned int>(ceil((gds_uly-gds_lry)/getDeltaY())));
3441 int nDesiredSamples=static_cast<unsigned int>(ceil((gds_lrx-gds_ulx)/getDeltaX()))*static_cast<unsigned int>(ceil((gds_uly-gds_lry)/getDeltaY()));
3442 poBand=poBand->GetRasterSampleOverview(nDesiredSamples);
3443 if(poBand->GetXSize()*poBand->GetYSize()<nDesiredSamples){
3444 //should never be entered as GetRasterSampleOverview must return best overview or original band in worst case...
3445 // std::cout << "Warning: not enough samples in best overview, falling back to original band" << std::endl;
3446 poBand = m_gds->GetRasterBand(iband+1);//GDAL uses 1 based index
3447 }
3448 int ods_ncol=poBand->GetXSize();
3449 int ods_nrow=poBand->GetYSize();
3450 double ods_dx=gds_dx*gds_ncol/ods_ncol;
3451 double ods_dy=gds_dy*gds_nrow/ods_nrow;
3452
3453 // dfXSize=diffXm/ods_dx;
3454 dfXSize=(getLrx()-getUlx())/ods_dx;
3455 // nXSize=abs(static_cast<unsigned int>(ceil((getLrx()-getUlx())/ods_dx)));//x-size in pixels of region to read in overview image
3456 nXSize=static_cast<unsigned int>(ceil((getLrx()-getUlx())/ods_dx));//x-size in pixels of region to read in overview image
3457 if(nXSize>ods_ncol)
3458 nXSize=ods_ncol;
3459 dfXOff=diffXm/ods_dx;
3460 nXOff=static_cast<int>(dfXOff);
3461 dfYSize=(m_end[iband]-m_begin[iband])*getDeltaY()/ods_dy;//y-size in pixels of region to read in overview image
3462 // nYSize=abs(static_cast<unsigned int>(ceil((m_end[iband]-m_begin[iband])*getDeltaY()/ods_dy)));//y-size in pixels of region to read in overview image
3463 nYSize=static_cast<unsigned int>(ceil((m_end[iband]-m_begin[iband])*getDeltaY()/ods_dy));//y-size in pixels of region to read in overview image
3464 if(nYSize>ods_nrow)
3465 nYSize=ods_nrow;
3466 dfYOff=(gds_uly-getUly())/ods_dy+m_begin[iband]*getDeltaY()/ods_dy;
3467 nYOff=static_cast<int>(dfYOff);
3468 }
3469 if(dfXOff-nXOff>0||dfYOff-nYOff>0||getDeltaX()<gds_dx||getDeltaX()>gds_dx||getDeltaY()<gds_dy||getDeltaY()>gds_dy){
3470 sExtraArg.bFloatingPointWindowValidity = TRUE;
3471 sExtraArg.dfXOff = dfXOff;
3472 sExtraArg.dfYOff = dfYOff;
3473 sExtraArg.dfXSize = dfXSize;
3474 sExtraArg.dfYSize = dfYSize;
3475 }
3476 else{
3477 sExtraArg.bFloatingPointWindowValidity = FALSE;
3478 sExtraArg.dfXOff = 0;
3479 sExtraArg.dfYOff = 0;
3480 sExtraArg.dfXSize = dfXSize;
3481 sExtraArg.dfYSize = dfYSize;
3482 }
3483 // //test
3484 // std::cout << "nXOff: " << nXOff << std::endl;
3485 // std::cout << "nYOff: " << nYOff << std::endl;
3486 // std::cout << "dfXOff: " << dfXOff << std::endl;
3487 // std::cout << "dfYOff: " << dfYOff << std::endl;
3488 // std::cout << "nXSize: " << nXSize << std::endl;
3489 // std::cout << "nYSize: " << nYSize << std::endl;
3490 // std::cout << "nrOfCol(): " << nrOfCol() << std::endl;
3491 // std::cout << "nrOfRow(): " << nrOfRow() << std::endl;
3492 // std::cout << "getDeltaX(): " << getDeltaX() << std::endl;
3493 // std::cout << "getDeltaY(): " << getDeltaY() << std::endl;
3494 // std::cout << "gds_dx: " << gds_dx << std::endl;
3495 // std::cout << "gds_dy: " << gds_dy << std::endl;
3496 // std::cout << "getUlx(): " << getUlx() << std::endl;
3497 // std::cout << "getUly(): " << getUly() << std::endl;
3498 // std::cout << "gds_ulx: " << gds_ulx << std::endl;
3499 // std::cout << "gds_uly: " << gds_uly << std::endl;
3500 // eRWFlag Either GF_Read to read a region of data, or GF_Write to write a region of data.
3501 // nXOff The pixel offset to the top left corner of the region of the band to be accessed. This would be zero to start from the left side.
3502 // nYOff The line offset to the top left corner of the region of the band to be accessed. This would be zero to start from the top.
3503 // nXSize The width of the region of the band to be accessed in pixels.
3504 // nYSize The height of the region of the band to be accessed in lines.
3505 // pData The buffer into which the data should be read, or from which it should be written. This buffer must contain at least nBufXSize * nBufYSize words of type eBufType. It is organized in left to right, top to bottom pixel order. Spacing is controlled by the nPixelSpace, and nLineSpace parameters.
3506 // nBufXSize the width of the buffer image into which the desired region is to be read, or from which it is to be written.
3507 // nBufYSize the height of the buffer image into which the desired region is to be read, or from which it is to be written.
3508 // eBufType the type of the pixel values in the pData data buffer. The pixel values will automatically be translated to/from the GDALRasterBand data type as needed.
3509 // nPixelSpace The byte offset from the start of one pixel value in pData to the start of the next pixel value within a scanline. If defaulted (0) the size of the datatype eBufType is used.
3510 // nLineSpace The byte offset from the start of one scanline in pData to the start of the next. If defaulted (0) the size of the datatype eBufType * nBufXSize is used.
3511 // psExtraArg (new in GDAL 2.0) pointer to a GDALRasterIOExtraArg structure with additional arguments to specify resampling and progress callback, or NULL for default behaviour. The GDAL_RASTERIO_RESAMPLING configuration option can also be defined to override the default resampling to one of BILINEAR, CUBIC, CUBICSPLINE, LANCZOS, AVERAGE or MODE.
3512
3513 if((poBand->RasterIO(GF_Read,nXOff,nYOff+m_begin[iband],nXSize,nYSize,imgWriter.getDataPointer(iband),imgWriter.nrOfCol(),imgWriter.nrOfRow(),imgWriter.getGDALDataType(),0,0,&sExtraArg) != CE_None)){
3514 std::ostringstream errorStream;
3515 errorStream << "Error: could not read raster band using RasterIO";
3516 throw(errorStream.str());
3517 }
3518 }
3519 }
3520 catch(string predefinedString){
3521 std::cout << predefinedString << std::endl;
3522 throw;
3523 }
3524 }
3525
3526 shared_ptr<Jim> Jim::createct(app::AppFactory& app){
3527 shared_ptr<Jim> imgWriter=Jim::createImg();
3528 createct(*imgWriter, app);
3529 return(imgWriter);
3530 }
3531
3532 void Jim::createct(Jim& imgWriter, app::AppFactory& app){
3533 Optionjl<double> min_opt("min", "min", "minimum value", 0);
3534 Optionjl<double> max_opt("max", "max", "maximum value", 100);
3535 Optionjl<bool> grey_opt("g", "grey", "grey scale", false);
3536 Optionjl<string> colorTable_opt("ct", "ct", "color table (file with 5 columns: id R G B ALFA (0: transparent, 255: solid)");
3537 Optionjl<bool> verbose_opt("v", "verbose", "verbose", false,2);
3538
3539 bool doProcess;//stop process when program was invoked with help option (-h --help)
3540 doProcess=min_opt.retrieveOption(app);
3541 max_opt.retrieveOption(app);
3542 grey_opt.retrieveOption(app);
3543 colorTable_opt.retrieveOption(app);
3544 verbose_opt.retrieveOption(app);
3545
3546 if(!doProcess){
3547 cout << endl;
3548 std::ostringstream helpStream;
3549 helpStream << "short option -h shows basic options only, use long option --help to show all options" << std::endl;
3550 throw(helpStream.str());//help was invoked, stop processing
3551 }
3552
3553 std::vector<std::string> badKeys;
3554 app.badKeys(badKeys);
3555 if(badKeys.size()){
3556 std::ostringstream errorStream;
3557 if(badKeys.size()>1)
3558 errorStream << "Error: unknown keys: ";
3559 else
3560 errorStream << "Error: unknown key: ";
3561 for(int ikey=0;ikey<badKeys.size();++ikey){
3562 errorStream << badKeys[ikey] << " ";
3563 }
3564 errorStream << std::endl;
3565 throw(errorStream.str());
3566 }
3567
3568 GDALColorTable colorTable;
3569 GDALColorEntry sEntry;
3570 if(colorTable_opt.empty()){
3571 sEntry.c4=255;
3572 for(int i=min_opt[0];i<=max_opt[0];++i){
3573 if(grey_opt[0]){
3574 sEntry.c1=255*(i-min_opt[0])/(max_opt[0]-min_opt[0]);
3575 sEntry.c2=255*(i-min_opt[0])/(max_opt[0]-min_opt[0]);
3576 sEntry.c3=255*(i-min_opt[0])/(max_opt[0]-min_opt[0]);
3577 }
3578 else{//hot to cold colour ramp
3579 sEntry.c1=255;
3580 sEntry.c2=255;
3581 sEntry.c3=255;
3582 double delta=max_opt[0]-min_opt[0];
3583 if(i<(min_opt[0]+0.25*delta)){
3584 sEntry.c1=0;
3585 sEntry.c2=255*4*(i-min_opt[0])/delta;
3586 }
3587 else if(i<(min_opt[0]+0.5*delta)){
3588 sEntry.c1=0;
3589 sEntry.c3=255*(1+4*(min_opt[0]+0.25*delta-i)/delta);
3590 }
3591 else if(i<(min_opt[0]+0.75*delta)){
3592 sEntry.c1=255*4*(i-min_opt[0]-0.5*delta)/delta;
3593 sEntry.c3=0;
3594 }
3595 else{
3596 sEntry.c2=255*(1+4*(min_opt[0]+0.75*delta-i)/delta);
3597 sEntry.c3=0;
3598 }
3599 }
3600 colorTable.SetColorEntry(i,&sEntry);
3601 // if(output_opt.empty())
3602 // cout << i << " " << sEntry.c1 << " " << sEntry.c2 << " " << sEntry.c3 << " " << sEntry.c4 << endl;
3603 }
3604 }
3605 imgWriter.open(nrOfCol(),nrOfRow(),1,GDT_Byte);
3606 std::vector<double> gt;
3607 getGeoTransform(gt);
3608 imgWriter.setGeoTransform(gt);
3609 imgWriter.setProjection(getProjection());
3610 if(colorTable_opt.size()){
3611 if(colorTable_opt[0]!="none")
3612 imgWriter.setColorTable(colorTable_opt[0]);
3613 }
3614 else
3615 imgWriter.setColorTable(&colorTable);
3616 switch(getDataType()){
3617 case(GDT_Byte):{
3618 #if JIPLIB_PROCESS_IN_PARALLEL == 1
3619 #pragma omp parallel for
3620 #else
3621 #endif
3622 for(unsigned int irow=0;irow<nrOfRow();++irow){
3623 vector<char> buffer;
3624 readData(buffer,irow);
3625 imgWriter.writeData(buffer,irow);
3626 }
3627 break;
3628 }
3629 case(GDT_Int16):{
3630 if(verbose_opt[0])
3631 std::cerr << "Warning: copying short to unsigned short without conversion, use convert with -scale if needed..." << std::endl;
3632 #if JIPLIB_PROCESS_IN_PARALLEL == 1
3633 #pragma omp parallel for
3634 #else
3635 #endif
3636 for(unsigned int irow=0;irow<nrOfRow();++irow){
3637 vector<short> buffer;
3638 readData(buffer,irow);
3639 imgWriter.writeData(buffer,irow);
3640 }
3641 break;
3642 }
3643 case(GDT_UInt16):{
3644 #if JIPLIB_PROCESS_IN_PARALLEL == 1
3645 #pragma omp parallel for
3646 #else
3647 #endif
3648 for(unsigned int irow=0;irow<nrOfRow();++irow){
3649 vector<unsigned short> buffer;
3650 readData(buffer,irow);
3651 imgWriter.writeData(buffer,irow);
3652 }
3653 break;
3654 }
3655 default:
3656 if(verbose_opt[0])
3657 cerr << "data type " << getDataType() << " not supported for adding a colortable" << endl;
3658 break;
3659 }
3660 }
3661
3662 //stack image to current image
3663 void Jim::stackBand(Jim& imgSrc, Jim& imgWriter, AppFactory& app){
3664 Optionjl<unsigned int> band_opt("b", "band", "band index to crop (leave empty to retain all bands)");
3665 Optionjl<unsigned int> bstart_opt("sband", "startband", "Start band sequence number");
3666 Optionjl<unsigned int> bend_opt("eband", "endband", "End band sequence number");
3667 Optionjl<short> verbose_opt("v", "verbose", "verbose", 0,2);
3668
3669 bool doProcess;//stop process when program was invoked with help option (-h --help)
3670 try{
3671 doProcess=band_opt.retrieveOption(app);
3672 bstart_opt.retrieveOption(app);
3673 bend_opt.retrieveOption(app);
3674 verbose_opt.retrieveOption(app);
3675
3676 if(!doProcess){
3677 cout << endl;
3678 std::ostringstream helpStream;
3679 helpStream << "short option -h shows basic options only, use long option --help to show all options" << std::endl;
3680 throw(helpStream.str());//help was invoked, stop processing
3681 }
3682
3683 std::vector<std::string> badKeys;
3684 app.badKeys(badKeys);
3685 if(badKeys.size()){
3686 std::ostringstream errorStream;
3687 if(badKeys.size()>1)
3688 errorStream << "Error: unknown keys: ";
3689 else
3690 errorStream << "Error: unknown key: ";
3691 for(int ikey=0;ikey<badKeys.size();++ikey){
3692 errorStream << badKeys[ikey] << " ";
3693 }
3694 errorStream << std::endl;
3695 throw(errorStream.str());
3696 }
3697 }
3698 catch(string predefinedString){
3699 std::cerr << predefinedString << std::endl;
3700 throw;
3701 }
3702 if(bstart_opt.size()!=bend_opt.size()){
3703 std::cerr << "Error: size of start band is not equal to size of end band" << std::endl;
3704 throw;
3705 }
3706 std::vector<unsigned int> vband=band_opt;
3707 for(size_t ipair=0;ipair<bstart_opt.size();++ipair){
3708 if(bend_opt[ipair]<bstart_opt[ipair]){
3709 string errorstring="Error: index for start band must be smaller then end band";
3710 throw(errorstring);
3711 }
3712 for(size_t iband=bstart_opt[ipair];iband<=bend_opt[ipair];++iband)
3713 vband.push_back(iband);
3714 }
3715 if(vband.empty()){
3716 for(size_t iband=0;iband<imgSrc.nrOfBand();++iband)
3717 vband.push_back(iband);
3718 }
3719 if(vband.empty()){
3720 std::cerr << "Error: no bands selected" << std::endl;
3721 throw;
3722 }
3723 if(m_ncol!=imgSrc.nrOfCol()){
3724 std::string errorString="Error: number of columns do not match";
3725 throw(errorString);
3726 }
3727 if(m_nrow!=imgSrc.nrOfRow()){
3728 std::string errorString="Error: number of rows do not match";
3729 throw(errorString);
3730 }
3731 if(m_nplane!=imgSrc.nrOfPlane()){
3732 std::string errorString="Error: number of planes do not match";
3733 throw(errorString);
3734 }
3735 if(m_dataType!=imgSrc.getDataType()){
3736 std::string errorString="Error: data types do not match";
3737 throw(errorString);
3738 }
3739 imgWriter.open(nrOfCol(),nrOfRow(),nrOfBand()+vband.size(),nrOfPlane(),getGDALDataType());
3740 imgWriter.copyGeoTransform(*this);
3741 imgWriter.setProjection(this->getProjection());
3742 for(size_t iband=0;iband<nrOfBand();++iband){
3743 copyData(imgWriter.getDataPointer(iband),iband);
3744 }
3745 for(size_t iband=0;iband<vband.size();++iband){
3746 imgSrc.copyData(imgWriter.getDataPointer(nrOfBand()+iband),vband[iband]);
3747 }
3748 }
3749
3750 //destructive version of stack image to current image
3751 void Jim::d_stackBand(Jim& imgSrc, AppFactory& app){
3752 Optionjl<unsigned int> band_opt("b", "band", "band index to crop (leave empty to retain all bands)");
3753 Optionjl<unsigned int> bstart_opt("sband", "startband", "Start band sequence number");
3754 Optionjl<unsigned int> bend_opt("eband", "endband", "End band sequence number");
3755 Optionjl<short> verbose_opt("v", "verbose", "verbose", 0,2);
3756
3757 bool doProcess;//stop process when program was invoked with help option (-h --help)
3758 try{
3759 doProcess=band_opt.retrieveOption(app);
3760 bstart_opt.retrieveOption(app);
3761 bend_opt.retrieveOption(app);
3762 verbose_opt.retrieveOption(app);
3763
3764 if(!doProcess){
3765 cout << endl;
3766 std::ostringstream helpStream;
3767 helpStream << "short option -h shows basic options only, use long option --help to show all options" << std::endl;
3768 throw(helpStream.str());//help was invoked, stop processing
3769 }
3770
3771 std::vector<std::string> badKeys;
3772 app.badKeys(badKeys);
3773 if(badKeys.size()){
3774 std::ostringstream errorStream;
3775 if(badKeys.size()>1)
3776 errorStream << "Error: unknown keys: ";
3777 else
3778 errorStream << "Error: unknown key: ";
3779 for(int ikey=0;ikey<badKeys.size();++ikey){
3780 errorStream << badKeys[ikey] << " ";
3781 }
3782 errorStream << std::endl;
3783 throw(errorStream.str());
3784 }
3785 }
3786 catch(string predefinedString){
3787 std::cerr << predefinedString << std::endl;
3788 throw;
3789 }
3790 if(bstart_opt.size()!=bend_opt.size()){
3791 std::cerr << "Error: size of start band is not equal to size of end band" << std::endl;
3792 throw;
3793 }
3794 std::vector<unsigned int> vband=band_opt;
3795 for(size_t ipair=0;ipair<bstart_opt.size();++ipair){
3796 if(bend_opt[ipair]<bstart_opt[ipair]){
3797 string errorstring="Error: index for start band must be smaller then end band";
3798 throw(errorstring);
3799 }
3800 for(size_t iband=bstart_opt[ipair];iband<=bend_opt[ipair];++iband)
3801 vband.push_back(iband);
3802 }
3803 if(vband.empty()){
3804 for(size_t iband=0;iband<imgSrc.nrOfBand();++iband)
3805 vband.push_back(iband);
3806 }
3807 if(vband.empty()){
3808 std::cerr << "Error: no bands selected" << std::endl;
3809 throw;
3810 }
3811 if(m_ncol!=imgSrc.nrOfCol()){
3812 std::string errorString="Error: number of columns do not match";
3813 throw(errorString);
3814 }
3815 if(m_nrow!=imgSrc.nrOfRow()){
3816 std::string errorString="Error: number of rows do not match";
3817 throw(errorString);
3818 }
3819 if(m_nplane!=imgSrc.nrOfPlane()){
3820 std::string errorString="Error: number of planes do not match";
3821 throw(errorString);
3822 }
3823 if(m_dataType!=imgSrc.getDataType()){
3824 std::string errorString="Error: data types do not match";
3825 throw(errorString);
3826 }
3827 size_t oldnband=nrOfBand();
3828 m_data.resize(oldnband+vband.size());
3829 m_nband+=vband.size();
3830 m_begin.resize(oldnband+vband.size());
3831 m_end.resize(oldnband+vband.size());
3832 for(size_t iband=0;iband<vband.size();++iband){
3833 m_data[oldnband+iband]=(void *) calloc(static_cast<size_t>(imgSrc.nrOfPlane())*imgSrc.nrOfCol()*imgSrc.getBlockSize(),imgSrc.getDataTypeSizeBytes());
3834 m_begin[oldnband+iband]=0;
3835 m_end[oldnband+iband]=nrOfRow();
3836 imgSrc.copyData(getDataPointer(oldnband+iband),vband[iband]);
3837 }
3838 }
3839
3840 shared_ptr<Jim> JimList::stackBand(AppFactory& app){
3841 shared_ptr<Jim> imgWriter=Jim::createImg();
3842 stackBand(*imgWriter, app);
3843 return(imgWriter);
3844 }
3845
3846 void JimList::stackBand(Jim& imgWriter, AppFactory& app){
3847 Optionjl<unsigned int> band_opt("b", "band", "band index to crop (leave empty to retain all bands)");
3848 Optionjl<unsigned int> bstart_opt("sband", "startband", "Start band sequence number");
3849 Optionjl<unsigned int> bend_opt("eband", "endband", "End band sequence number");
3850 Optionjl<short> verbose_opt("v", "verbose", "verbose", 0,2);
3851
3852 bool doProcess;//stop process when program was invoked with help option (-h --help)
3853 try{
3854 doProcess=band_opt.retrieveOption(app);
3855 bstart_opt.retrieveOption(app);
3856 bend_opt.retrieveOption(app);
3857 verbose_opt.retrieveOption(app);
3858
3859 if(!doProcess){
3860 cout << endl;
3861 std::ostringstream helpStream;
3862 helpStream << "short option -h shows basic options only, use long option --help to show all options" << std::endl;
3863 throw(helpStream.str());//help was invoked, stop processing
3864 }
3865 if(empty()){
3866 std::ostringstream errorStream;
3867 errorStream << "Input collection is empty. Use --help for more help information" << std::endl;
3868 throw(errorStream.str());
3869 }
3870
3871 std::vector<std::string> badKeys;
3872 app.badKeys(badKeys);
3873 if(badKeys.size()){
3874 std::ostringstream errorStream;
3875 if(badKeys.size()>1)
3876 errorStream << "Error: unknown keys: ";
3877 else
3878 errorStream << "Error: unknown key: ";
3879 for(int ikey=0;ikey<badKeys.size();++ikey){
3880 errorStream << badKeys[ikey] << " ";
3881 }
3882 errorStream << std::endl;
3883 throw(errorStream.str());
3884 }
3885 std::list<std::shared_ptr<Jim> >::const_iterator imit=begin();
3886 bool initWriter=false;
3887
3888 std::vector<unsigned int> vband=band_opt;
3889 if(bstart_opt.size()!=bend_opt.size()){
3890 std::cerr << "Error: size of start band is not equal to size of end band" << std::endl;
3891 throw;
3892 }
3893 for(size_t ipair=0;ipair<bstart_opt.size();++ipair){
3894 if(bend_opt[ipair]<bstart_opt[ipair]){
3895 string errorstring="Error: index for start band must be smaller then end band";
3896 throw(errorstring);
3897 }
3898 for(size_t iband=bstart_opt[ipair];iband<=bend_opt[ipair];++iband)
3899 vband.push_back(iband);
3900 }
3901 size_t nband=vband.size()*getSize();
3902 if(!nband){
3903 for(imit=begin();imit!=end();++imit)
3904 nband+=(*imit)->nrOfBand();
3905 }
3906 imgWriter.open((*begin())->nrOfCol(),(*begin())->nrOfRow(),nband,(*begin())->nrOfPlane(),(*begin())->getGDALDataType());
3907 imgWriter.copyGeoTransform(*(*begin()));
3908 imgWriter.setProjection((*begin())->getProjection());
3909 size_t currentBand=0;
3910 for(imit=begin();imit!=end();++imit){
3911 if((*begin())->nrOfCol()!=imgWriter.nrOfCol()){
3912 std::string errorString="Error: number of columns do not match";
3913 throw(errorString);
3914 }
3915 if((*begin())->nrOfRow()!=imgWriter.nrOfRow()){
3916 std::string errorString="Error: number of rows do not match";
3917 throw(errorString);
3918 }
3919 if((*begin())->nrOfPlane()!=imgWriter.nrOfPlane()){
3920 std::string errorString="Error: number of planes do not match";
3921 throw(errorString);
3922 }
3923 if((*begin())->getDataType()!=imgWriter.getDataType()){
3924 std::string errorString="Error: data types do not match";
3925 throw(errorString);
3926 }
3927 if(!(*imit)){
3928 std::ostringstream errorStream;
3929 errorStream << "Error: image in list is empty"<< std::endl;
3930 throw(errorStream.str());
3931 }
3932 if(vband.size()){
3933 for(size_t iband=0;iband<vband.size();++iband){
3934 if(iband>=(*imit)->nrOfBand()){
3935 std::string errorString="Error: band number out of range";
3936 throw(errorString);
3937 }
3938
3939 (*imit)->copyData(imgWriter.getDataPointer(currentBand),vband[iband]);
3940 ++currentBand;
3941 }
3942 }
3943 else{
3944 for(size_t iband=0;iband<(*imit)->nrOfBand();++iband){
3945 (*imit)->copyData(imgWriter.getDataPointer(currentBand),iband);
3946 ++currentBand;
3947 }
3948 }
3949 }
3950 }
3951 catch(string predefinedString){
3952 std::cout << predefinedString << std::endl;
3953 throw;
3954 }
3955 }
3956
3957 //destructive version of stack image to current image
3958 void Jim::d_stackPlane(Jim& imgSrc, AppFactory& app){
3959 Optionjl<short> verbose_opt("v", "verbose", "verbose", 0,2);
3960
3961 bool doProcess;//stop process when program was invoked with help option (-h --help)
3962 try{
3963 doProcess=verbose_opt.retrieveOption(app);
3964
3965 if(!doProcess){
3966 cout << endl;
3967 std::ostringstream helpStream;
3968 helpStream << "short option -h shows basic options only, use long option --help to show all options" << std::endl;
3969 throw(helpStream.str());//help was invoked, stop processing
3970 }
3971
3972 std::vector<std::string> badKeys;
3973 app.badKeys(badKeys);
3974 if(badKeys.size()){
3975 std::ostringstream errorStream;
3976 if(badKeys.size()>1)
3977 errorStream << "Error: unknown keys: ";
3978 else
3979 errorStream << "Error: unknown key: ";
3980 for(int ikey=0;ikey<badKeys.size();++ikey){
3981 errorStream << badKeys[ikey] << " ";
3982 }
3983 errorStream << std::endl;
3984 throw(errorStream.str());
3985 }
3986 }
3987 catch(string predefinedString){
3988 std::cerr << predefinedString << std::endl;
3989 throw;
3990 }
3991 if(m_ncol!=imgSrc.nrOfCol()){
3992 std::string errorString="Error: number of columns do not match";
3993 throw(errorString);
3994 }
3995 if(m_nrow!=imgSrc.nrOfRow()){
3996 std::string errorString="Error: number of rows do not match";
3997 throw(errorString);
3998 }
3999 if(m_nband!=imgSrc.nrOfBand()){
4000 std::string errorString="Error: number of bands do not match";
4001 throw(errorString);
4002 }
4003 if(m_dataType!=imgSrc.getDataType()){
4004 std::string errorString="Error: data types do not match";
4005 throw(errorString);
4006 }
4007 size_t oldnplane=nrOfPlane();
4008 m_nplane+=imgSrc.nrOfPlane();
4009 for(size_t iband=0;iband<nrOfBand();++iband){
4010 void* newpointer=0;
4011 if(m_data[iband]==imgSrc.getDataPointer(iband)){
4012 newpointer=malloc(static_cast<size_t>(nrOfCol())*nrOfRow()*nrOfPlane()*getDataTypeSizeBytes());
4013 if(! newpointer){
4014 m_nplane=oldnplane;
4015 std::string errorString="Error: not sufficient memory for reallocation in stackPlane";
4016 throw(errorString);
4017 }
4018 memcpy((uint_least8_t*)(newpointer),(uint_least8_t*)(m_data[iband]),static_cast<size_t>(getDataTypeSizeBytes())*nrOfCol()*nrOfRow()*oldnplane);
4019 memcpy((uint_least8_t*)(newpointer)+static_cast<size_t>(getDataTypeSizeBytes())*nrOfCol()*nrOfRow()*oldnplane,(uint_least8_t*)(imgSrc.getDataPointer(iband)),static_cast<size_t>(imgSrc.getDataTypeSizeBytes())*imgSrc.nrOfCol()*imgSrc.nrOfRow()*oldnplane);
4020 m_data[iband]=newpointer;
4021 }
4022 else{
4023 newpointer=realloc(m_data[iband],static_cast<size_t>(nrOfCol())*nrOfRow()*nrOfPlane()*getDataTypeSizeBytes());
4024 if(! newpointer){
4025 m_nplane=oldnplane;
4026 std::string errorString="Error: not sufficient memory for reallocation in stackPlane";
4027 throw(errorString);
4028 }
4029 m_data[iband]=newpointer;
4030 memcpy((uint_least8_t*)(m_data[iband])+static_cast<size_t>(getDataTypeSizeBytes())*nrOfCol()*nrOfRow()*oldnplane,(uint_least8_t*)(imgSrc.getDataPointer(iband)),static_cast<size_t>(imgSrc.getDataTypeSizeBytes())*imgSrc.nrOfCol()*imgSrc.nrOfRow()*imgSrc.nrOfPlane());
4031 }
4032 }
4033 }
4034
4035
4036 shared_ptr<Jim> JimList::stackPlane(AppFactory& app){
4037 shared_ptr<Jim> imgWriter=Jim::createImg();
4038 stackPlane(*imgWriter, app);
4039 return(imgWriter);
4040 }
4041
4042 void JimList::stackPlane(Jim& imgWriter, AppFactory& app){
4043 Optionjl<short> verbose_opt("v", "verbose", "verbose", 0,2);
4044
4045 bool doProcess;//stop process when program was invoked with help option (-h --help)
4046 try{
4047 doProcess=verbose_opt.retrieveOption(app);
4048
4049 if(!doProcess){
4050 cout << endl;
4051 std::ostringstream helpStream;
4052 helpStream << "short option -h shows basic options only, use long option --help to show all options" << std::endl;
4053 throw(helpStream.str());//help was invoked, stop processing
4054 }
4055 if(empty()){
4056 std::ostringstream errorStream;
4057 errorStream << "Input collection is empty. Use --help for more help information" << std::endl;
4058 throw(errorStream.str());
4059 }
4060
4061 std::vector<std::string> badKeys;
4062 app.badKeys(badKeys);
4063 if(badKeys.size()){
4064 std::ostringstream errorStream;
4065 if(badKeys.size()>1)
4066 errorStream << "Error: unknown keys: ";
4067 else
4068 errorStream << "Error: unknown key: ";
4069 for(int ikey=0;ikey<badKeys.size();++ikey){
4070 errorStream << badKeys[ikey] << " ";
4071 }
4072 errorStream << std::endl;
4073 throw(errorStream.str());
4074 }
4075 std::list<std::shared_ptr<Jim> >::const_iterator imit=begin();
4076 bool initWriter=false;
4077
4078 size_t nplane=0;
4079 for(imit=begin();imit!=end();++imit)
4080 nplane+=(*imit)->nrOfPlane();
4081
4082 imgWriter.open((*begin())->nrOfCol(),(*begin())->nrOfRow(),(*begin())->nrOfBand(),nplane,(*begin())->getGDALDataType());
4083 imgWriter.copyGeoTransform(*(*begin()));
4084 imgWriter.setProjection((*begin())->getProjection());
4085 size_t currentBand=0;
4086 size_t iplane=0;
4087 for(imit=begin();imit!=end();++imit){
4088 if((*begin())->nrOfCol()!=imgWriter.nrOfCol()){
4089 std::string errorString="Error: number of columns do not match";
4090 throw(errorString);
4091 }
4092 if((*begin())->nrOfRow()!=imgWriter.nrOfRow()){
4093 std::string errorString="Error: number of rows do not match";
4094 throw(errorString);
4095 }
4096 if((*begin())->nrOfBand()!=imgWriter.nrOfBand()){
4097 std::string errorString="Error: number of bands do not match";
4098 throw(errorString);
4099 }
4100 if((*begin())->getDataType()!=imgWriter.getDataType()){
4101 std::string errorString="Error: data types do not match";
4102 throw(errorString);
4103 }
4104 if(!(*imit)){
4105 std::ostringstream errorStream;
4106 errorStream << "Error: image in list is empty"<< std::endl;
4107 throw(errorStream.str());
4108 }
4109 for(size_t iband=0;iband<imgWriter.nrOfBand();++iband){
4110 if(iband>=(*imit)->nrOfBand()){
4111 std::string errorString="Error: band number out of range";
4112 throw(errorString);
4113 }
4114 (*imit)->copyData((uint_least8_t*)(imgWriter.getDataPointer(iband))+imgWriter.nrOfCol()*imgWriter.nrOfRow()*iplane*imgWriter.getDataTypeSizeBytes(),iband);
4115 }
4116 iplane+=(*imit)->nrOfPlane();
4117 }
4118 }
4119 catch(string predefinedString){
4120 std::cout << predefinedString << std::endl;
4121 throw;
4122 }
4123 }
4124
4125 // shared_ptr<Jim> JimList::crop(AppFactory& app){
4126 // shared_ptr<Jim> imgWriter=Jim::createImg();
4127 // crop(*imgWriter, app);
4128 // return(imgWriter);
4129 // }
4130
4131 //todo: support extent a VectorOgr argument instead of option in app
4132 // JimList& JimList::crop(Jim& imgWriter, AppFactory& app){
4133 // Optionjl<string> projection_opt("a_srs", "a_srs", "Override the projection for the output file (leave blank to copy from input file, use epsg:3035 to use European projection and force to European grid");
4134 // //todo: support layer names
4135 // Optionjl<string> extent_opt("e", "extent", "get boundary from extent from polygons in vector file");
4136 // Optionjl<string> layer_opt("ln", "ln", "layer name of extent to crop");
4137 // Optionjl<bool> cut_to_cutline_opt("cut_to_cutline", "crop_to_cutline", "Crop the extent of the target dataset to the extent of the cutline, setting the outside area to nodata.",false);
4138 // Optionjl<bool> cut_in_cutline_opt("cut_in_cutline", "crop_in_cutline", "Crop the extent of the target dataset to the extent of the cutline, setting the inner area to nodata.",false);
4139 // 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");
4140 // Optionjl<string> mask_opt("m", "mask", "Use the the specified file as a validity mask (0 is nodata).");
4141 // Optionjl<double> msknodata_opt("msknodata", "msknodata", "Mask value not to consider for crop.", 0);
4142 // Optionjl<unsigned int> mskband_opt("mskband", "mskband", "Mask band to read (0 indexed)", 0);
4143 // Optionjl<double> ulx_opt("ulx", "ulx", "Upper left x value bounding box", 0.0);
4144 // Optionjl<double> uly_opt("uly", "uly", "Upper left y value bounding box", 0.0);
4145 // Optionjl<double> lrx_opt("lrx", "lrx", "Lower right x value bounding box", 0.0);
4146 // Optionjl<double> lry_opt("lry", "lry", "Lower right y value bounding box", 0.0);
4147 // Optionjl<double> dx_opt("dx", "dx", "Output resolution in x (in meter) (empty: keep original resolution)");
4148 // Optionjl<double> dy_opt("dy", "dy", "Output resolution in y (in meter) (empty: keep original resolution)");
4149 // Optionjl<double> cx_opt("x", "x", "x-coordinate of image center to crop (in meter)");
4150 // Optionjl<double> cy_opt("y", "y", "y-coordinate of image center to crop (in meter)");
4151 // Optionjl<double> nx_opt("nx", "nx", "image size in x to crop (in meter)");
4152 // Optionjl<double> ny_opt("ny", "ny", "image size in y to crop (in meter)");
4153 // Optionjl<unsigned int> ns_opt("ns", "ns", "number of samples to crop (in pixels)");
4154 // Optionjl<unsigned int> nl_opt("nl", "nl", "number of lines to crop (in pixels)");
4155 // Optionjl<unsigned int> band_opt("b", "band", "band index to crop (leave empty to retain all bands)");
4156 // Optionjl<unsigned int> bstart_opt("sband", "startband", "Start band sequence number");
4157 // Optionjl<unsigned int> bend_opt("eband", "endband", "End band sequence number");
4158 // Optionjl<double> autoscale_opt("as", "autoscale", "scale output to min and max, e.g., --autoscale 0 --autoscale 255");
4159 // Optionjl<double> scale_opt("scale", "scale", "output=scale*input+offset");
4160 // Optionjl<double> offset_opt("offset", "offset", "output=scale*input+offset");
4161 // 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");
4162 // // Optionjl<string> oformat_opt("of", "oformat", "Output image format (see also gdal_translate).","GTiff");
4163 // // Optionjl<string> option_opt("co", "co", "Creation option for output file. Multiple options can be specified.");
4164 // Optionjl<string> colorTable_opt("ct", "ct", "color table (file with 5 columns: id R G B ALFA (0: transparent, 255: solid)");
4165 // Optionjl<double> nodata_opt("nodata", "nodata", "Nodata value to put in image if out of bounds.");
4166 // Optionjl<string> resample_opt("r", "resample", "Resampling method (near: nearest neighbor, bilinear: bi-linear interpolation).", "near");
4167 // Optionjl<string> description_opt("d", "description", "Set image description");
4168 // Optionjl<bool> align_opt("align", "align", "Align output bounding box to input image",false);
4169 // Optionjl<short> verbose_opt("v", "verbose", "verbose", 0,2);
4170
4171 // extent_opt.setHide(1);
4172 // layer_opt.setHide(1);
4173 // cut_to_cutline_opt.setHide(1);
4174 // cut_in_cutline_opt.setHide(1);
4175 // eoption_opt.setHide(1);
4176 // bstart_opt.setHide(1);
4177 // bend_opt.setHide(1);
4178 // mask_opt.setHide(1);
4179 // msknodata_opt.setHide(1);
4180 // mskband_opt.setHide(1);
4181 // // option_opt.setHide(1);
4182 // cx_opt.setHide(1);
4183 // cy_opt.setHide(1);
4184 // nx_opt.setHide(1);
4185 // ny_opt.setHide(1);
4186 // ns_opt.setHide(1);
4187 // nl_opt.setHide(1);
4188 // scale_opt.setHide(1);
4189 // offset_opt.setHide(1);
4190 // nodata_opt.setHide(1);
4191 // description_opt.setHide(1);
4192
4193 // bool doProcess;//stop process when program was invoked with help option (-h --help)
4194 // try{
4195 // doProcess=projection_opt.retrieveOption(app);
4196 // ulx_opt.retrieveOption(app);
4197 // uly_opt.retrieveOption(app);
4198 // lrx_opt.retrieveOption(app);
4199 // lry_opt.retrieveOption(app);
4200 // band_opt.retrieveOption(app);
4201 // bstart_opt.retrieveOption(app);
4202 // bend_opt.retrieveOption(app);
4203 // autoscale_opt.retrieveOption(app);
4204 // otype_opt.retrieveOption(app);
4205 // // oformat_opt.retrieveOption(app);
4206 // colorTable_opt.retrieveOption(app);
4207 // dx_opt.retrieveOption(app);
4208 // dy_opt.retrieveOption(app);
4209 // resample_opt.retrieveOption(app);
4210 // extent_opt.retrieveOption(app);
4211 // layer_opt.retrieveOption(app);
4212 // cut_to_cutline_opt.retrieveOption(app);
4213 // cut_in_cutline_opt.retrieveOption(app);
4214 // eoption_opt.retrieveOption(app);
4215 // mask_opt.retrieveOption(app);
4216 // msknodata_opt.retrieveOption(app);
4217 // mskband_opt.retrieveOption(app);
4218 // // option_opt.retrieveOption(app);
4219 // cx_opt.retrieveOption(app);
4220 // cy_opt.retrieveOption(app);
4221 // nx_opt.retrieveOption(app);
4222 // ny_opt.retrieveOption(app);
4223 // ns_opt.retrieveOption(app);
4224 // nl_opt.retrieveOption(app);
4225 // scale_opt.retrieveOption(app);
4226 // offset_opt.retrieveOption(app);
4227 // nodata_opt.retrieveOption(app);
4228 // description_opt.retrieveOption(app);
4229 // align_opt.retrieveOption(app);
4230 // verbose_opt.retrieveOption(app);
4231
4232 // if(!doProcess){
4233 // cout << endl;
4234 // std::ostringstream helpStream;
4235 // helpStream << "short option -h shows basic options only, use long option --help to show all options" << std::endl;
4236 // throw(helpStream.str());//help was invoked, stop processing
4237 // }
4238 // if(empty()){
4239 // std::ostringstream errorStream;
4240 // errorStream << "Input collection is empty. Use --help for more help information" << std::endl;
4241 // throw(errorStream.str());
4242 // }
4243
4244
4245 // std::vector<std::string> badKeys;
4246 // app.badKeys(badKeys);
4247 // if(badKeys.size()){
4248 // std::ostringstream errorStream;
4249 // if(badKeys.size()>1)
4250 // errorStream << "Error: unknown keys: ";
4251 // else
4252 // errorStream << "Error: unknown key: ";
4253 // for(int ikey=0;ikey<badKeys.size();++ikey){
4254 // errorStream << badKeys[ikey] << " ";
4255 // }
4256 // errorStream << std::endl;
4257 // throw(errorStream.str());
4258 // }
4259
4260 // double nodataValue=nodata_opt.size()? nodata_opt[0] : 0;
4261 // RESAMPLE theResample;
4262 // if(resample_opt[0]=="near"){
4263 // theResample=NEAR;
4264 // if(verbose_opt[0])
4265 // cout << "resampling: nearest neighbor" << endl;
4266 // }
4267 // else if(resample_opt[0]=="bilinear"){
4268 // theResample=BILINEAR;
4269 // if(verbose_opt[0])
4270 // cout << "resampling: bilinear interpolation" << endl;
4271 // }
4272 // else{
4273 // std::ostringstream errorStream;
4274 // errorStream << "Error: resampling method " << resample_opt[0] << " not supported" << std::endl;
4275 // throw(errorStream.str());
4276 // // return(CE_Failure);
4277 // }
4278
4279 // const char* pszMessage;
4280 // void* pProgressArg=NULL;
4281 // GDALProgressFunc pfnProgress=GDALTermProgress;
4282 // double progress=0;
4283 // MyProgressFunc(progress,pszMessage,pProgressArg);
4284 // // ImgReaderGdal imgReader;
4285 // // ImgWriterGdal imgWriter;
4286 // //open input images to extract number of bands and spatial resolution
4287 // int ncropband=0;//total number of bands to write
4288 // double dx=0;
4289 // double dy=0;
4290 // if(dx_opt.size())
4291 // dx=dx_opt[0];
4292 // if(dy_opt.size())
4293 // dy=dy_opt[0];
4294
4295 // try{
4296 // //convert start and end band options to vector of band indexes
4297 // if(bstart_opt.size()){
4298 // if(bend_opt.size()!=bstart_opt.size()){
4299 // string errorstring="Error: options for start and end band indexes must be provided as pairs, missing end band";
4300 // throw(errorstring);
4301 // }
4302 // band_opt.clear();
4303 // for(int ipair=0;ipair<bstart_opt.size();++ipair){
4304 // if(bend_opt[ipair]<=bstart_opt[ipair]){
4305 // string errorstring="Error: index for end band must be smaller then start band";
4306 // throw(errorstring);
4307 // }
4308 // for(unsigned int iband=bstart_opt[ipair];iband<=bend_opt[ipair];++iband)
4309 // band_opt.push_back(iband);
4310 // }
4311 // }
4312 // }
4313 // catch(string error){
4314 // throw;
4315 // // return(CE_Failure);
4316 // }
4317
4318 // bool isGeoRef=false;
4319 // string projectionString;
4320 // // for(int iimg=0;iimg<input_opt.size();++iimg){
4321
4322 // // std::vector<std::shared_ptr<Jim> >::const_iterator imit=begin();
4323 // std::list<std::shared_ptr<Jim> >::const_iterator imit=begin();
4324
4325 // for(imit=begin();imit!=end();++imit){
4326 // //image must be georeferenced
4327 // if(!((*imit)->isGeoRef())){
4328 // string errorstring="Warning: input image is not georeferenced in JimList";
4329 // std::cerr << errorstring << std::endl;
4330 // // throw(errorstring);
4331 // }
4332 // // while((imgReader=getNextImage())){
4333 // // for(int iimg=0;iimg<imgReader.size();++iimg){
4334 // // try{
4335 // // }
4336 // // catch(string error){
4337 // // cerr << "Error: could not open file " << input_opt[iimg] << ": " << error << std::endl;
4338 // // exit(1);
4339 // // }
4340 // if(!isGeoRef)
4341 // isGeoRef=(*imit)->isGeoRef();
4342 // if((*imit)->isGeoRef()&&projection_opt.empty())
4343 // projectionString=(*imit)->getProjection();
4344 // if(dx_opt.empty()){
4345 // if(imit==begin()||(*imit)->getDeltaX()<dx)
4346 // dx=(*imit)->getDeltaX();
4347 // if(dx<=0){
4348 // string errorstring="Warning: pixel size in x has not been defined in input image";
4349 // std::cerr << errorstring << std::endl;
4350 // dx=1;
4351 // // throw(errorstring);
4352 // }
4353 // }
4354
4355 // if(dy_opt.empty()){
4356 // if(imit==begin()||(*imit)->getDeltaY()<dy)
4357 // dy=(*imit)->getDeltaY();
4358 // if(dy<=0){
4359 // string errorstring="Warning: pixel size in y has not been defined in input image";
4360 // std::cerr << errorstring << std::endl;
4361 // dy=1;
4362 // // throw(errorstring);
4363 // }
4364 // }
4365 // if(band_opt.size())
4366 // ncropband+=band_opt.size();
4367 // else
4368 // ncropband+=(*imit)->nrOfBand();
4369 // // (*imit)->close();
4370 // }
4371
4372 // GDALDataType theType=GDT_Unknown;
4373 // if(otype_opt.size()){
4374 // theType=string2GDAL(otype_opt[0]);
4375 // if(theType==GDT_Unknown)
4376 // std::cout << "Warning: unknown output pixel type: " << otype_opt[0] << ", using input type as default" << std::endl;
4377 // }
4378 // if(verbose_opt[0])
4379 // cout << "Output pixel type: " << GDALGetDataTypeName(theType) << endl;
4380
4381 // //bounding box of cropped image
4382 // double cropulx=ulx_opt[0];
4383 // double cropuly=uly_opt[0];
4384 // double croplrx=lrx_opt[0];
4385 // double croplry=lry_opt[0];
4386 // //get bounding box from extentReader if defined
4387 // VectorOgr extentReader;
4388
4389 // if(extent_opt.size()){
4390 // double e_ulx;
4391 // double e_uly;
4392 // double e_lrx;
4393 // double e_lry;
4394 // for(int iextent=0;iextent<extent_opt.size();++iextent){
4395 // extentReader.open(extent_opt[iextent],layer_opt,true);//noread=true
4396 // extentReader.getExtent(e_ulx,e_uly,e_lrx,e_lry);
4397 // if(!iextent){
4398 // ulx_opt[0]=e_ulx;
4399 // uly_opt[0]=e_uly;
4400 // lrx_opt[0]=e_lrx;
4401 // lry_opt[0]=e_lry;
4402 // }
4403 // else{
4404 // if(e_ulx<ulx_opt[0])
4405 // ulx_opt[0]=e_ulx;
4406 // if(e_uly>uly_opt[0])
4407 // uly_opt[0]=e_uly;
4408 // if(e_lrx>lrx_opt[0])
4409 // lrx_opt[0]=e_lrx;
4410 // if(e_lry<lry_opt[0])
4411 // lry_opt[0]=e_lry;
4412 // }
4413 // extentReader.close();
4414 // }
4415 // if(croplrx>cropulx&&cropulx>ulx_opt[0])
4416 // ulx_opt[0]=cropulx;
4417 // if(croplrx>cropulx&&croplrx<lrx_opt[0])
4418 // lrx_opt[0]=croplrx;
4419 // if(cropuly>croplry&&cropuly<uly_opt[0])
4420 // uly_opt[0]=cropuly;
4421 // if(croplry<cropuly&&croplry>lry_opt[0])
4422 // lry_opt[0]=croplry;
4423 // if(cut_to_cutline_opt[0]||cut_in_cutline_opt[0]||eoption_opt.size())
4424 // extentReader.open(extent_opt[0],layer_opt,true);
4425 // }
4426 // else if(cx_opt.size()&&cy_opt.size()&&nx_opt.size()&&ny_opt.size()){
4427 // ulx_opt[0]=cx_opt[0]-nx_opt[0]/2.0;
4428 // uly_opt[0]=(isGeoRef) ? cy_opt[0]+ny_opt[0]/2.0 : cy_opt[0]-ny_opt[0]/2.0;
4429 // lrx_opt[0]=cx_opt[0]+nx_opt[0]/2.0;
4430 // lry_opt[0]=(isGeoRef) ? cy_opt[0]-ny_opt[0]/2.0 : cy_opt[0]+ny_opt[0]/2.0;
4431 // }
4432 // else if(cx_opt.size()&&cy_opt.size()&&ns_opt.size()&&nl_opt.size()){
4433 // ulx_opt[0]=cx_opt[0]-ns_opt[0]*dx/2.0;
4434 // uly_opt[0]=(isGeoRef) ? cy_opt[0]+nl_opt[0]*dy/2.0 : cy_opt[0]-nl_opt[0]*dy/2.0;
4435 // lrx_opt[0]=cx_opt[0]+ns_opt[0]*dx/2.0;
4436 // lry_opt[0]=(isGeoRef) ? cy_opt[0]-nl_opt[0]*dy/2.0 : cy_opt[0]+nl_opt[0]*dy/2.0;
4437 // }
4438
4439 // if(verbose_opt[0])
4440 // cout << "--ulx=" << ulx_opt[0] << " --uly=" << uly_opt[0] << " --lrx=" << lrx_opt[0] << " --lry=" << lry_opt[0] << endl;
4441
4442 // int ncropcol=0;
4443 // int ncroprow=0;
4444
4445 // Jim maskReader;
4446 // if(extent_opt.size()&&(cut_to_cutline_opt[0]||cut_in_cutline_opt[0]||eoption_opt.size())){
4447 // if(mask_opt.size()){
4448 // string errorString="Error: can only either mask or extent extent with cut_to_cutline / cut_in_cutline, not both";
4449 // throw(errorString);
4450 // }
4451 // try{
4452 // // ncropcol=abs(static_cast<unsigned int>(ceil((lrx_opt[0]-ulx_opt[0])/dx)));
4453 // // ncroprow=abs(static_cast<unsigned int>(ceil((uly_opt[0]-lry_opt[0])/dy)));
4454 // ncropcol=static_cast<unsigned int>(ceil((lrx_opt[0]-ulx_opt[0])/dx));
4455 // ncroprow=static_cast<unsigned int>(ceil((uly_opt[0]-lry_opt[0])/dy));
4456 // maskReader.open(ncropcol,ncroprow,1,GDT_Float64);
4457 // double gt[6];
4458 // gt[0]=ulx_opt[0];
4459 // gt[1]=dx;
4460 // gt[2]=0;
4461 // gt[3]=uly_opt[0];
4462 // gt[4]=0;
4463 // gt[5]=-dy;
4464 // maskReader.setGeoTransform(gt);
4465 // if(projection_opt.size())
4466 // maskReader.setProjectionProj4(projection_opt[0]);
4467 // else if(projectionString.size())
4468 // maskReader.setProjection(projectionString);
4469
4470 // // vector<double> burnValues(1,1);//burn value is 1 (single band)
4471 // // maskReader.rasterizeBuf(extentReader,msknodata_opt[0],eoption_opt,layer_opt);
4472 // maskReader.rasterizeBuf(extentReader,1,eoption_opt,layer_opt);
4473
4474 // // if(eoption_opt.size())
4475 // // maskReader.rasterizeBuf(extentReader,eoption_opt);
4476 // // else
4477 // // maskReader.rasterizeBuf(extentReader);
4478 // }
4479 // catch(string error){
4480 // throw;
4481 // // return(CE_Failure);
4482 // }
4483 // }
4484 // else if(mask_opt.size()==1){
4485 // try{
4486 // //there is only a single mask
4487 // maskReader.open(mask_opt[0]);
4488 // if(mskband_opt[0]>=maskReader.nrOfBand()){
4489 // string errorString="Error: illegal mask band";
4490 // throw(errorString);
4491 // }
4492 // }
4493 // catch(string error){
4494 // throw;
4495 // // return(CE_Failure);
4496 // }
4497 // }
4498
4499 // //determine number of output bands
4500 // int writeBand=0;//write band
4501
4502 // if(scale_opt.size()){
4503 // while(scale_opt.size()<band_opt.size())
4504 // scale_opt.push_back(scale_opt[0]);
4505 // }
4506 // if(offset_opt.size()){
4507 // while(offset_opt.size()<band_opt.size())
4508 // offset_opt.push_back(offset_opt[0]);
4509 // }
4510 // if(autoscale_opt.size()){
4511 // assert(autoscale_opt.size()%2==0);
4512 // }
4513
4514 // // for(int iimg=0;iimg<input_opt.size();++iimg){
4515 // for(imit=begin();imit!=end();++imit){
4516 // // for(int iimg=0;iimg<imgReader.size();++iimg){
4517 // // if(verbose_opt[0])
4518 // // cout << "opening image " << input_opt[iimg] << endl;
4519 // // try{
4520 // // }
4521 // // catch(string error){
4522 // // cerr << error << std::endl;
4523 // // exit(2);
4524 // // }
4525 // //if output type not set, get type from input image
4526 // if(theType==GDT_Unknown){
4527 // theType=(*imit)->getGDALDataType();
4528 // if(verbose_opt[0])
4529 // cout << "Using data type from input image: " << GDALGetDataTypeName(theType) << endl;
4530 // }
4531 // // if(option_opt.findSubstring("INTERLEAVE=")==option_opt.end()){
4532 // // string theInterleave="INTERLEAVE=";
4533 // // theInterleave+=(*imit)->getInterleave();
4534 // // option_opt.push_back(theInterleave);
4535 // // }
4536 // // if(verbose_opt[0])
4537 // // cout << "size of " << input_opt[iimg] << ": " << ncol << " cols, "<< nrow << " rows" << endl;
4538 // double uli,ulj,lri,lrj;//image coordinates
4539 // bool forceEUgrid=false;
4540 // if(projection_opt.size())
4541 // forceEUgrid=(!(projection_opt[0].compare("EPSG:3035"))||!(projection_opt[0].compare("EPSG:3035"))||projection_opt[0].find("ETRS-LAEA")!=string::npos);
4542 // if(ulx_opt[0]>=lrx_opt[0]){//default bounding box: no cropping
4543 // uli=0;
4544 // lri=(*imit)->nrOfCol()-1;
4545 // ulj=0;
4546 // lrj=(*imit)->nrOfRow()-1;
4547 // ncropcol=(*imit)->nrOfCol();
4548 // ncroprow=(*imit)->nrOfRow();
4549 // (*imit)->getBoundingBox(cropulx,cropuly,croplrx,croplry);
4550 // double magicX=1,magicY=1;
4551 // // (*imit)->getMagicPixel(magicX,magicY);
4552 // if(forceEUgrid){
4553 // //force to LAEA grid
4554 // Egcs egcs;
4555 // egcs.setLevel(egcs.res2level(dx));
4556 // egcs.force2grid(cropulx,cropuly,croplrx,croplry);
4557 // (*imit)->geo2image(cropulx+(magicX-1.0)*(*imit)->getDeltaX(),cropuly-(magicY-1.0)*(*imit)->getDeltaY(),uli,ulj);
4558 // (*imit)->geo2image(croplrx+(magicX-2.0)*(*imit)->getDeltaX(),croplry-(magicY-2.0)*(*imit)->getDeltaY(),lri,lrj);
4559 // }
4560 // (*imit)->geo2image(cropulx+(magicX-1.0)*(*imit)->getDeltaX(),cropuly-(magicY-1.0)*(*imit)->getDeltaY(),uli,ulj);
4561 // (*imit)->geo2image(croplrx+(magicX-2.0)*(*imit)->getDeltaX(),croplry-(magicY-2.0)*(*imit)->getDeltaY(),lri,lrj);
4562 // // ncropcol=abs(static_cast<unsigned int>(ceil((croplrx-cropulx)/dx)));
4563 // // ncroprow=abs(static_cast<unsigned int>(ceil((cropuly-croplry)/dy)));
4564 // ncropcol=static_cast<unsigned int>(ceil((croplrx-cropulx)/dx));
4565 // ncroprow=static_cast<unsigned int>(ceil((cropuly-croplry)/dy));
4566 // if(verbose_opt[0]){
4567 // cout << "default bounding box" << endl;
4568 // cout << "ulx_opt[0]: " << ulx_opt[0]<< endl;
4569 // cout << "uly_opt[0]: " << uly_opt[0]<< endl;
4570 // cout << "lrx_opt[0]: " << lrx_opt[0]<< endl;
4571 // cout << "lry_opt[0]: " << lry_opt[0]<< endl;
4572 // cout << "croplrx,cropulx: " << croplrx << "," << cropulx << endl;
4573 // cout << "dx: " << dx << endl;
4574 // cout << "cropuly,croplry: " << cropuly << "," << croplry << endl;
4575 // cout << "dy: " << dy << endl;
4576 // cout << "filename: " << (*imit)->getFileName() << endl;
4577 // }
4578 // }
4579 // else{
4580 // double magicX=1,magicY=1;
4581 // // (*imit)->getMagicPixel(magicX,magicY);
4582 // cropulx=ulx_opt[0];
4583 // cropuly=uly_opt[0];
4584 // croplrx=lrx_opt[0];
4585 // croplry=lry_opt[0];
4586 // if(forceEUgrid){
4587 // //force to LAEA grid
4588 // Egcs egcs;
4589 // egcs.setLevel(egcs.res2level(dx));
4590 // egcs.force2grid(cropulx,cropuly,croplrx,croplry);
4591 // }
4592 // else if(align_opt[0]){
4593 // if(cropulx>(*imit)->getUlx())
4594 // cropulx-=fmod(cropulx-(*imit)->getUlx(),dx);
4595 // else if(cropulx<(*imit)->getUlx())
4596 // cropulx+=fmod((*imit)->getUlx()-cropulx,dx)-dx;
4597 // if(croplrx<(*imit)->getLrx())
4598 // croplrx+=fmod((*imit)->getLrx()-croplrx,dx);
4599 // else if(croplrx>(*imit)->getLrx())
4600 // croplrx-=fmod(croplrx-(*imit)->getLrx(),dx)+dx;
4601 // if(croplry>(*imit)->getLry())
4602 // croplry-=fmod(croplry-(*imit)->getLry(),dy);
4603 // else if(croplry<(*imit)->getLry())
4604 // croplry+=fmod((*imit)->getLry()-croplry,dy)-dy;
4605 // if(cropuly<(*imit)->getUly())
4606 // cropuly+=fmod((*imit)->getUly()-cropuly,dy);
4607 // else if(cropuly>(*imit)->getUly())
4608 // cropuly-=fmod(cropuly-(*imit)->getUly(),dy)+dy;
4609 // }
4610 // (*imit)->geo2image(cropulx+(magicX-1.0)*(*imit)->getDeltaX(),cropuly-(magicY-1.0)*(*imit)->getDeltaY(),uli,ulj);
4611 // (*imit)->geo2image(croplrx+(magicX-2.0)*(*imit)->getDeltaX(),croplry-(magicY-2.0)*(*imit)->getDeltaY(),lri,lrj);
4612
4613 // // ncropcol=abs(static_cast<unsigned int>(ceil((croplrx-cropulx)/dx)));
4614 // // ncroprow=abs(static_cast<unsigned int>(ceil((cropuly-croplry)/dy)));
4615 // ncropcol=static_cast<unsigned int>(ceil((croplrx-cropulx)/dx));
4616 // ncroprow=static_cast<unsigned int>(ceil((cropuly-croplry)/dy));
4617 // uli=floor(uli);
4618 // ulj=floor(ulj);
4619 // lri=floor(lri);
4620 // lrj=floor(lrj);
4621 // }
4622
4623 // // double deltaX=(*imit)->getDeltaX();
4624 // // double deltaY=(*imit)->getDeltaY();
4625 // if(!imgWriter.nrOfBand()){//not opened yet
4626 // if(verbose_opt[0]){
4627 // cout << "cropulx: " << cropulx << endl;
4628 // cout << "cropuly: " << cropuly << endl;
4629 // cout << "croplrx: " << croplrx << endl;
4630 // cout << "croplry: " << croplry << endl;
4631 // cout << "ncropcol: " << ncropcol << endl;
4632 // cout << "ncroprow: " << ncroprow << endl;
4633 // cout << "cropulx+ncropcol*dx: " << cropulx+ncropcol*dx << endl;
4634 // cout << "cropuly-ncroprow*dy: " << cropuly-ncroprow*dy << endl;
4635 // cout << "upper left column of input image: " << uli << endl;
4636 // cout << "upper left row of input image: " << ulj << endl;
4637 // cout << "lower right column of input image: " << lri << endl;
4638 // cout << "lower right row of input image: " << lrj << endl;
4639 // cout << "new number of cols: " << ncropcol << endl;
4640 // cout << "new number of rows: " << ncroprow << endl;
4641 // cout << "new number of bands: " << ncropband << endl;
4642 // }
4643 // // string imageType;//=(*imit)->getImageType();
4644 // // if(oformat_opt.size())//default
4645 // // imageType=oformat_opt[0];
4646 // try{
4647 // imgWriter.open(ncropcol,ncroprow,ncropband,theType);
4648 // imgWriter.setNoData(nodata_opt);
4649 // // if(nodata_opt.size()){
4650 // // imgWriter.setNoData(nodata_opt);
4651 // // }
4652 // }
4653 // catch(string errorstring){
4654 // throw;
4655 // // cout << errorstring << endl;
4656 // // return(CE_Failure);
4657 // }
4658 // if(description_opt.size())
4659 // imgWriter.setImageDescription(description_opt[0]);
4660 // double gt[6];
4661 // gt[0]=cropulx;
4662 // gt[1]=dx;
4663 // gt[2]=0;
4664 // gt[3]=cropuly;
4665 // gt[4]=0;
4666 // gt[5]=((*imit)->isGeoRef())? -dy : dy;
4667 // imgWriter.setGeoTransform(gt);
4668 // if(projection_opt.size()){
4669 // if(verbose_opt[0])
4670 // cout << "projection: " << projection_opt[0] << endl;
4671 // imgWriter.setProjectionProj4(projection_opt[0]);
4672 // }
4673 // else
4674 // imgWriter.setProjection((*imit)->getProjection());
4675 // if(imgWriter.getDataType()==GDT_Byte){
4676 // if(colorTable_opt.size()){
4677 // if(colorTable_opt[0]!="none")
4678 // imgWriter.setColorTable(colorTable_opt[0]);
4679 // }
4680 // else if ((*imit)->getColorTable()!=NULL)//copy colorTable from input image
4681 // imgWriter.setColorTable((*imit)->getColorTable());
4682 // }
4683 // }
4684
4685 // double startCol=uli;
4686 // double endCol=lri;
4687 // if(uli<0)
4688 // startCol=0;
4689 // else if(uli>=(*imit)->nrOfCol())
4690 // startCol=(*imit)->nrOfCol()-1;
4691 // if(lri<0)
4692 // endCol=0;
4693 // else if(lri>=(*imit)->nrOfCol())
4694 // endCol=(*imit)->nrOfCol()-1;
4695 // double startRow=ulj;
4696 // double endRow=lrj;
4697 // if(ulj<0)
4698 // startRow=0;
4699 // else if(ulj>=(*imit)->nrOfRow())
4700 // startRow=(*imit)->nrOfRow()-1;
4701 // if(lrj<0)
4702 // endRow=0;
4703 // else if(lrj>=(*imit)->nrOfRow())
4704 // endRow=(*imit)->nrOfRow()-1;
4705
4706 // vector<double> readBuffer;
4707 // unsigned int nband=(band_opt.size())?band_opt.size() : (*imit)->nrOfBand();
4708 // for(unsigned int iband=0;iband<nband;++iband){
4709 // unsigned int readBand=(band_opt.size()>iband)?band_opt[iband]:iband;
4710 // if(verbose_opt[0]){
4711 // cout << "extracting band " << readBand << endl;
4712 // MyProgressFunc(progress,pszMessage,pProgressArg);
4713 // }
4714 // double theMin=0;
4715 // double theMax=0;
4716 // if(autoscale_opt.size()){
4717 // try{
4718 // (*imit)->getMinMax(static_cast<unsigned int>(startCol),static_cast<unsigned int>(endCol),static_cast<unsigned int>(startRow),static_cast<unsigned int>(endRow),readBand,theMin,theMax);
4719 // }
4720 // catch(string errorString){
4721 // cout << errorString << endl;
4722 // }
4723 // if(verbose_opt[0])
4724 // cout << "minmax: " << theMin << ", " << theMax << endl;
4725 // double theScale=(autoscale_opt[1]-autoscale_opt[0])/(theMax-theMin);
4726 // double theOffset=autoscale_opt[0]-theScale*theMin;
4727 // (*imit)->setScale(theScale,readBand);
4728 // (*imit)->setOffset(theOffset,readBand);
4729 // }
4730 // else{
4731 // if(scale_opt.size()){
4732 // if(scale_opt.size()>iband)
4733 // (*imit)->setScale(scale_opt[iband],readBand);
4734 // else
4735 // (*imit)->setScale(scale_opt[0],readBand);
4736 // }
4737 // if(offset_opt.size()){
4738 // if(offset_opt.size()>iband)
4739 // (*imit)->setOffset(offset_opt[iband],readBand);
4740 // else
4741 // (*imit)->setOffset(offset_opt[0],readBand);
4742 // }
4743 // }
4744
4745 // double readRow=0;
4746 // double readCol=0;
4747 // double lowerCol=0;
4748 // double upperCol=0;
4749 // for(int irow=0;irow<imgWriter.nrOfRow();++irow){
4750 // vector<double> lineMask;
4751 // double x=0;
4752 // double y=0;
4753 // //convert irow to geo
4754 // imgWriter.image2geo(0,irow,x,y);
4755 // //lookup corresponding row for irow in this file
4756 // (*imit)->geo2image(x,y,readCol,readRow);
4757 // vector<double> writeBuffer;
4758 // if(readRow<0||readRow>=(*imit)->nrOfRow()){
4759 // for(int icol=0;icol<imgWriter.nrOfCol();++icol)
4760 // writeBuffer.push_back(nodataValue);
4761 // }
4762 // else{
4763 // try{
4764 // if(endCol<(*imit)->nrOfCol()-1){
4765 // (*imit)->readData(readBuffer,startCol,endCol+1,readRow,readBand,theResample);
4766 // }
4767 // else{
4768 // (*imit)->readData(readBuffer,startCol,endCol,readRow,readBand,theResample);
4769 // }
4770 // double oldRowMask=-1;//keep track of row mask to optimize number of line readings
4771 // for(int icol=0;icol<imgWriter.nrOfCol();++icol){
4772 // imgWriter.image2geo(icol,irow,x,y);
4773 // //lookup corresponding row for irow in this file
4774 // (*imit)->geo2image(x,y,readCol,readRow);
4775 // if(readCol<0||readCol>=(*imit)->nrOfCol()){
4776 // writeBuffer.push_back(nodataValue);
4777 // }
4778 // else{
4779 // bool valid=true;
4780 // double geox=0;
4781 // double geoy=0;
4782 // if(maskReader.isInit()){
4783 // //read mask
4784 // double colMask=0;
4785 // double rowMask=0;
4786
4787 // imgWriter.image2geo(icol,irow,geox,geoy);
4788 // maskReader.geo2image(geox,geoy,colMask,rowMask);
4789 // colMask=static_cast<unsigned int>(colMask);
4790 // rowMask=static_cast<unsigned int>(rowMask);
4791 // if(rowMask>=0&&rowMask<maskReader.nrOfRow()&&colMask>=0&&colMask<maskReader.nrOfCol()){
4792 // if(static_cast<unsigned int>(rowMask)!=static_cast<unsigned int>(oldRowMask)){
4793
4794 // try{
4795 // maskReader.readData(lineMask,static_cast<unsigned int>(rowMask),mskband_opt[0]);
4796 // }
4797 // catch(string errorstring){
4798 // throw;
4799 // // cerr << errorstring << endl;
4800 // // return(CE_Failure);
4801 // }
4802 // catch(...){
4803 // std::string errorString="error caught";
4804 // throw;
4805 // // cerr << "error caught" << std::endl;
4806 // // return(CE_Failure);
4807 // }
4808 // oldRowMask=rowMask;
4809 // }
4810 // if(cut_to_cutline_opt[0]){
4811 // if(lineMask[colMask]!=1){
4812 // nodataValue=nodata_opt[0];
4813 // valid=false;
4814 // }
4815 // }
4816 // else if(cut_in_cutline_opt[0]){
4817 // if(lineMask[colMask]==1){
4818 // nodataValue=nodata_opt[0];
4819 // valid=false;
4820 // }
4821 // }
4822 // else{
4823 // for(int ivalue=0;ivalue<msknodata_opt.size();++ivalue){
4824 // if(lineMask[colMask]==msknodata_opt[ivalue]){
4825 // if(nodata_opt.size()>ivalue)
4826 // nodataValue=nodata_opt[ivalue];
4827 // valid=false;
4828 // break;
4829 // }
4830 // }
4831 // }
4832 // }
4833 // }
4834 // if(!valid)
4835 // writeBuffer.push_back(nodataValue);
4836 // else{
4837 // switch(theResample){
4838 // case(BILINEAR):
4839 // lowerCol=readCol-0.5;
4840 // lowerCol=static_cast<unsigned int>(lowerCol);
4841 // upperCol=readCol+0.5;
4842 // upperCol=static_cast<unsigned int>(upperCol);
4843 // if(lowerCol<0)
4844 // lowerCol=0;
4845 // if(upperCol>=(*imit)->nrOfCol())
4846 // upperCol=(*imit)->nrOfCol()-1;
4847 // writeBuffer.push_back((readCol-0.5-lowerCol)*readBuffer[upperCol-startCol]+(1-readCol+0.5+lowerCol)*readBuffer[lowerCol-startCol]);
4848 // break;
4849 // default:
4850 // readCol=static_cast<unsigned int>(readCol);
4851 // readCol-=startCol;//we only start reading from startCol
4852 // writeBuffer.push_back(readBuffer[readCol]);
4853 // break;
4854 // }
4855 // }
4856 // }
4857 // }
4858 // }
4859 // catch(string errorstring){
4860 // throw;
4861 // // cout << errorstring << endl;
4862 // // return(CE_Failure);
4863 // }
4864 // }
4865 // if(writeBuffer.size()!=imgWriter.nrOfCol())
4866 // cout << "writeBuffer.size()=" << writeBuffer.size() << ", imgWriter.nrOfCol()=" << imgWriter.nrOfCol() << endl;
4867
4868 // assert(writeBuffer.size()==imgWriter.nrOfCol());
4869 // try{
4870 // imgWriter.writeData(writeBuffer,irow,writeBand);
4871 // }
4872 // catch(string errorstring){
4873 // throw;
4874 // // cout << errorstring << endl;
4875 // // return(CE_Failure);
4876 // }
4877 // if(verbose_opt[0]){
4878 // progress=(1.0+irow);
4879 // progress/=imgWriter.nrOfRow();
4880 // MyProgressFunc(progress,pszMessage,pProgressArg);
4881 // }
4882 // else{
4883 // progress=(1.0+irow);
4884 // progress+=(imgWriter.nrOfRow()*writeBand);
4885 // progress/=imgWriter.nrOfBand()*imgWriter.nrOfRow();
4886 // assert(progress>=0);
4887 // assert(progress<=1);
4888 // MyProgressFunc(progress,pszMessage,pProgressArg);
4889 // }
4890 // }
4891 // ++writeBand;
4892 // }
4893 // // (*imit)->close();
4894 // }
4895 // if(extent_opt.size()&&(cut_to_cutline_opt[0]||cut_in_cutline_opt[0]||eoption_opt.size())){
4896 // extentReader.close();
4897 // }
4898 // if(maskReader.isInit())
4899 // maskReader.close();
4900 // // return(CE_None);
4901 // }
4902 // catch(string predefinedString){
4903 // std::cout << predefinedString << std::endl;
4904 // throw;
4905 // }
4906 // return(*this);
4907 // }