26 #include "imageclasses/ImgWriterGdal.h"
27 #include "imageclasses/ImgReaderGdal.h"
28 #include "imageclasses/ImgReaderOgr.h"
29 #include "base/Optionpk.h"
30 #include "algorithms/Egcs.h"
96 int main(
int argc,
char *argv[])
98 Optionpk<string> input_opt(
"i",
"input",
"Input image file(s). If input contains multiple images, a multi-band output is created");
100 Optionpk<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");
102 Optionpk<string> extent_opt(
"e",
"extent",
"get boundary from extent from polygons in vector file");
103 Optionpk<bool> cut_opt(
"cut",
"crop_to_cutline",
"Crop the extent of the target dataset to the extent of the cutline.",
false);
104 Optionpk<string> mask_opt(
"m",
"mask",
"Use the first band of the specified file as a validity mask (0 is nodata).");
105 Optionpk<double> ulx_opt(
"ulx",
"ulx",
"Upper left x value bounding box", 0.0);
106 Optionpk<double> uly_opt(
"uly",
"uly",
"Upper left y value bounding box", 0.0);
107 Optionpk<double> lrx_opt(
"lrx",
"lrx",
"Lower right x value bounding box", 0.0);
108 Optionpk<double> lry_opt(
"lry",
"lry",
"Lower right y value bounding box", 0.0);
109 Optionpk<double> dx_opt(
"dx",
"dx",
"Output resolution in x (in meter) (empty: keep original resolution)");
110 Optionpk<double> dy_opt(
"dy",
"dy",
"Output resolution in y (in meter) (empty: keep original resolution)");
111 Optionpk<double> cx_opt(
"x",
"x",
"x-coordinate of image center to crop (in meter)");
112 Optionpk<double> cy_opt(
"y",
"y",
"y-coordinate of image center to crop (in meter)");
115 Optionpk<int> ns_opt(
"ns",
"ns",
"number of samples to crop (in pixels)");
116 Optionpk<int> nl_opt(
"nl",
"nl",
"number of lines to crop (in pixels)");
117 Optionpk<int> band_opt(
"b",
"band",
"band index to crop (leave empty to retain all bands)");
118 Optionpk<double> autoscale_opt(
"as",
"autoscale",
"scale output to min and max, e.g., --autoscale 0 --autoscale 255");
121 Optionpk<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",
"");
122 Optionpk<string> oformat_opt(
"of",
"oformat",
"Output image format (see also gdal_translate). Empty string: inherit from input image");
123 Optionpk<string> option_opt(
"co",
"co",
"Creation option for output file. Multiple options can be specified.");
124 Optionpk<string> colorTable_opt(
"ct",
"ct",
"color table (file with 5 columns: id R G B ALFA (0: transparent, 255: solid)");
125 Optionpk<float> nodata_opt(
"nodata",
"nodata",
"Nodata value to put in image if out of bounds.");
126 Optionpk<string> resample_opt(
"r",
"resampling-method",
"Resampling method (near: nearest neighbor, bilinear: bi-linear interpolation).",
"near");
127 Optionpk<string> description_opt(
"d",
"description",
"Set image description");
130 extent_opt.setHide(1);
133 option_opt.setHide(1);
140 scale_opt.setHide(1);
141 offset_opt.setHide(1);
142 nodata_opt.setHide(1);
143 description_opt.setHide(1);
147 doProcess=input_opt.retrieveOption(argc,argv);
148 output_opt.retrieveOption(argc,argv);
149 projection_opt.retrieveOption(argc,argv);
150 ulx_opt.retrieveOption(argc,argv);
151 uly_opt.retrieveOption(argc,argv);
152 lrx_opt.retrieveOption(argc,argv);
153 lry_opt.retrieveOption(argc,argv);
154 band_opt.retrieveOption(argc,argv);
155 autoscale_opt.retrieveOption(argc,argv);
156 otype_opt.retrieveOption(argc,argv);
157 oformat_opt.retrieveOption(argc,argv);
158 colorTable_opt.retrieveOption(argc,argv);
159 dx_opt.retrieveOption(argc,argv);
160 dy_opt.retrieveOption(argc,argv);
161 resample_opt.retrieveOption(argc,argv);
162 extent_opt.retrieveOption(argc,argv);
163 cut_opt.retrieveOption(argc,argv);
164 mask_opt.retrieveOption(argc,argv);
165 option_opt.retrieveOption(argc,argv);
166 cx_opt.retrieveOption(argc,argv);
167 cy_opt.retrieveOption(argc,argv);
168 nx_opt.retrieveOption(argc,argv);
169 ny_opt.retrieveOption(argc,argv);
170 ns_opt.retrieveOption(argc,argv);
171 nl_opt.retrieveOption(argc,argv);
172 scale_opt.retrieveOption(argc,argv);
173 offset_opt.retrieveOption(argc,argv);
174 nodata_opt.retrieveOption(argc,argv);
175 description_opt.retrieveOption(argc,argv);
176 verbose_opt.retrieveOption(argc,argv);
178 catch(
string predefinedString){
179 std::cout << predefinedString << std::endl;
183 cout << setprecision(12) <<
"--ulx=" << ulx_opt[0] <<
" --uly=" << uly_opt[0] <<
" --lrx=" << lrx_opt[0] <<
" --lry=" << lry_opt[0] << endl;
187 cout <<
"Usage: pkcrop -i input -o output" << endl;
189 std::cout <<
"short option -h shows basic options only, use long option --help to show all options" << std::endl;
192 if(input_opt.empty()){
193 std::cerr <<
"No input file provided (use option -i). Use --help for help information" << std::endl;
196 if(output_opt.empty()){
197 std::cerr <<
"No output file provided (use option -o). Use --help for help information" << std::endl;
201 float nodataValue=nodata_opt.size()? nodata_opt[0] : 0;
202 RESAMPLE theResample;
203 if(resample_opt[0]==
"near"){
206 cout <<
"resampling: nearest neighbor" << endl;
208 else if(resample_opt[0]==
"bilinear"){
209 theResample=BILINEAR;
211 cout <<
"resampling: bilinear interpolation" << endl;
214 std::cout <<
"Error: resampling method " << resample_opt[0] <<
" not supported" << std::endl;
218 const char* pszMessage;
219 void* pProgressArg=NULL;
220 GDALProgressFunc pfnProgress=GDALTermProgress;
222 pfnProgress(progress,pszMessage,pProgressArg);
235 string projectionString;
236 for(
int iimg=0;iimg<input_opt.size();++iimg){
237 imgReader.open(input_opt[iimg]);
239 isGeoRef=imgReader.isGeoRef();
240 if(imgReader.isGeoRef()&&projection_opt.empty())
241 projectionString=imgReader.getProjection();
243 if(!iimg||imgReader.getDeltaX()<dx)
244 dx=imgReader.getDeltaX();
247 if(!iimg||imgReader.getDeltaY()<dy)
248 dy=imgReader.getDeltaY();
251 ncropband+=band_opt.size();
253 ncropband+=imgReader.nrOfBand();
257 GDALDataType theType=GDT_Unknown;
259 cout <<
"possible output data types: ";
260 for(
int iType = 0; iType < GDT_TypeCount; ++iType){
262 cout <<
" " << GDALGetDataTypeName((GDALDataType)iType);
263 if( GDALGetDataTypeName((GDALDataType)iType) != NULL
264 && EQUAL(GDALGetDataTypeName((GDALDataType)iType),
265 otype_opt[0].c_str()))
266 theType=(GDALDataType) iType;
270 if(theType==GDT_Unknown)
271 cout <<
"Unknown output pixel type: " << otype_opt[0] << endl;
273 cout <<
"Output pixel type: " << GDALGetDataTypeName(theType) << endl;
276 double cropulx=ulx_opt[0];
277 double cropuly=uly_opt[0];
278 double croplrx=lrx_opt[0];
279 double croplry=lry_opt[0];
283 if(extent_opt.size()){
288 for(
int iextent=0;iextent<extent_opt.size();++iextent){
289 extentReader.open(extent_opt[iextent]);
290 if(!(extentReader.getExtent(e_ulx,e_uly,e_lrx,e_lry))){
291 cerr <<
"Error: could not get extent from " << extent_opt[0] << endl;
310 extentReader.close();
313 extentReader.open(extent_opt[0]);
315 else if(cx_opt.size()&&cy_opt.size()&&nx_opt.size()&&ny_opt.size()){
316 ulx_opt[0]=cx_opt[0]-nx_opt[0]/2.0;
317 uly_opt[0]=(isGeoRef) ? cy_opt[0]+ny_opt[0]/2.0 : cy_opt[0]-ny_opt[0]/2.0;
318 lrx_opt[0]=cx_opt[0]+nx_opt[0]/2.0;
319 lry_opt[0]=(isGeoRef) ? cy_opt[0]-ny_opt[0]/2.0 : cy_opt[0]+ny_opt[0]/2.0;
329 else if(cx_opt.size()&&cy_opt.size()&&ns_opt.size()&&nl_opt.size()){
330 ulx_opt[0]=cx_opt[0]-ns_opt[0]*dx/2.0;
331 uly_opt[0]=(isGeoRef) ? cy_opt[0]+nl_opt[0]*dy/2.0 : cy_opt[0]-nl_opt[0]*dy/2.0;
332 lrx_opt[0]=cx_opt[0]+ns_opt[0]*dx/2.0;
333 lry_opt[0]=(isGeoRef) ? cy_opt[0]-nl_opt[0]*dy/2.0 : cy_opt[0]+nl_opt[0]*dy/2.0;
345 cout <<
"--ulx=" << ulx_opt[0] <<
" --uly=" << uly_opt[0] <<
" --lrx=" << lrx_opt[0] <<
" --lry=" << lry_opt[0] << endl;
351 if(extent_opt.size()&&cut_opt[0]){
353 ncropcol=abs(static_cast<int>(ceil((lrx_opt[0]-ulx_opt[0])/dx)));
354 ncroprow=abs(static_cast<int>(ceil((uly_opt[0]-lry_opt[0])/dy)));
355 maskWriter.open(
"/vsimem/mask.tif",ncropcol,ncroprow,1,GDT_Float32,
"GTiff",option_opt);
363 maskWriter.setGeoTransform(gt);
364 if(projection_opt.size())
365 maskWriter.setProjectionProj4(projection_opt[0]);
366 else if(projectionString.size())
367 maskWriter.setProjection(projectionString);
370 vector<double> burnValues(1,1);
371 maskWriter.rasterizeOgr(extentReader,burnValues);
375 cerr << error << std::endl;
379 cerr <<
"error catched" << std::endl;
384 mask_opt.push_back(
"/vsimem/mask.tif");
389 if(verbose_opt[0]>=1)
390 std::cout <<
"opening mask image file " << mask_opt[0] << std::endl;
391 maskReader.open(mask_opt[0]);
394 cerr << error << std::endl;
398 cerr <<
"error catched" << std::endl;
406 if(scale_opt.size()){
407 while(scale_opt.size()<band_opt.size())
408 scale_opt.push_back(scale_opt[0]);
410 if(offset_opt.size()){
411 while(offset_opt.size()<band_opt.size())
412 offset_opt.push_back(offset_opt[0]);
414 if(autoscale_opt.size()){
415 assert(autoscale_opt.size()%2==0);
422 for(
int iimg=0;iimg<input_opt.size();++iimg){
424 cout <<
"opening image " << input_opt[iimg] << endl;
425 imgReader.open(input_opt[iimg]);
427 if(theType==GDT_Unknown){
428 theType=imgReader.getDataType();
430 cout <<
"Using data type from input image: " << GDALGetDataTypeName(theType) << endl;
432 if(option_opt.findSubstring(
"INTERLEAVE=")==option_opt.end()){
433 string theInterleave=
"INTERLEAVE=";
434 theInterleave+=imgReader.getInterleave();
435 option_opt.push_back(theInterleave);
437 int nrow=imgReader.nrOfRow();
438 int ncol=imgReader.nrOfCol();
444 cout <<
"size of " << input_opt[iimg] <<
": " << ncol <<
" cols, "<< nrow <<
" rows" << endl;
445 double uli,ulj,lri,lrj;
446 bool forceEUgrid=
false;
447 if(projection_opt.size())
448 forceEUgrid=(!(projection_opt[0].compare(
"EPSG:3035"))||!(projection_opt[0].compare(
"EPSG:3035"))||projection_opt[0].find(
"ETRS-LAEA")!=string::npos);
449 if(ulx_opt[0]>=lrx_opt[0]){
451 lri=imgReader.nrOfCol()-1;
453 lrj=imgReader.nrOfRow()-1;
454 ncropcol=imgReader.nrOfCol();
455 ncroprow=imgReader.nrOfRow();
456 imgReader.getBoundingBox(cropulx,cropuly,croplrx,croplry);
457 double magicX=1,magicY=1;
462 egcs.setLevel(egcs.res2level(dx));
463 egcs.force2grid(cropulx,cropuly,croplrx,croplry);
464 imgReader.geo2image(cropulx+(magicX-1.0)*imgReader.getDeltaX(),cropuly-(magicY-1.0)*imgReader.getDeltaY(),uli,ulj);
465 imgReader.geo2image(croplrx+(magicX-2.0)*imgReader.getDeltaX(),croplry-(magicY-2.0)*imgReader.getDeltaY(),lri,lrj);
467 imgReader.geo2image(cropulx+(magicX-1.0)*imgReader.getDeltaX(),cropuly-(magicY-1.0)*imgReader.getDeltaY(),uli,ulj);
468 imgReader.geo2image(croplrx+(magicX-2.0)*imgReader.getDeltaX(),croplry-(magicY-2.0)*imgReader.getDeltaY(),lri,lrj);
470 ncropcol=abs(static_cast<int>(ceil((croplrx-cropulx)/dx)));
471 ncroprow=abs(static_cast<int>(ceil((cropuly-croplry)/dy)));
474 double magicX=1,magicY=1;
483 egcs.setLevel(egcs.res2level(dx));
484 egcs.force2grid(cropulx,cropuly,croplrx,croplry);
485 imgReader.geo2image(cropulx+(magicX-1.0)*imgReader.getDeltaX(),cropuly-(magicY-1.0)*imgReader.getDeltaY(),uli,ulj);
486 imgReader.geo2image(croplrx+(magicX-2.0)*imgReader.getDeltaX(),croplry-(magicY-2.0)*imgReader.getDeltaY(),lri,lrj);
488 imgReader.geo2image(cropulx+(magicX-1.0)*imgReader.getDeltaX(),cropuly-(magicY-1.0)*imgReader.getDeltaY(),uli,ulj);
489 imgReader.geo2image(croplrx+(magicX-2.0)*imgReader.getDeltaX(),croplry-(magicY-2.0)*imgReader.getDeltaY(),lri,lrj);
491 ncropcol=abs(static_cast<int>(ceil((croplrx-cropulx)/dx)));
492 ncroprow=abs(static_cast<int>(ceil((cropuly-croplry)/dy)));
501 double deltaX=imgReader.getDeltaX();
502 double deltaY=imgReader.getDeltaY();
503 dcropcol=(lri-uli+1)/(dx/deltaX);
504 dcroprow=(lrj-ulj+1)/(dy/deltaY);
505 if(!imgWriter.nrOfBand()){
507 cout <<
"cropulx: " << cropulx << endl;
508 cout <<
"cropuly: " << cropuly << endl;
509 cout <<
"croplrx: " << croplrx << endl;
510 cout <<
"croplry: " << croplry << endl;
511 cout <<
"ncropcol: " << ncropcol << endl;
512 cout <<
"ncroprow: " << ncroprow << endl;
513 cout <<
"cropulx+ncropcol*dx: " << cropulx+ncropcol*dx << endl;
514 cout <<
"cropuly-ncroprow*dy: " << cropuly-ncroprow*dy << endl;
515 cout <<
"upper left column of input image: " << uli << endl;
516 cout <<
"upper left row of input image: " << ulj << endl;
517 cout <<
"lower right column of input image: " << lri << endl;
518 cout <<
"lower right row of input image: " << lrj << endl;
519 cout <<
"new number of cols: " << ncropcol << endl;
520 cout <<
"new number of rows: " << ncroprow << endl;
521 cout <<
"new number of bands: " << ncropband << endl;
533 string imageType=imgReader.getImageType();
534 if(oformat_opt.size())
535 imageType=oformat_opt[0];
537 imgWriter.open(output_opt[0],ncropcol,ncroprow,ncropband,theType,imageType,option_opt);
538 if(nodata_opt.size()){
539 for(
int iband=0;iband<ncropband;++iband)
540 imgWriter.GDALSetNoDataValue(nodata_opt[0],iband);
543 catch(
string errorstring){
544 cout << errorstring << endl;
547 if(description_opt.size())
548 imgWriter.setImageDescription(description_opt[0]);
555 gt[5]=(imgReader.isGeoRef())? -dy : dy;
556 imgWriter.setGeoTransform(gt);
557 if(projection_opt.size()){
559 cout <<
"projection: " << projection_opt[0] << endl;
560 imgWriter.setProjectionProj4(projection_opt[0]);
563 imgWriter.setProjection(imgReader.getProjection());
564 if(imgWriter.getDataType()==GDT_Byte){
565 if(colorTable_opt.size()){
566 if(colorTable_opt[0]!=
"none")
567 imgWriter.setColorTable(colorTable_opt[0]);
569 else if (imgReader.getColorTable()!=NULL)
570 imgWriter.setColorTable(imgReader.getColorTable());
578 else if(uli>=imgReader.nrOfCol())
579 startCol=imgReader.nrOfCol()-1;
582 else if(lri>=imgReader.nrOfCol())
583 endCol=imgReader.nrOfCol()-1;
588 else if(ulj>=imgReader.nrOfRow())
589 startRow=imgReader.nrOfRow()-1;
592 else if(lrj>=imgReader.nrOfRow())
593 endRow=imgReader.nrOfRow()-1;
597 int readncol=endCol-startCol+1;
598 vector<double> readBuffer(readncol+1);
599 int nband=(band_opt.size())?band_opt.size() : imgReader.nrOfBand();
600 for(
int iband=0;iband<nband;++iband){
601 int readBand=(band_opt.size()>iband)?band_opt[iband]:iband;
603 cout <<
"extracting band " << readBand << endl;
604 pfnProgress(progress,pszMessage,pProgressArg);
608 if(autoscale_opt.size()){
610 imgReader.getMinMax(static_cast<int>(startCol),static_cast<int>(endCol),static_cast<int>(startRow),static_cast<int>(endRow),readBand,theMin,theMax);
612 catch(
string errorString){
613 cout << errorString << endl;
616 cout <<
"minmax: " << theMin <<
", " << theMax << endl;
617 double theScale=(autoscale_opt[1]-autoscale_opt[0])/(theMax-theMin);
618 double theOffset=autoscale_opt[0]-theScale*theMin;
619 imgReader.setScale(theScale,readBand);
620 imgReader.setOffset(theOffset,readBand);
623 if(scale_opt.size()){
624 if(scale_opt.size()>iband)
625 imgReader.setScale(scale_opt[iband],readBand);
627 imgReader.setScale(scale_opt[0],readBand);
629 if(offset_opt.size()){
630 if(offset_opt.size()>iband)
631 imgReader.setOffset(offset_opt[iband],readBand);
633 imgReader.setOffset(offset_opt[0],readBand);
641 for(
int irow=0;irow<imgWriter.nrOfRow();++irow){
642 vector<float> lineMask;
646 imgWriter.image2geo(0,irow,x,y);
648 imgReader.geo2image(x,y,readCol,readRow);
649 vector<double> writeBuffer;
650 if(readRow<0||readRow>=imgReader.nrOfRow()){
655 for(
int ib=0;ib<imgWriter.nrOfCol();++ib)
656 writeBuffer.push_back(nodataValue);
660 cout <<
"reading row: " << readRow << endl;
662 if(endCol<imgReader.nrOfCol()-1)
663 imgReader.readData(readBuffer,GDT_Float64,startCol,endCol+1,readRow,readBand,theResample);
665 imgReader.readData(readBuffer,GDT_Float64,startCol,endCol,readRow,readBand,theResample);
667 double oldRowMask=-1;
668 for(
int ib=0;ib<imgWriter.nrOfCol();++ib){
669 imgWriter.image2geo(ib,irow,x,y);
671 imgReader.geo2image(x,y,readCol,readRow);
672 if(readCol<0||readCol>=imgReader.nrOfCol()){
678 writeBuffer.push_back(nodataValue);
689 imgWriter.image2geo(ib,irow,geox,geoy);
690 maskReader.geo2image(geox,geoy,colMask,rowMask);
691 colMask=
static_cast<int>(colMask);
692 rowMask=
static_cast<int>(rowMask);
693 if(rowMask>=0&&rowMask<maskReader.nrOfRow()&&colMask>=0&&colMask<maskReader.nrOfCol()){
694 if(static_cast<int>(rowMask)!=
static_cast<int>(oldRowMask)){
696 assert(rowMask>=0&&rowMask<maskReader.nrOfRow());
698 maskReader.readData(lineMask,GDT_Float32,static_cast<int>(rowMask));
700 catch(
string errorstring){
701 cerr << errorstring << endl;
705 cerr <<
"error catched" << std::endl;
710 if(lineMask[colMask]==0)
716 writeBuffer.push_back(nodataValue);
720 lowerCol=readCol-0.5;
721 lowerCol=
static_cast<int>(lowerCol);
722 upperCol=readCol+0.5;
723 upperCol=
static_cast<int>(upperCol);
726 if(upperCol>=imgReader.nrOfCol())
727 upperCol=imgReader.nrOfCol()-1;
729 writeBuffer.push_back((readCol-0.5-lowerCol)*readBuffer[upperCol-startCol]+(1-readCol+0.5+lowerCol)*readBuffer[lowerCol-startCol]);
732 readCol=
static_cast<int>(readCol);
735 writeBuffer.push_back(readBuffer[readCol]);
742 catch(
string errorstring){
743 cout << errorstring << endl;
747 if(writeBuffer.size()!=imgWriter.nrOfCol())
748 cout <<
"writeBuffer.size()=" << writeBuffer.size() <<
", imgWriter.nrOfCol()=" << imgWriter.nrOfCol() << endl;
749 assert(writeBuffer.size()==imgWriter.nrOfCol());
751 imgWriter.writeData(writeBuffer,GDT_Float64,irow,writeBand);
753 catch(
string errorstring){
754 cout << errorstring << endl;
759 progress/=imgWriter.nrOfRow();
760 pfnProgress(progress,pszMessage,pProgressArg);
764 progress+=(imgWriter.nrOfRow()*writeBand);
765 progress/=imgWriter.nrOfBand()*imgWriter.nrOfRow();
768 pfnProgress(progress,pszMessage,pProgressArg);
775 if(extent_opt.size()&&cut_opt.size()){
776 extentReader.close();