Debian Codegraph @

src/imageclasses/Jim.h

raw symbols SCIP
1 /**********************************************************************
2 Jim.h: class to read/write raster files using GDAL API library
3 Author(s): [email protected]
4 Copyright (C) 2016-2022 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 /*
22 2017-05-04 Kris Vanhoof (vhoofk): Fix rounding issues in bilinear interpolation
23 2017-05-08 Kris Vanhoof (vhoofk): Fix rounding issues in bilinear interpolation
24 2017-05-08 Kris Vanhoof (vhoofk): Handle nodata values in bilinear interpolation
25 */
26 #ifndef _JIM_H_
27 #define _JIM_H_
28
29 #include <cfloat>
30 #include <typeinfo>
31 #include <fstream>
32 #include <sstream>
33 #include <string>
34 #include <vector>
35 #include <list>
36 #include <algorithm>
37 #include <utility>
38 #include <memory>
39 #include <assert.h>
40 #include "gdal_priv.h"
41 #include "gdalwarper.h"
42 #include "gdal_version.h"
43 #include "base/Vector2d.h"
44 #include "JimList.h"
45 #include "apps/AppFactory.h"
46 #include "config_jiplib.h"
47
48 #if MIALLIB == 1
49 extern "C" {
50 #include "miallib_swig.h"
51 #include "miallib_convolve.h"
52 #include "miallib_dem.h"
53 #include "miallib_dist.h"
54 #include "miallib_erodil.h"
55 #include "miallib_format.h"
56 #include "miallib_geodesy.h"
57 #include "miallib_geometry.h"
58 #include "miallib_hmt.h"
59 #include "miallib_imem.h"
60 #include "miallib_io.h"
61 #include "miallib_label.h"
62 #include "miallib_miscel.h"
63 #include "miallib_opclo.h"
64 #include "miallib_pointop.h"
65 #include "miallib_proj.h"
66 #include "miallib_segment.h"
67 #include "miallib_stats.h"
68 #include "op.h"
69 }
70 #endif
71
72 #include <Python.h>
73 /* #include "numpy/arrayobject.h" */
74
75 namespace app{
76 class AppFactory;
77 }
78
79 #if MIALLIB
80 enum JIPLIBDataType {JDT_Unknown=0, JDT_Int64=14, JDT_UInt64=15, JDT_Word=16};
81 #endif
82
83 namespace cover{
84 enum COVER_TYPE {ALL_TOUCHED=0, ALL_COVERED=1, ALL_CENTER=2};
85 }
86
87 enum DATA_ACCESS { READ_ONLY = 0, UPDATE = 1, WRITE = 3};
88 enum RESAMPLE { NEAR = 0, BILINEAR = 1, BICUBIC = 2 };
89 /* enum GDALDataType { */
90 /* GDT_Unknown = 0, GDT_Byte = 1, GDT_UInt16 = 2, GDT_Int16 = 3, */
91 /* GDT_UInt32 = 4, GDT_Int32 = 5, GDT_Float32 = 6, GDT_Float64 = 7, */
92 /* GDT_CInt16 = 8, GDT_CInt32 = 9, GDT_CFloat32 = 10, GDT_CFloat64 = 11, */
93 /* GDT_TypeCount = 12 */
94 /* } */
95
96 /**
97 * @param C++ data type to be converted to GDAL data type
98 * @return the GDAL data type that corresponds to the given C++ data type
99 **/
100 //template<typename T1> GDALDataType getGDALDataType(){
101 template<typename T1> GDALDataType type2GDAL(){
102 if (typeid(T1) == typeid(char))
103 return GDT_Byte;
104 else if (typeid(T1) == typeid(unsigned char))
105 return GDT_Byte;
106 else if (typeid(T1) == typeid(unsigned short))
107 return GDT_UInt16;
108 else if (typeid(T1) == typeid(short))
109 return GDT_Int16;
110 else if (typeid(T1) == typeid(int))
111 return GDT_Int32;
112 else if (typeid(T1) == typeid(unsigned int))
113 return GDT_UInt32;
114 else if (typeid(T1) == typeid(long))
115 return GDT_Int32;
116 else if (typeid(T1) == typeid(unsigned long))
117 return GDT_UInt32;
118 else if (typeid(T1) == typeid(float))
119 return GDT_Float32;
120 else if (typeid(T1) == typeid(double))
121 return GDT_Float64;
122 else
123 return GDT_Unknown;
124 };
125
126 static GDALDataType string2GDAL(const std::string &typeString){
127 std::map<std::string,GDALDataType> typeMap;
128 typeMap["Byte"]=GDT_Byte;
129 typeMap["UInt16"]=GDT_UInt16;
130 typeMap["Int16"]=GDT_Int16;
131 typeMap["UInt32"]=GDT_UInt32;
132 typeMap["Int32"]=GDT_Int32;
133 typeMap["Float32"]=GDT_Float32;
134 typeMap["Float64"]=GDT_Float64;
135 typeMap["GDT_Byte"]=GDT_Byte;
136 typeMap["GDT_UInt16"]=GDT_UInt16;
137 typeMap["GDT_Int16"]=GDT_Int16;
138 typeMap["GDT_UInt32"]=GDT_UInt32;
139 typeMap["GDT_Int32"]=GDT_Int32;
140 typeMap["GDT_Float32"]=GDT_Float32;
141 typeMap["GDT_Float64"]=GDT_Float64;
142 typeMap["int8"]=GDT_Byte;
143 typeMap["uint8"]=GDT_Byte;
144 typeMap["int16"]=GDT_Int16;
145 typeMap["uint16"]=GDT_UInt16;
146 typeMap["uint32"]=GDT_UInt32;
147 typeMap["int32"]=GDT_Int32;
148 typeMap["float32"]=GDT_Float32;
149 typeMap["float64"]=GDT_Float64;
150 typeMap["Int8"]=GDT_Byte;
151 typeMap["UInt8"]=GDT_Byte;
152 typeMap["UInt8"]=GDT_Byte;
153 typeMap["UInt16"]=GDT_UInt16;
154 typeMap["Int16"]=GDT_Int16;
155 typeMap["UInt32"]=GDT_UInt32;
156 typeMap["Int32"]=GDT_Int32;
157 typeMap["Float32"]=GDT_Float32;
158 typeMap["Float64"]=GDT_Float64;
159 if(typeMap.count(typeString))
160 return(typeMap[typeString]);
161 else
162 return(GDT_Unknown);
163 }
164
165 static JIPLIBDataType string2JDT(const std::string &typeString){
166 std::map<std::string,JIPLIBDataType> typeMap;
167 typeMap["UInt64"]=JDT_UInt64;
168 typeMap["Int64"]=JDT_Int64;
169 typeMap["JDT_UInt64"]=JDT_UInt64;
170 typeMap["JDT_Int64"]=JDT_Int64;
171 typeMap["JDT_Word"]=JDT_Word;
172 if(typeMap.count(typeString))
173 return(typeMap[typeString]);
174 else
175 return(JDT_Unknown);
176 }
177
178 static int getDataType(const std::string &typeString){
179 //initialize selMap
180 /* std::map<std::string,GDALDataType> typeMap; */
181 std::map<std::string,int> typeMap;
182 typeMap["Byte"]=GDT_Byte;
183 typeMap["UInt16"]=GDT_UInt16;
184 typeMap["Int16"]=GDT_Int16;
185 typeMap["UInt32"]=GDT_UInt32;
186 typeMap["Int32"]=GDT_Int32;
187 typeMap["Float32"]=GDT_Float32;
188 typeMap["Float64"]=GDT_Float64;
189 typeMap["GDT_Byte"]=GDT_Byte;
190 typeMap["GDT_UInt16"]=GDT_UInt16;
191 typeMap["GDT_Int16"]=GDT_Int16;
192 typeMap["GDT_UInt32"]=GDT_UInt32;
193 typeMap["GDT_Int32"]=GDT_Int32;
194 typeMap["GDT_Float32"]=GDT_Float32;
195 typeMap["GDT_Float64"]=GDT_Float64;
196 typeMap["Int64"]=JDT_Int64;
197 typeMap["UInt64"]=JDT_UInt64;
198 typeMap["JDT_Int64"]=JDT_Int64;
199 typeMap["JDT_UInt64"]=JDT_UInt64;
200 typeMap["JDT_Word"]=JDT_Word;
201 typeMap["int8"]=GDT_Byte;
202 typeMap["uint8"]=GDT_Byte;
203 typeMap["int16"]=GDT_Int16;
204 typeMap["uint16"]=GDT_UInt16;
205 typeMap["uint32"]=GDT_UInt32;
206 typeMap["int32"]=GDT_Int32;
207 typeMap["float32"]=GDT_Float32;
208 typeMap["float64"]=GDT_Float64;
209 typeMap["Int8"]=GDT_Byte;
210 typeMap["UInt8"]=GDT_Byte;
211 typeMap["UInt8"]=GDT_Byte;
212 typeMap["UInt16"]=GDT_UInt16;
213 typeMap["Int16"]=GDT_Int16;
214 typeMap["UInt32"]=GDT_UInt32;
215 typeMap["Int32"]=GDT_Int32;
216 typeMap["Float32"]=GDT_Float32;
217 typeMap["Float64"]=GDT_Float64;
218 if(typeMap.count(typeString))
219 return(typeMap[typeString]);
220 else
221 return(GDT_Unknown);
222 }
223
224 static std::size_t getDataTypeSizeBytes(const std::string &typeString){
225 int typeInt=getDataType(typeString);
226 switch (typeInt){
227 case JDT_UInt64:
228 case JDT_Int64:
229 return(static_cast<std::size_t>(8));
230 case JDT_Word:
231 return(static_cast<std::size_t>(1));
232 default:{
233 if(typeInt==GDT_Unknown){
234 std::string errorString="Error: data type not supported";
235 throw(errorString);
236 }
237 return static_cast<std::size_t>(GDALGetDataTypeSizeBytes(static_cast<GDALDataType>(typeInt)));
238 }
239 }
240 }
241
242 static GDALRIOResampleAlg getGDALResampleIO(const std::string &resampleString){
243 //initialize selMap
244 std::map<std::string,GDALRIOResampleAlg> resampleMap;
245 //for IO (from https://gdal.org/doxygen/gdal_8h.html#a640ada511cbddeefac67c548e009d5ac)
246 resampleMap["NearestNeighbour"]=GRIORA_NearestNeighbour; //Nearest neighbour
247 resampleMap["Bilinear"] = GRIORA_Bilinear; //Bilinear (2x2 kernel)
248 resampleMap["Cubic"]=GRIORA_Cubic; //Cubic Convolution Approximation (4x4 kernel)
249 resampleMap["CubicSpline"]=GRIORA_CubicSpline; //Cubic B-Spline Approximation (4x4 kernel)
250 resampleMap["Lanczos"]=GRIORA_Lanczos; //Lanczos windowed sinc interpolation (6x6 kernel)
251 resampleMap["Average"]=GRIORA_Average; //Average
252 resampleMap["Mode"]=GRIORA_Mode; //Mode (selects the value which appears most often of all the sampled points)
253 resampleMap["Gauss"]=GRIORA_Gauss; //Gauss blurring
254 resampleMap["GRIORA_NearestNeighbour"]=GRIORA_NearestNeighbour;
255 resampleMap["GRIORA_Bilinear"] = GRIORA_Bilinear;
256 resampleMap["GRIORA_Cubic"]=GRIORA_Cubic;
257 resampleMap["GRIORA_CubicSpline"]=GRIORA_CubicSpline;
258 resampleMap["GRIORA_Lanczos"]=GRIORA_Lanczos;
259 resampleMap["GRIORA_Average"]=GRIORA_Average;
260 resampleMap["GRIORA_Mode"]=GRIORA_Mode;
261 resampleMap["GRIORA_Gauss"]=GRIORA_Gauss;
262 if(resampleMap.count(resampleString))
263 return(resampleMap[resampleString]);
264 else
265 return(GRIORA_NearestNeighbour);
266 }
267
268 static GDALResampleAlg getGDALResampleAlg(const std::string &resampleString){
269 //initialize selMap
270 std::map<std::string,GDALResampleAlg> resampleMap;
271 //for warping (from https://gdal.org/doxygen/gdalwarper_8h.html#a4775b029869df1f9270ad554c0633843)
272 resampleMap["near"]=GRA_NearestNeighbour;// nearest neighbour resampling (default, fastest algorithm, worst interpolation quality).
273 resampleMap["bilinear"]=GRA_Bilinear;// bilinear resampling.
274 resampleMap["cubic"]=GRA_Cubic;// cubic resampling.
275 resampleMap["cubicspline"]=GRA_CubicSpline;// cubic spline resampling.
276 resampleMap["lanczos"]=GRA_Lanczos;// Lanczos windowed sinc resampling.
277 resampleMap["average"]=GRA_Average;// average resampling, computes the weighted average of all non-NODATA contributing pixels.
278 resampleMap["mode"]=GRA_Mode;// mode resampling, selects the value which appears most often of all the sampled points.
279 resampleMap["max"]=GRA_Max;// maximum resampling, selects the maximum value from all non-NODATA contributing pixels.
280 resampleMap["min"]=GRA_Min;// minimum resampling, selects the minimum value from all non-NODATA contributing pixels.
281 resampleMap["med"]=GRA_Med;// median resampling, selects the median value of all non-NODATA contributing pixels.
282 resampleMap["q1"]=GRA_Q1;// first quartile resampling, selects the first quartile value of all non-NODATA contributing pixels.
283 resampleMap["q3"]=GRA_Q3;// third quartile resampling, selects the third quartile value of all non-NODATA contributing pixels.
284 //#if GDAL_VERSION_MAJOR >= 3 && GDAL_VERSION_MINOR >= 1
285 #if GDAL_VERSION_MAJOR > 3
286 resampleMap["sum"]=GRA_Sum;// compute the weighted sum of all non-NODATA contributing pixels (since GDAL 3.1)
287 #endif
288 if(resampleMap.count(resampleString))
289 return(resampleMap[resampleString]);
290 else
291 return(GRA_NearestNeighbour);
292 }
293
294 class JimList;
295 class VectorOgr;
296
297 //todo: create name space jiplib?
298 /**
299 Base class for raster dataset (read and write) in a format supported by GDAL. This general raster class is used to store e.g., filename, number of columns, rows and bands of the dataset.
300 **/
301 class Jim : public std::enable_shared_from_this<Jim>
302 {
303 public:
304 ///default constructor
305 Jim();
306 /* Jim(PyObject* npArray, bool copyData=false); */
307 ///constructor opening an image in memory using an external data pointer
308 Jim(void* dataPointer, int ncol, int nrow, const GDALDataType& dataType);
309 Jim(std::vector<void*> dataPointers, int ncol, int nrow, const GDALDataType& dataType);
310 Jim(void* dataPointer, int ncol, int nrow, int nplane, const GDALDataType& dataType);
311 Jim(std::vector<void*> dataPointers, int ncol, int nrow, int nplane, const GDALDataType& dataType);
312 ///constructor input image
313 #if MIALLIB == 1
314 Jim(IMAGE *mia);
315 #endif
316 ///constructor input image
317 Jim(const std::string& filename, bool readData=true, unsigned int memory=0);
318 ///constructor output image
319 Jim(const std::string& filename, const Jim& imgSrc, unsigned int memory=0, const std::vector<std::string>& options=std::vector<std::string>());
320 ///constructor input image
321 /* Jim(std::shared_ptr<Jim> imgSrc, bool copyData=true) : m_nplane(1), Jim(imgSrc, copyData){}; */
322 ///constructor input image
323 Jim(Jim& imgSrc, bool copyData=true);
324 ///constructor output image
325 Jim(const std::string& filename, int ncol, int nrow, int nband, const GDALDataType& dataType, const std::string& imageType, unsigned int memory=0, const std::vector<std::string>& options=std::vector<std::string>());
326 ///constructor output image with nplane
327 Jim(int ncol, int nrow, int nband, int nplane, const GDALDataType& dataType);
328 ///constructor output image
329 Jim(int ncol, int nrow, int nband, const GDALDataType& dataType);
330 ///constructor from app
331 Jim(app::AppFactory &theApp);
332
333 //from Reader
334 /* Jim(const std::string& filename, unsigned int memory=0){ */
335 /* reset(); */
336 /* open(filename, memory); */
337 /* }; */
338 // Jim(const std::string& filename, const GDALAccess& readMode=GA_ReadOnly, unsigned int memory=0) : m_writeMode(false) {open(filename, readMode, memory);};
339 //from Writer
340 /* ///constructor opening an image for writing, copying image attributes from a source image. Caching is supported when memory>0 */
341 /* Jim(const std::string& filename, const Jim& imgSrc, unsigned int memory=0, const std::vector<std::string>& options=std::vector<std::string>()) {open(filename, imgSrc, memory, options); */
342 /* }; */
343 /* ///copy constructor opening an image for writing in memory, copying image attributes from a source image. */
344 /* Jim(Jim& imgSrc, bool copyData=true){ */
345 /* reset(); */
346 /* open(imgSrc,copyData); */
347 /* }; */
348 ///copy constructor opening an image for writing in memory, copying image attributes from a source image.
349 /* Jim(std::shared_ptr<Jim> imgSrc, bool copyData=true){ */
350 /* reset(); */
351 /* open(imgSrc,copyData); */
352 /* }; */
353 ///constructor opening an image for writing, defining all image attributes. Caching is supported when memory>0
354 /* Jim(const std::string& filename, int ncol, int nrow, int nband, const GDALDataType& dataType, const std::string& imageType, unsigned int memory=0, const std::vector<std::string>& options=std::vector<std::string>()) { */
355 /* reset(); */
356 /* open(filename, ncol, nrow, nband, dataType, imageType, memory, options); */
357 /* }; */
358 ///constructor opening an image for writing in memory, defining all image attributes
359 /* Jim(int ncol, int nrow, int nband, const GDALDataType& dataType) { */
360 /* reset(); */
361 /* open(ncol, nrow, nband, dataType); */
362 /* }; */
363 /* ///constructor opening an image for reading or writing using application arguments */
364 /* Jim(app::AppFactory& app){ */
365 /* reset(); */
366 /* open(app); */
367 /* }; */
368
369 ///destructor
370 /* virtual ~Jim(void){freeMem();}; */
371 virtual ~Jim(void);
372
373 ///Create new shared pointer to Jim object
374 /**
375 *
376 * @return shared pointer to new Jim object
377 */
378 static std::shared_ptr<Jim> createImg();
379 /* { */
380 /* return(std::make_shared<Jim>()); */
381 /* }; */
382 ///create shared pointer to Jim
383 static std::shared_ptr<Jim> createImg(const std::shared_ptr<Jim> pSrc, bool copyData=true);
384 /* { */
385 /* std::shared_ptr<Jim> pRaster=std::make_shared<Jim>(*pSrc,copyData); */
386 /* return(pRaster); */
387 /* }; */
388 ///create shared pointer to Jim with random values only for in memory
389 static std::shared_ptr<Jim> createImg(app::AppFactory &theApp);
390 static std::shared_ptr<Jim> createImg(const std::string filename, bool readData=true, unsigned int memory=0);
391 ///get write mode
392 bool writeMode(){return(m_access==WRITE);};
393 ///get access mode
394 DATA_ACCESS getAccess(){return m_access;};
395 ///set access mode
396 CPLErr setAccess(DATA_ACCESS theAccess){m_access=theAccess;return CE_None;};
397 ///set access mode using a string argument
398 CPLErr setAccess(std::string accessString){
399 if(accessString=="READ_ONLY"){
400 m_access=READ_ONLY;
401 return CE_None;
402 }
403 if(accessString=="UPDATE"){
404 m_access=UPDATE;
405 return CE_None;
406 }
407 if(accessString=="WRITE"){
408 m_access=WRITE;
409 return CE_None;
410 }
411 else
412 return CE_Failure;
413 }
414 ///check if data pointer has been initialized
415 bool isInit(){return(m_data.size()>0);};
416 ///Set scale for a specific band when writing the raster data values. The scaling and offset are applied on a per band basis. You need to set the scale for each band. If the image data are cached (class was created with memory>0), the scaling is applied on the cached memory.
417 CPLErr setScale(double theScale, int band=0){
418 if(m_scale.size()!=nrOfBand()){//initialize
419 m_scale.resize(nrOfBand());
420 for(int iband=0;iband<nrOfBand();++iband)
421 m_scale[iband]=1.0;
422 }
423 m_scale[band]=theScale;
424 return CE_None;
425 };
426 ///Set offset for a specific band when writing the raster data values. The scaling and offset are applied on a per band basis. You need to set the offset for each band. If the image data are cached (class was created with memory>0), the offset is applied on the cached memory.
427 CPLErr setOffset(double theOffset, int band=0){
428 if(m_offset.size()!=nrOfBand()){
429 m_offset.resize(nrOfBand());
430 for(int iband=0;iband<nrOfBand();++iband)
431 m_offset[iband]=0.0;
432 }
433 m_offset[band]=theOffset;
434 return(CE_None);
435 };
436 ///set externalData
437 CPLErr setExternalData(bool flag){m_externalData=flag; return CE_None;};
438 bool getExternalData() const {return(m_externalData);};
439 ///Open image from allocated memory instead of from file. This will allow in place image processing in memory (streaming). Notice that an extra call must be made to set the geotranform and projection. This function has not been tested yet!
440 //void open(void* dataPointer, int ncol, int nrow, int nband, const GDALDataType& dataType);
441 ///Close the image.
442 CPLErr close();
443 ///write to file previously set (eg., with setFile). Specialization of the writeData member function of Jim, avoiding reset of the memory.
444 CPLErr write();
445 ///write to file Specialization of the writeData member function of Jim, avoiding reset of the memory.
446 /**
447 * @param output (type: std::string) Output image file
448 * @param oformat (type: std::string) (default: GTiff) Output image format (see also gdal_translate).
449 * @param co (type: std::string) Creation option for output file. Multiple options can be specified.
450 * @return CE_None if successful, CE_Failure if not.
451 * @param nodata Nodata value to put in image.
452 **/
453 CPLErr write(app::AppFactory &theApp);
454 ///Get the filename of this dataset
455 std::string getFileName() const {return m_filename;};
456 ///Get the number of columns of this dataset
457 int nrOfCol() const { return m_ncol;};
458 ///Get the number of rows of this dataset
459 int nrOfRow() const { return m_nrow;};
460 ///Get the number of bands of this dataset
461 int nrOfBand() const { return m_nband;};
462 #ifdef SWIG
463 %pythonprepend nrOfPlane() "\"\"\"HELP.METHOD.Jim.nrOfPlane()\"\"\""
464 #endif
465 ///Get the number of planes of this dataset
466 int nrOfPlane() const { return m_nplane;};
467 ///Is this dataset georeferenced (pixel size in y must be negative) ?
468 bool isGeoRef() const {std::vector<double> gt(6);getGeoTransform(gt);if(gt.size()!=6) return false;else if(gt[5]<0) return true;else return false;};
469 ///Get the projection string (deprecated, use getProjectionRef instead)
470 std::string getProjection() const;
471 ///Get the projection reference
472 std::string getProjectionRef() const;
473 ///Get the geotransform data for this dataset as a list of doubles
474
475 const OGRSpatialReference getSpatialRef() const{
476 OGRSpatialReference thisSpatialRef(getProjectionRef().c_str());
477 return thisSpatialRef;
478 }
479 // const OGRSpatialReference getSpatialRefDS() const{
480 // if(!m_gds){
481 // std::ostringstream errorStream;
482 // errorStream << "Error: no associated GDAL dataset" << std::endl;
483 // throw(errorStream.str());
484 // }
485 // return *(m_gds->GetSpatialRef());
486 // }
487 // const OGRSpatialReference getSpatialRef() const{return *(m_gds->GetSpatialRef());};
488 void getGeoTransform(double& gt0, double& gt1, double& gt2, double& gt3, double& gt4, double& gt5) const{std::vector<double> gt(6); getGeoTransform(gt);if (gt.size()==6){gt0=gt[0];gt1=gt[1];gt2=gt[2];gt3=gt[3];gt4=gt[4];gt5=gt[5];}};
489 /* std::string getGeoTransform() const; */
490 ///Get the geotransform data for this dataset
491 void getGeoTransform(std::vector<double>& gt) const;
492 void getGeoTransform(double* gt) const;
493 ///Set the geotransform data for this dataset
494 CPLErr setGeoTransform(const std::vector<double>& gt);
495 CPLErr setGeoTransform(double* gt);
496 ///Copy geotransform information from another georeferenced image
497 CPLErr copyGeoReference(const Jim& imgSrc);
498 CPLErr copyGeoTransform(const Jim& imgSrc);
499 ///Set the projection for this dataset in well known text (wkt) format
500 void setProjection(const std::string& projection){setProjectionProj4(projection);};
501 ///Set the projection for this dataset from user input (supports epsg:<number> format)
502 void setProjectionProj4(const std::string& projection);
503 ///Get the bounding box of this dataset in georeferenced coordinates with coordinate transform
504 void getBoundingBox(double& ulx, double& uly, double& lrx, double& lry, OGRCoordinateTransformation *poCT=0) const;
505 ///Get the bounding box of this dataset in georeferenced coordinates with coordinate transform
506 void getBoundingBox(std::vector<double> &bbvector, OGRCoordinateTransformation *poCT=0) const;
507 ///Get the bounding box of this dataset in georeferenced coordinates with coordinate transform
508 void getBoundingBox(OGRPolygon *bbPolygon, OGRCoordinateTransformation *poCT=0) const;
509 /* ///Get the bounding box of this dataset in georeferenced coordinates with coordinate transform based on EPSG code */
510 /* bool getBoundingBox(std::vector<double> &bbvector, int targetEPSG) const; */
511 ///Get the center position of this dataset in georeferenced coordinates
512 void getCenterPos(double& centerX, double& centerY) const;
513 ///Get the upper left corner x (georeferenced) coordinate of this dataset
514 double getUlx() const {double ulx, uly, lrx,lry;getBoundingBox(ulx,uly,lrx,lry);return(ulx);};
515 ///Get the upper left corner y (georeferenced) coordinate of this dataset
516 double getUly() const {double ulx, uly, lrx,lry;getBoundingBox(ulx,uly,lrx,lry);return(uly);};
517 ///Get the lower right corner x (georeferenced) coordinate of this dataset
518 double getLrx() const {double ulx, uly, lrx,lry;getBoundingBox(ulx,uly,lrx,lry);return(lrx);};
519 ///Get the lower right corner y (georeferenced) coordinate of this dataset
520 double getLry() const {double ulx, uly, lrx,lry;getBoundingBox(ulx,uly,lrx,lry);return(lry);};
521 ///Get the scale for specific band
522 double getScale(std::size_t band=0){
523 if(m_scale.size()<=band)
524 return(1.0);
525 else
526 return(m_scale[band]);
527 };
528 ///Get the scale as a standard template library (stl) vector
529 void getScale(std::vector<double>& scale) const {scale=m_scale;};
530 ///Get the scale for specific band
531 double getOffset(std::size_t band=0){
532 if(m_offset.size()<=band)
533 return(0.0);
534 else
535 return(m_offset[band]);
536 };
537 ///Get the offset as a standard template library (stl) vector
538 void getOffset(std::vector<double>& offset) const {offset=m_offset;};
539 ///Get the no data values of this dataset as a standard template library (stl) vector
540 /* std::vector<double> getNoDataValues() const{std::cout << "calling with out" << std::endl; return m_noDataValues;}; */
541 ///Get the no data values of this dataset as a standard template library (stl) vector
542 void getNoDataValues(std::vector<double>& noDataValues) const;
543 ///Print the no data values of this dataset as a standard template library (stl) vector
544 CPLErr printNoDataValues() const{
545 if(m_noDataValues.size()){
546 for(int i=0;i<m_noDataValues.size();++i)
547 std::cout << m_noDataValues[i] << " ";
548 std::cout << std::endl;
549 return(CE_None);
550 }
551 else
552 return(CE_Warning);
553 };
554 ///Check if value is nodata in this dataset
555 bool isNoData(double value) const{if(m_noDataValues.empty()) return false;else return find(m_noDataValues.begin(),m_noDataValues.end(),value)!=m_noDataValues.end();};
556 ///Push a no data value for this dataset
557 CPLErr pushNoDataValue(double noDataValue);
558 ///Set the single no data values of this dataset
559 CPLErr setNoDataValue(double nodata){clearNoData(); pushNoDataValue(nodata);if(m_noDataValues.empty()) return(CE_Failure);else return(CE_None);};
560 ///Set the no data values of this dataset using a standard template library (stl) vector as input
561 CPLErr setNoData(const std::vector<double>& nodata){m_noDataValues=nodata; if(nodata.size() != m_noDataValues.size()) return(CE_Failure);else return(CE_None);};
562 ///Set the no data values of this dataset using a standard template library (stl) vector as input
563 CPLErr setNoData(const std::list<double>& nodata){
564 clearNoData();
565 std::list<double>::const_iterator lit=nodata.begin();
566 while(lit!=nodata.end())
567 pushNoDataValue(*(lit++));
568 if(nodata.size() != m_noDataValues.size())
569 return(CE_Failure);
570 else return(CE_None);
571 };
572 void setData(double value);
573 void setData(double value, int band);
574 void setData(double value, double ulx, double uly, double lrx, double lry, int band=0, double dx=0, double dy=0, bool nogeo=false);
575 ///Clear all no data values, including the one in GDAL dataset if it is set
576 CPLErr clearNoData(int band=0){m_noDataValues.clear();if(m_access!=READ_ONLY&&getRasterBand(band)) getRasterBand(band)->DeleteNoDataValue();return(CE_None);}
577 ///Set the GDAL (internal) no data value for this data set. Only a single no data value per band is supported.
578 CPLErr GDALSetNoDataValue(double noDataValue, int band=0) {if(getRasterBand(band)) return getRasterBand(band)->SetNoDataValue(noDataValue);else return(CE_Warning);};
579 ///Check if a geolocation is covered by this dataset. Only the bounding box is checked, irrespective of no data values.
580 bool covers(double x, double y, OGRCoordinateTransformation *poCT=NULL) const;
581 ///Check if a region of interest is (partially or all if all is set) covered by this dataset. Only the bounding box is checked, irrespective of no data values.
582 bool covers(double ulx, double uly, double lrx, double lry, std::string coverType="ALL_TOUCHED", OGRCoordinateTransformation *poCT=NULL) const;
583 ///Check if an image is (partially or all if all is set) covered by this dataset. Only the bounding box is checked, irrespective of no data values.
584 bool covers(const std::shared_ptr<Jim> imgRaster, std::string coverType="ALL_TOUCHED") const{
585 OGRSpatialReference thisSpatialRef(getProjectionRef().c_str());
586 OGRSpatialReference thatSpatialRef(imgRaster->getProjectionRef().c_str());
587 OGRCoordinateTransformation *that2this = OGRCreateCoordinateTransformation(&thatSpatialRef, &thisSpatialRef);
588 if(thisSpatialRef.IsSame(&thatSpatialRef)){
589 that2this=0;
590 }
591 else{
592 if(!that2this){
593 std::ostringstream errorStream;
594 errorStream << "Error: cannot create OGRCoordinateTransformation that to this" << std::endl;
595 throw(errorStream.str());
596 }
597 }
598 //image bounding box in SRS of the this
599 double img_ulx,img_uly,img_lrx,img_lry;
600 imgRaster->getBoundingBox(img_ulx,img_uly,img_lrx,img_lry,that2this);
601 return covers(img_ulx,img_uly,img_lrx,img_lry,coverType);
602 };
603 ///Convert georeferenced coordinates (x and y) to image coordinates (column and row)
604 bool geo2image(double x, double y, double& i, double& j, OGRCoordinateTransformation *poCT=NULL) const;
605 ///Convert image coordinates (column and row) to georeferenced coordinates (x and y)
606 bool image2geo(double i, double j, double& x, double& y, OGRCoordinateTransformation *poCT=NULL) const;
607 ///Get the pixel cell spacing in x
608 double getDeltaX() const {std::vector<double> gt(6);getGeoTransform(gt);return gt[1];};
609 ///Get the pixel cell spacing in y
610 double getDeltaY() const {std::vector<double> gt(6);getGeoTransform(gt);return -gt[5];};
611 ///Get the GDAL datatype for this dataset
612 GDALDataType getDataTypeDS(int band=0) const;
613 ///Get the internal datatype for this dataset
614 int getDataType(int band=0) const;
615 GDALDataType getGDALDataType(int band=0) const;
616 std::size_t getDataTypeSizeBytes(int band=0) const;
617 //GDALDataType getDataType(int band=0) const;
618 ///Get the datapointer
619 void* getDataPointer(int band=0){return(m_data[band]);};
620 ///free memory os data pointer
621 void freeMem();
622 ///Copy data
623 CPLErr copyData(void* data, int band=0);
624 ///Copy data
625 // void copyData(Jim& imgRaster, int band=0);
626 //todo: introduce smart pointer instead of void*
627 // std::unique_ptr<void> getDataPointer(int band=0){return(m_data[band]);};
628 ///Get the GDAL rasterband for this dataset
629 GDALRasterBand* getRasterBand(int band=0) const;
630 ///Get the GDAL color table for this dataset as an instance of the GDALColorTable class
631 GDALColorTable* getColorTable(int band=0) const;
632 ///Get the GDAL driver description of this dataset
633 std::string getDriverDescription() const;
634 ///Get the image type (implemented as the driver description)
635 std::string getImageType() const{return getDriverDescription();};
636 ///Get the band coding (interleave)
637 std::string getInterleave() const;
638 ///Get the compression from the metadata of this dataset
639 std::string getCompression() const;
640 //Get a pointer to the GDAL dataset
641 GDALDataset* getDataset(){return m_gds;};
642 ///Get the metadata of this dataset
643 #if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(3, 13, 0)
644 CSLConstList getMetadata() const;
645 #else
646 char** getMetadata() const;
647 #endif
648 // Get the metadata of this dataset in the form of a list of strings (const version)
649 void getMetadata(std::list<std::string>& metadata) const;
650 ///Get the image description from the driver of this dataset
651 std::string getDescription() const;
652 ///Get metadata item of this dataset
653 std::string getMetadataItem() const;
654 ///Get the image description from the metadata of this dataset
655 std::string getImageDescription() const;
656 int getBlockSize() const{return m_blockSize;};
657 int getBlockSizeX(int band=0)
658 {
659 int blockSizeX=0;
660 int blockSizeY=0;
661 if(getRasterBand(band))
662 getRasterBand(band)->GetBlockSize( &blockSizeX, &blockSizeY );
663 return blockSizeX;
664 }
665 int getBlockSizeY(int band=0)
666 {
667 int blockSizeX=0;
668 int blockSizeY=0;
669 if(getRasterBand(band))
670 getRasterBand(band)->GetBlockSize( &blockSizeX, &blockSizeY );
671 return blockSizeY;
672 }
673 int nrOfBlockX(int band=0)
674 {
675 int blockSizeX=0;
676 int blockSizeY=0;
677 int nXBlocks=0;
678 if(getRasterBand(band)){
679 getRasterBand(band)->GetBlockSize( &blockSizeX, &blockSizeY );
680 nXBlocks = (nrOfCol() + blockSizeX - 1) / blockSizeX;
681 }
682 return nXBlocks;
683 }
684 int nrOfBlockY(int band=0)
685 {
686 int blockSizeX=0;
687 int blockSizeY=0;
688 int nYBlocks=0;
689 if(getRasterBand(band)){
690 getRasterBand(band)->GetBlockSize( &blockSizeX, &blockSizeY );
691 nYBlocks = (nrOfRow() + blockSizeY - 1) / blockSizeY;
692 }
693 return nYBlocks;
694 }
695
696 ///Create a JSON string from a Jim image
697 std::string jim2json();
698 ///Clone as new shared pointer to Jim object
699 /* std::shared_ptr<Jim> clone() { */
700 /* return(cloneImpl()); */
701 /* }; */
702 std::shared_ptr<Jim> clone(bool copyData=true);
703 std::shared_ptr<Jim> getShared(){return(std::dynamic_pointer_cast<Jim>(shared_from_this()));};
704 ///Read all pixels from image in memory for specific dataset band
705 CPLErr readDataDS(int band, int ds_band);
706 ///Read all pixels from image in memory for specific band
707 CPLErr readData(int band){return readDataDS(band,band);};
708 ///Read all pixels from image in memory
709 CPLErr readData();
710 ///Read data using the arguments from AppFactory
711 /* CPLErr readData(app::AppFactory &app); */
712 ///Read a single pixel cell value at a specific column and row for a specific band (all indices start counting from 0)
713 template<typename T> CPLErr readData(T& value, int col, int row, int band=0);
714 template<typename T> CPLErr readData3D(T& value, std::size_t col, std::size_t row, std::size_t plane, std::size_t band=0);
715 template<typename T> CPLErr readData3D(std::vector<T>& buffer, std::size_t minCol, std::size_t maxCol, std::size_t row, std::size_t plane, std::size_t band=0);
716 ///Return a single pixel cell value at a specific column and row for a specific band (all indices start counting from 0)
717 double readData(int col, int row, int band=0){
718 double value;
719 readData(value, col, row, band);
720 return(value);
721 };
722 double readData3D(std::size_t col, std::size_t row, std::size_t plane, std::size_t band=0){
723 double value;
724 readData3D(value, col, row, plane, band);
725 return(value);
726 };
727 ///Read pixel cell values for a range of columns for a specific row and band (all indices start counting from 0)
728 template<typename T> CPLErr readData(std::vector<T>& buffer, int minCol, int maxCol, int row, int band=0);
729 ///Read pixel cell values for a range of columns for a specific row and band (all indices start counting from 0). The row counter can be floating, in which case a resampling is applied at the row level. You still must apply the resampling at column level. This function will be deprecated, as the GDAL API now supports rasterIO resampling (see http://www.gdal.org/structGDALRasterIOExtraArg.html)
730 template<typename T> CPLErr readData(std::vector<T>& buffer, int minCol, int maxCol, double row, int band, RESAMPLE resample);
731 ///Read pixel cell values for a range of columns and rows for a specific band (all indices start counting from 0). The buffer is a two dimensional vector (stl vector of stl vector) representing [row][col].
732 template<typename T> CPLErr readDataBlock(Vector2d<T>& buffer2d, int minCol, int maxCol, int minRow, int maxRow, int band=0);
733 template<typename T> CPLErr readDataBlock3D(Vector2d<T>& buffer2d, std::size_t minCol, std::size_t maxCol, std::size_t minRow, std::size_t maxRow, std::size_t plane, std::size_t band=0);
734 ///Read pixel cell values for a range of columns and rows for a specific band (all indices start counting from 0). The buffer is a one dimensional stl vector representing all pixel values read starting from upper left to lower right.
735 template<typename T> CPLErr readDataBlock(std::vector<T>& buffer , int minCol, int maxCol, int minRow, int maxRow, int band=0);
736 template<typename T> CPLErr readDataBlock3D(std::vector<T>& buffer , std::size_t minCol, std::size_t maxCol, std::size_t minRow, std::size_t maxRow, std::size_t plane, std::size_t band=0);
737 ///Read pixel cell values for a range of columns, rows and bands for a specific band (all indices start counting from 0). The buffer is a one dimensional stl vector representing all pixel values read starting from upper left to lower right, band interleaved.
738 template<typename T> CPLErr readData(std::vector<T>& buffer, int row, int band=0);
739 ///Read pixel cell values for an entire row for a specific band (all indices start counting from 0). The row counter can be floating, in which case a resampling is applied at the row level. You still must apply the resampling at column level. This function will be deprecated, as the GDAL API now supports rasterIO resampling (see http://www.gdal.org/structGDALRasterIOExtraArg.html)
740 template<typename T> CPLErr readData(std::vector<T>& buffer, double row, int band, RESAMPLE resample);
741 ///Get the minimum and maximum cell values for a specific band in a region of interest defined by startCol, endCol, startRow and endRow (all indices start counting from 0).
742 void getMinMax(int startCol, int endCol, int startRow, int endRow, int band, double& minValue, double& maxValue);
743 ///Get the minimum and maximum cell values for a specific band (all indices start counting from 0).
744 void getMinMax(double& minValue, double& maxValue, int band=0);
745 ///Get the minimum cell values for a specific band and report the column and row in which the minimum value was found (all indices start counting from 0).
746 double getMin(int& col, int& row, int band=0);
747 ///Get the minimum cell values for a specific band.
748 double getMin(int band=0){int theCol=0;int theRow=0;return(getMin(theCol,theRow,band));};
749 ///Get the maximum cell values for a specific band and report the column and row in which the maximum value was found (all indices start counting from 0).
750 double getMax(int& col, int& row, int band=0);
751 ///Get the maximum cell values for a specific band.
752 double getMax(int band=0){int theCol=0;int theRow=0;return(getMax(theCol,theRow,band));};
753 ///Calculate the image histogram for a specific band using a defined number of bins and constrained by a minimum and maximum value. A kernel density function can also be applied (default is false).
754 double getHistogram(std::vector<double>& histvector, double& min, double& max, int& nbin, int theBand=0, bool kde=false);
755 ///Calculate the reference pixel as the centre of gravity pixel (weighted average of all values not taking into account no data values) for a specific band (start counting from 0).
756 void getRefPix(double& refX, double &refY, int band=0);
757 ///Calculate the range of cell values in the image for a specific band (start counting from 0).
758 void getRange(std::vector<short>& range, int band=0);
759 ///Calculate the number of valid pixels (with a value not defined as no data).
760 unsigned long int getNvalid(int band=0);
761 ///Calculate the number of invalid pixels (with a value defined as no data).
762 unsigned long int getNinvalid(int band=0);
763
764 //From Reader
765 ///Open dataset
766 CPLErr open(const std::string& filename, bool readData=true, unsigned int memory=0);
767 // void open(const std::string& filename, const GDALAccess& readMode=GA_ReadOnly, unsigned int memory=0);
768 //From Writer
769 ///Open an image for writing, copying image attributes from a source image. Image is directly written to file. Use the constructor with memory>0 to support caching
770 CPLErr open(const std::string& filename, const Jim& imgSrc, const std::vector<std::string>& options=std::vector<std::string>());
771 ///Open an image for writing, copying image attributes from a source image. Caching is supported when memory>0
772 CPLErr open(const std::string& filename, const Jim& imgSrc, unsigned int memory, const std::vector<std::string>& options=std::vector<std::string>());
773 ///Open an image for writing, defining all image attributes. Image is directly written to file. Use the constructor with memory>0 to support caching
774 // void open(const std::string& filename, int ncol, int nrow, int nband, const GDALDataType& dataType, const std::string& imageType, const std::vector<std::string>& options=std::vector<std::string>());
775 ///Open an image for writing, defining all image attributes. Caching is supported when memory>0
776 CPLErr open(const std::string& filename, int ncol, int nrow, int nband, const GDALDataType& dataType, const std::string& imageType, unsigned int memory=0, const std::vector<std::string>& options=std::vector<std::string>());
777 ///Open an image for writing in memory, defining image attributes.
778 CPLErr open(int ncol, int nrow, int nband, const GDALDataType& dataType);
779 ///Open an image for writing in memory with nplane, defining image attributes.
780 CPLErr open(int ncol, int nrow, int nband, int nplane, const GDALDataType& dataType);
781 ///Open an image for writing in memory, copying image attributes from a source image.
782 CPLErr open(Jim& imgSrc, bool copyData=true);
783 ///Open an image for writing in memory, copying image attributes from a source image.
784 /* CPLErr open(std::shared_ptr<Jim> imgSrc, bool copyData=true); */
785 ///Open an image for writing using an external data pointer (not tested yet)
786 CPLErr open(void* dataPointer, int ncol, int nrow, const GDALDataType& dataType);
787 ///Open an image for writing using an external data pointer
788 CPLErr open(void* dataPointer, int ncol, int nrow, int nplane, const GDALDataType& dataType, bool copyData=true);
789 ///Open a multiband image for writing using a external data pointers
790 CPLErr open(std::vector<void*> dataPointers, int ncol, int nrow, int nplane, const GDALDataType& dataType, bool copyData=true);
791 ///Open an image for writing using an external data pointer (not tested yet)
792 CPLErr open(std::vector<void*> dataPointers, int ncol, int nrow, const GDALDataType& dataType);
793 ///Open an image for reading or writing using application arguments
794 CPLErr open(app::AppFactory &app);
795
796 ///Set the image description (only for GeoTiff format: TIFFTAG_IMAGEDESCRIPTION)
797 CPLErr setImageDescription(const std::string& imageDescription){m_gds->SetMetadataItem( "TIFFTAG_IMAGEDESCRIPTION",imageDescription.c_str()); return(CE_None);};
798
799 ///Write a single pixel cell value at a specific column and row for a specific band (all indices start counting from 0)
800 template<typename T> CPLErr writeData(const T& value, int col, int row, int band=0);
801 ///Write pixel cell values for a range of columns for a specific row and band (all indices start counting from 0)
802 template<typename T> CPLErr writeData(std::vector<T>& buffer, int minCol, int maxCol, int row, int band=0);
803 ///Write pixel cell values for an entire row for a specific band (all indices start counting from 0)
804 template<typename T> CPLErr writeData(std::vector<T>& buffer, int row, int band=0);
805 /* template<typename T> void writeData3D(std::vector<T>& buffer, std::size_t minCol, std::size_t maxCol, std::size_t row, std::size_t plane, std::size_t band=0); */
806 /* template<typename T> void writeData3D(std::vector<T>& buffer, std::size_t row, std::size_t plane, std::size_t band=0){ */
807 /* writeData3D(buffer, row, 0, nrOfCol()-1, plane, band); */
808 /* }; */
809 // deprecated? Write an entire image from memory to file
810 // CPLErr writeData(void* pdata, const GDALDataType& dataType, int band=0);
811 ///Write pixel cell values for a range of columns and rows for a specific band (all indices start counting from 0). The buffer is a two dimensional vector (stl vector of stl vector) representing [row][col].
812 template<typename T> CPLErr writeDataBlock(Vector2d<T>& buffer2d, int minCol, int maxCol, int minRow, int maxRow, int band=0);
813 template<typename T> CPLErr writeDataBlock(T value, int minCol, int maxCol, int minRow, int maxRow, int band=0);
814 ///Prepare image writer to write to file
815 CPLErr setFile(const std::string& filename, const std::string& imageType, unsigned int memory=0, const std::vector<std::string>& options=std::vector<std::string>());
816 ///Prepare image writer to write to file
817 // void setFile(const std::string& filename, const Jim& imgSrc, unsigned int memory=0, const std::vector<std::string>& options=std::vector<std::string>());
818 ///Set the color table using an (ASCII) file with 5 columns (value R G B alpha)
819 CPLErr setColorTable(const std::string& filename, int band=0);
820 ///Set the color table using the GDAL class GDALColorTable
821 CPLErr setColorTable(GDALColorTable* colorTable, int band=0);
822 ///Set specific metadata (driver specific)
823 CPLErr setMetadata(char** metadata);
824 // CPLErr rasterizeBuf(const std::string& ogrFilename);
825 // CPLErr rasterizeBuf(VectorOgr& ogrReader, app::AppFactory &app);
826 // CPLErr rasterizeBuf(VectorOgr& ogrReader, double burnValue, const std::vector<std::string>& eoption=std::vector<std::string>(), const std::vector<std::string>& layernames=std::vector<std::string>());
827 void d_rasterizeBuf(VectorOgr& ogrReader, app::AppFactory &app);
828 void d_rasterizeBuf(VectorOgr& ogrReader, double burnValue, const std::vector<std::string>& eoption=std::vector<std::string>(), const std::vector<std::string>& layernames=std::vector<std::string>());
829
830 /* CPLErr rasterizeLayersBuf(std::vector<OGRLayer*>& layers, double burnValue=1.0); */
831 /* CPLErr rasterizeLayersBuf(OGRLayer* layer, double burnValue=1.0){std::vector<OGRLayer*> layers;layers.push_back(layer);rasterizeLayersBuf(layers,burnValue);}; */
832 ///Apply thresholds: set to no data if not within thresholds t1 and t2
833 void setThreshold(Jim& imgWriter, double t1, double t2);
834 void setThresholdMin(Jim& imgWriter, double minThreshold);
835 void setThresholdMax(Jim& imgWriter, double maxThreshold);
836 ///Apply absolute thresholds: set to no data if not within thresholds t1 and t2
837 void setAbsThreshold(Jim& imgWriter, double t1, double t2);
838 void setAbsThresholdMin(Jim& imgWriter, double minThreshold);
839 void setAbsThresholdMax(Jim& imgWriter, double maxThreshold);
840 ///Apply thresholds for in memory: set to no data if not within thresholds t1 and t2
841 std::shared_ptr<Jim> setThreshold(double t1, double t2);
842 ///Apply absolute thresholds for in memory: set to no data if not within thresholds t1 and t2
843 std::shared_ptr<Jim> setAbsThreshold(double t1, double t2);
844 ///Apply thresholds: set to no data if not within thresholds t1 and t2, else set to value
845 void setThreshold(Jim& imgWriter, double t1, double t2, double value);
846 void setThresholdMin(Jim& imgWriter, double minThreshold, double value);
847 void setThresholdMax(Jim& imgWriter, double maxThreshold, double value);
848 ///Apply absolute thresholds: set to no data if not within thresholds t1 and t2, else set to value
849 void setAbsThreshold(Jim& imgWriter, double t1, double t2, double value);
850 void setAbsThresholdMin(Jim& imgWriter, double minThreshold, double value);
851 void setAbsThresholdMax(Jim& imgWriter, double maxThreshold, double value);
852 ///Apply thresholds for in memory: set to no data if not within thresholds t1 and t2, else set to value
853 std::shared_ptr<Jim> setThreshold(double t1, double t2, double value);
854 ///Apply absolute thresholds for in memory: set to no data if not within thresholds t1 and t2, else set to value
855 std::shared_ptr<Jim> setAbsThreshold(double t1, double t2, double value);
856 ///Apply thresholds with theApp
857 void setThreshold(Jim& imgWriter, app::AppFactory &theApp);
858 ///Apply thresholds for in memory with theApp
859 std::shared_ptr<Jim> setThreshold(app::AppFactory &theApp);
860
861 ///assignment operator
862 /* Jim& operator=(Jim& imgSrc); */
863 #if MIALLIB == 1
864 bool isEqual(std::shared_ptr<Jim> refImg);
865 #endif
866 ///equal operator
867 std::shared_ptr<Jim> eq(std::shared_ptr<Jim> refJim);
868 std::shared_ptr<Jim> eq(double value);
869 void eq(Jim& refJim, Jim& imgWriter);
870 void eq(double value, Jim& imgWriter);
871 ///not equal operator
872 std::shared_ptr<Jim> ne(std::shared_ptr<Jim> refJim);
873 std::shared_ptr<Jim> ne(double value);
874 void ne(Jim& refJim, Jim& imgWriter);
875 void ne(double value, Jim& imgWriter);
876 ///less than operator
877 std::shared_ptr<Jim> lt(std::shared_ptr<Jim> refJim);
878 std::shared_ptr<Jim> lt(double value);
879 void lt(Jim& refJim, Jim& imgWriter);
880 void lt(double value, Jim& imgWriter);
881 template<typename T> void lt_t(Jim& other, Jim& imgWriter);
882 template<typename T> void lt_t(double value, Jim& imgWriter);
883 ///less than or equal operator
884 std::shared_ptr<Jim> le(std::shared_ptr<Jim> refJim);
885 std::shared_ptr<Jim> le(double value);
886 void le(Jim& refJim, Jim& imgWriter);
887 void le(double value, Jim& imgWriter);
888 ///greater than operator
889 std::shared_ptr<Jim> gt(std::shared_ptr<Jim> refJim);
890 std::shared_ptr<Jim> gt(double value);
891 void gt(Jim& refJim, Jim& imgWriter);
892 void gt(double value, Jim& imgWriter);
893 ///greater than or equal operator
894 std::shared_ptr<Jim> ge(std::shared_ptr<Jim> refJim);
895 std::shared_ptr<Jim> ge(double value);
896 void ge(Jim& refJim, Jim& imgWriter);
897 void ge(double value, Jim& imgWriter);
898 //lib functions
899 ///create color table
900 std::shared_ptr<Jim> createct(app::AppFactory& app);
901 ///create color table
902 void createct(Jim& imgWriter, app::AppFactory& app);
903 ///convert image
904 void convert(Jim& imgWriter, app::AppFactory& app);
905 std::shared_ptr<Jim> convertDataType(const GDALDataType& dataType);
906 std::shared_ptr<Jim> convertDataType(const std::string dataTypeString){return convertDataType(string2GDAL(dataTypeString));};
907 void convertDataType(Jim& imgWriter, const GDALDataType& dataType);
908 template<typename T1, typename T2> void convertDataType_t(Jim& imgWriter);
909 ///hillShade
910 std::shared_ptr<Jim> hillShade(Jim& sza, Jim& saa);
911 void hillShade(Jim& imgWriter, Jim& sza, Jim& saa);
912 template<typename T1, typename T2> void hillShade_t(Jim& imgWriter, Jim& sza, Jim& saa);
913 ///crop image
914 void crop(Jim& imgWriter, app::AppFactory& app);
915 ///crop image
916 void cropOgr(VectorOgr& sampleReader, Jim& imgWriter, app::AppFactory& app);
917 ///crop image if it has not been read yet (typically used when Jim has been opened with argument noRead true)
918 void cropDS(Jim& imgWriter, app::AppFactory& app);
919 ///crop image
920 /* CPLErr crop(Jim& imgWriter, double ulx, double uly, double lrx, double lry); */
921 /* CPLErr crop(Jim& imgWriter, double ulx, double uly, double lrx, double lry, double dx=0, double dy=0, bool geo=true); */
922 ///stack band(s) from another Jim
923 std::shared_ptr<Jim> stackBand(Jim& imgSrc, app::AppFactory& app);
924 std::shared_ptr<Jim> stackBand(Jim& imgSrc){app::AppFactory theApp;return stackBand(imgSrc,theApp);};
925 ///stack band(s) from another Jim
926 void stackBand(Jim& imgSrc, Jim& imgWriter, app::AppFactory& app);
927 void stackBand(Jim& imgSrc, Jim& imgWriter){app::AppFactory theApp;return stackBand(imgSrc,imgWriter,theApp);};
928 ///destructive version of stack band(s) from another Jim
929 void d_stackBand(Jim& imgSrc, app::AppFactory& app);
930 void d_stackBand(Jim& imgSrc){app::AppFactory theApp; d_stackBand(imgSrc,theApp);};
931 ///destructive version of stack plane(s) from another Jim
932 void d_stackPlane(Jim& imgSrc, app::AppFactory& app);
933 void d_stackPlane(Jim& imgSrc){app::AppFactory theApp; d_stackPlane(imgSrc,theApp);};
934 ///crop band(s)
935 std::shared_ptr<Jim> cropBand(app::AppFactory& app);
936 std::shared_ptr<Jim> cropBand(){app::AppFactory theApp;return cropBand(theApp);};
937 ///crop plane(s)
938 std::shared_ptr<Jim> cropPlane(app::AppFactory& app);
939 std::shared_ptr<Jim> cropPlane(){app::AppFactory theApp;return cropPlane(theApp);};
940 void cropBand(Jim& imgWriter, app::AppFactory& app);
941 void cropBand(Jim& imgWriter){app::AppFactory theApp;return cropBand(imgWriter,theApp);};
942 ///destructive version of cropBand
943 void d_cropBand(app::AppFactory& app);
944 void d_cropBand(){app::AppFactory theApp;d_cropBand(theApp);};
945 void cropPlane(Jim& imgWriter, app::AppFactory& app);
946 void cropPlane(Jim& imgWriter){app::AppFactory theApp;return cropPlane(imgWriter,theApp);};
947 ///destructive version of cropPlane
948 void d_cropPlane(app::AppFactory& app);
949 void d_cropPlane(){app::AppFactory theApp;d_cropPlane(theApp);};
950 ///convert image only for in memory
951 std::shared_ptr<Jim> convert(app::AppFactory& app);
952 ///crop image only for in memory
953 std::shared_ptr<Jim> crop(app::AppFactory& app);
954 ///crop image only for in memory
955 /* std::shared_ptr<Jim> crop(double ulx, double uly, double lrx, double lry, double dx=0, double dy=0, bool geo=true); */
956 ///crop Jim image in memory based on VectorOgr returning Jim image
957 std::shared_ptr<Jim> cropOgr(VectorOgr& sampleReader, app::AppFactory& app);
958 ///warp Jim image in memory
959 std::shared_ptr<Jim> warp(app::AppFactory& theApp);
960 ///warp image
961 void warp(Jim& imgWriter, app::AppFactory &theApp);
962 ///polygonize image
963 std::shared_ptr<VectorOgr> polygonize(app::AppFactory& app, std::shared_ptr<Jim>mask=nullptr);
964 ///polygonize image
965 void polygonize(VectorOgr& ogrWriter, app::AppFactory& app, std::shared_ptr<Jim> mask=nullptr);
966 ///extract pixel values from raster image from a vector sample
967 CPLErr extractOgr(VectorOgr& sampleReader, VectorOgr& ogrWriter, app::AppFactory& app);
968 ///extract pixel values from raster image from a vector sample
969 std::shared_ptr<VectorOgr> extractOgr(VectorOgr& sampleReader, app::AppFactory& app);
970 ///extract pixel values from raster image with random or grid sampling
971 CPLErr extractSample(VectorOgr& ogrWriter, app::AppFactory& app);
972 ///extract pixel values from raster image with random or grid sampling
973 std::shared_ptr<VectorOgr> extractSample(app::AppFactory& app);
974 ///extract pixel values from raster image from a raster sample
975 void extractImg(Jim& classReader, VectorOgr& ogrWriter, app::AppFactory& app);
976 template<typename T> void extractImg_t(Jim& classReader, VectorOgr& ogrWriter, app::AppFactory& app);
977 ///extract pixel values from raster image from a raster sample
978 std::shared_ptr<VectorOgr> extractImg(Jim& classReader, app::AppFactory& app);
979 ///calculate statistics profile based on multiband raster dataset
980 void statProfile(Jim& imgWriter, app::AppFactory& app);
981 ///calculate statistics profile based on multiband raster dataset only for in memory
982 std::shared_ptr<Jim> statProfile(app::AppFactory& app);
983 ///filter raster dataset
984 /* CPLErr filter(Jim& imgWriter, app::AppFactory& app); */
985 ///filter raster dataset in spectral/temporal domain
986 void filter1d(Jim& imgWriter, app::AppFactory& app);
987 ///filter raster dataset in spatial domain
988 void filter2d(Jim& imgWriter, const app::AppFactory& app);
989 ///filter raster dataset only for in memory
990 /* std::shared_ptr<Jim> filter(app::AppFactory& app); */
991 ///filter raster dataset in spectral/temporal domain only for in memory
992 std::shared_ptr<Jim> filter1d(app::AppFactory& app);
993 ///filter raster dataset in spatial domain only for in memory
994 std::shared_ptr<Jim> filter2d(const app::AppFactory& app);
995 ///filter raster dataset in spectral/temporal domain
996 std::shared_ptr<Jim> firfilter1d(app::AppFactory& app);
997 ///filter raster dataset in spectral/temporal domain
998 void firfilter1d(Jim& imgWriter, app::AppFactory& app);
999 ///filter raster dataset in spectral/temporal domain
1000 std::shared_ptr<Jim> savgolay(app::AppFactory& app);
1001 ///filter raster dataset in spectral/temporal domain
1002 void savgolay(Jim& imgWriter, app::AppFactory& app);
1003 ///filter raster dataset in spectral/temporal domain
1004 template<typename T> void firfilter1d_t(Jim& imgWriter, app::AppFactory& app);
1005 ///forward wavelet transform in spectral/temporal domain
1006 void d_dwt1d(app::AppFactory& app);
1007 std::shared_ptr<Jim> dwt1d(app::AppFactory& app);
1008 ///inverse wavelet transform in spectral/temporal domain
1009 void d_dwti1d(app::AppFactory& app);
1010 std::shared_ptr<Jim> dwti1d(app::AppFactory& app);
1011 ///smooth no data in raster dataset in spectral/temporal domain
1012 void smoothNoData1d(Jim& imgWriter, app::AppFactory& app);
1013 template<typename T> void smoothNoData1d_t(Jim& imgWriter, app::AppFactory& app);
1014 std::shared_ptr<Jim> smoothNoData1d(app::AppFactory& app);
1015 ///create dataset with statistics based on 3D raster dataset in spectral/temporal domain
1016 void stats1d(Jim& imgWriter, app::AppFactory& app);
1017 template<typename T> void stats1d_t(Jim& imgWriter, app::AppFactory& app);
1018 std::shared_ptr<Jim> stats1d(app::AppFactory& app);
1019 ///filter raster dataset in spatial domain
1020 std::shared_ptr<Jim> firfilter2d(app::AppFactory& app);
1021 ///filter raster dataset in spatial domain
1022 void firfilter2d(Jim& imgWriter, app::AppFactory& app);
1023 template<typename T> void firfilter2d_t(Jim& imgWriter, app::AppFactory& app);
1024 ///forward wavelet transform in spatial domain
1025 void d_dwt2d(app::AppFactory& app);
1026 std::shared_ptr<Jim> dwt2d(app::AppFactory& app);
1027 ///inverse wavelet transform in spatial domain
1028 void d_dwti2d(app::AppFactory& app);
1029 std::shared_ptr<Jim> dwti2d(app::AppFactory& app);
1030 ///check the difference between two images (validate in case of classification image)
1031 CPLErr diff(Jim& imgReference, app::AppFactory& app);
1032 ///check the difference between two images (validate in case of classification image)
1033 CPLErr validate(app::AppFactory& app);
1034 ///train raster dataset
1035 /* void train(JimList& referenceReader, app::AppFactory& app); */
1036 /* void train2d(JimList& referenceReader, app::AppFactory& app); */
1037 ///classify raster dataset
1038 void classify(Jim& imgWriter, app::AppFactory& app);
1039 ///classify raster dataset only for in memory
1040 std::shared_ptr<Jim> classify(app::AppFactory& app);
1041 ///svm raster dataset
1042 void classifySVM(Jim& imgWriter, app::AppFactory& app);
1043 ///svm raster dataset only for in memory
1044 std::shared_ptr<Jim> classifySVM(app::AppFactory& app);
1045 ///svm raster dataset
1046 /* CPLErr svm(Jim& imgWriter, app::AppFactory& app); */
1047 ///svm raster dataset only for in memory
1048 /* std::shared_ptr<Jim> svm(app::AppFactory& app); */
1049 ///artificial neural network raster dataset
1050 void classifyANN(Jim& imgWriter, app::AppFactory& app);
1051 ///artificial neural network raster dataset only for in memory
1052 std::shared_ptr<Jim> classifyANN(app::AppFactory& app);
1053 ///artificial neural network raster dataset
1054 //CPLErr ann(Jim& imgWriter, app::AppFactory& app);
1055 ///ann raster dataset only for in memory
1056 //std::shared_ptr<Jim> ann(app::AppFactory& app);
1057 ///sml train and classify
1058 void classifySML(Jim& imgWriter, JimList& referenceReader, app::AppFactory& app);
1059 void classifySML(Jim& imgWriter, app::AppFactory& app);
1060 template<typename T> void classifySML_t(Jim& imgWriter, JimList& referenceReader, app::AppFactory& app);
1061 std::shared_ptr<Jim> classifySML(JimList& referenceReader, app::AppFactory& app);
1062 std::shared_ptr<Jim> classifySML(app::AppFactory& app);
1063 ///train sml raster dataset
1064 void trainSML(JimList& referenceReader, app::AppFactory& app);
1065 void trainSML2d(JimList& referenceReader, app::AppFactory& app);
1066 template<typename T> void trainSML_t(JimList& referenceReader, app::AppFactory& app);
1067 template<typename T> std::string trainSML2d_t(JimList& referenceReader, app::AppFactory& app);
1068 ///train sml raster dataset in memory
1069 std::string trainMem(JimList& referenceReader, app::AppFactory& app);
1070 ///classify raster dataset using SML
1071 template<typename T> void classifySML_t(Jim& imgWriter, app::AppFactory& app);
1072 ///sml raster dataset only for in memory
1073 template<typename T> std::shared_ptr<Jim> classifySML_t(app::AppFactory& app);
1074 ///sml raster dataset
1075 /* template<typename T> CPLErr classifySML(Jim& imgWriter, app::AppFactory& app); */
1076 ///stretch raster dataset
1077 void stretch(Jim& imgWriter, app::AppFactory& app);
1078 ///stretch raster dataset only for in memory
1079 std::shared_ptr<Jim> stretch(app::AppFactory& app);
1080 ///reclass raster dataset
1081 void reclass(Jim& imgWriter, app::AppFactory& app);
1082 ///reclass raster dataset only for in memory
1083 std::shared_ptr<Jim> reclass(app::AppFactory& app);
1084 //simplified destructive version of reclass
1085 void d_reclass(app::AppFactory& app);
1086 ///set mask to raster dataset
1087 //todo: create template function and make it work for 3D
1088 void setMask(VectorOgr& ogrReader, Jim& imgWriter, app::AppFactory& app);
1089 void d_setMask(VectorOgr& ogrReader, app::AppFactory& app);
1090 ///set mask to raster dataset
1091 //todo: create template function and make it work for 3D
1092 void setMask(JimList& maskReader, Jim& imgWriter, app::AppFactory& app);
1093 /* CPLErr setMask(Jim& imgWriter, app::AppFactory& app); */
1094 ///setmask raster dataset only for in memory
1095 std::shared_ptr<Jim> setMask(VectorOgr& ogrReader, app::AppFactory& app);
1096 ///setmask raster dataset only for in memory
1097 std::shared_ptr<Jim> setMask(JimList& maskReader, app::AppFactory& app);
1098 /* std::shared_ptr<Jim> setMask(app::AppFactory& app); */
1099 ///setMask destructive version
1100 /* template<typename T> void d_setMask(Jim& mask, T value); */
1101 void d_setMask2D(Jim& mask, double value);
1102 void d_setMask(Jim& mask, double value);
1103 template<typename T> void d_setMask_t(Jim& mask, double value);
1104 void d_setMask2D(Jim& mask, Jim& other);
1105 void d_setMask(Jim& mask, Jim& other);
1106 template<typename T1, typename T2> void d_setMask_t(Jim& mask, Jim& other);
1107 ///get mask to raster dataset
1108 void getMask(Jim& imgWriter, app::AppFactory& app);
1109 ///getmask raster dataset only for in memory
1110 std::shared_ptr<Jim> getMask(app::AppFactory& app);
1111 ///dump raster dataset
1112 CPLErr dumpImg(app::AppFactory& app);
1113 ///get statistics
1114 std::multimap<std::string,std::string> getStats(app::AppFactory& app);
1115 ///get unique pixels
1116 /* template<typename T> std::map<std::vector<T>,std::vector<std::pair<unsigned short,unsigned short> > > getUniquePixels(unsigned short start, unsigned short end); */
1117
1118 /// convert single plane multiband image to single band image with multiple planes
1119 void d_band2plane();
1120 ///read data bands into planes
1121 CPLErr readDataPlanes(std::vector<int> bands);
1122 ///write data bands from planes
1123 CPLErr writeDataPlanes();
1124 /// convert single band multiple plane image to single plane multiband image
1125 /* void d_plane2band();//not implemented yet */
1126 #if MIALLIB == 1
1127 ///get MIA representation for a particular band
1128 IMAGE* getMIA(int band=0);
1129 ///set memory from internal MIA representation for particular band
1130 CPLErr setMIA(int band=0);
1131 // ///set memory from MIA representation for particular band
1132 CPLErr setMIA(IMAGE* mia, int band=0);
1133 ///convert a GDAL data type to MIA data type
1134 int getMIADataType();
1135 ///convert a JIPLIB to MIA data type
1136 int JIPLIB2MIADataType(int aJIPLIBDataType);
1137 ///convert a GDAL to MIA data type
1138 int GDAL2MIADataType(GDALDataType aGDALDataType);
1139 ///convert a MIA data type to GDAL data type
1140 int MIA2JIPLIBDataType(int aMIADataType);
1141 #endif
1142
1143 //test for MIA functions
1144 template<typename T> void d_jlframebox_t(std::vector<int> box, T val, std::size_t band);
1145 void d_jlframebox(std::vector<int> box, double val, std::size_t band);
1146 template<typename T> void d_jldistanceGeodesic_t(Jim& reference, std::size_t graph, std::size_t band);
1147 void d_jldistanceGeodesic(Jim& reference, std::size_t, std::size_t band);
1148 std::shared_ptr<Jim> jldistanceGeodesic(Jim& reference, std::size_t graph, std::size_t band);
1149 void testFunction(){std::cout << "Hello testFunction" << std::endl;};
1150
1151 //start insert from fun2method_imagetype
1152 //end insert from fun2method_imagetype
1153 //start insert from fun2method_imagetype_multi
1154 //end insert from fun2method_imagetype_multi
1155 //start insert from fun2method_imagelisttype
1156 //end insert from fun2method_imagelisttype
1157 //start insert from fun2method_errortype
1158 //end insert from fun2method_errortype
1159 //start insert from fun2method_errortype_d
1160 //end insert from fun2method_errortype_d
1161 //start insert from fun2method_errortype_nd
1162 //end insert from fun2method_errortype_nd
1163 //start insert from fun2method_errortype_nm
1164 //end insert from fun2method_errortype_nm
1165 //start insert from fun2method_errortype_d_nm
1166 //end insert from fun2method_errortype_d_nm
1167 protected:
1168 ///reset all member variables
1169 void reset();
1170 //convert data to PyArrayObject
1171 ///Initialize the memory for read/write image in cache
1172 CPLErr initMem(unsigned int memory);
1173 ///filename of this dataset
1174 std::string m_filename;
1175 ///instance of the GDAL dataset of this dataset
1176 GDALDataset *m_gds;
1177 ///number of columns in this dataset
1178 int m_ncol;
1179 ///number of rows in this dataset
1180 int m_nrow;
1181 ///number of bands in this dataset
1182 int m_nband;
1183 ///number of planes in this dataset
1184 int m_nplane;
1185 ///GDAL data type for this dataset
1186 int m_dataType;
1187 //GDALDataType m_dataType;
1188 ///image type for this dataset
1189 std::string m_imageType;
1190 ///geotransform information of this dataset
1191 std::vector<double> m_gt;
1192 //projection string in wkt format
1193 std::string m_projection;
1194 ///no data values for this dataset
1195 std::vector<double> m_noDataValues;
1196 ///Vector containing the scale factor to be applied (one scale value for each band)
1197 std::vector<double> m_scale;
1198 ///Vector containing the offset factor to be applied (one offset value for each band)
1199 std::vector<double> m_offset;
1200 ///Flag for external data pointer, do not delete data pointer m_data when flag is set
1201 bool m_externalData;
1202
1203 ///Block size to cache pixel cell values in memory (calculated from user provided memory size in MB)
1204 unsigned int m_blockSize;
1205 ///The cached pixel cell values for a certain block: a vector of void pointers (one void pointer for each band)
1206 std::vector<void*> m_data;
1207 //todo: use smart pointer
1208 //std::vector<std::unique_ptr<void[]> > m_data;
1209 ///first line that has been read in cache for a specific band
1210 std::vector<int> m_begin;
1211 ///beyond last line read in cache for a specific band
1212 std::vector<int> m_end;
1213
1214 ///register driver for GDAl
1215 CPLErr registerDriver();
1216 ///Create options
1217 std::vector<std::string> m_coptions;
1218 ///Open options
1219 std::vector<std::string> m_ooptions;
1220 ///We are writing a physical file
1221 /* bool m_writeMode; */
1222 ///access mode (ReadOnly or GA_Update)
1223 DATA_ACCESS m_access;
1224 ///resampling algorithm: 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)"
1225 GDALRIOResampleAlg m_resample;
1226
1227 ///Read new block for a specific band in the dataset in specified band of cache (defined by m_begin and m_end) in band ()
1228 CPLErr readNewBlockDS(int row, int band, int ds_band);
1229 ///Read new block in cache (defined by m_begin and m_end)
1230 CPLErr readNewBlock(int row, int band){return readNewBlockDS(row,band,band);};
1231 ///Write new block from cache (defined by m_begin and m_end)
1232 CPLErr writeNewBlock(int row, int band);
1233
1234 private:
1235 std::shared_ptr<Jim> cloneImpl(bool copyData) {
1236 return(std::make_shared<Jim>(*this,copyData));
1237 };
1238 #if MIALLIB == 1
1239 std::vector<IMAGE*> m_mia;
1240 #endif
1241 };
1242
1243 template<typename T> CPLErr Jim::readData(T& value, int col, int row, int band)
1244 {
1245 CPLErr returnValue=CE_None;
1246 try{
1247 if(nrOfBand()<=band){
1248 std::string errorString="Error: band number exceeds number of bands in input image";
1249 throw(errorString);
1250 }
1251 if(nrOfCol()<=col){
1252 std::string errorString="Error: col number exceeds number of cols in input image";
1253 throw(errorString);
1254 }
1255 if(nrOfRow()<=row){
1256 std::string errorString="Error: row number exceeds number of rows in input image";
1257 throw(errorString);
1258 }
1259 double dvalue=0;
1260 double theScale=1;
1261 double theOffset=0;
1262 if(m_scale.size()>band||m_offset.size()>band){
1263 if(m_scale.size()>band)
1264 theScale=m_scale[band];
1265 if(m_offset.size()>band)
1266 theOffset=m_offset[band];
1267 }
1268 if(m_data.size()){
1269 //only support random access reading if entire image is in memory for performance reasons
1270 if(m_blockSize!=nrOfRow()){
1271 std::ostringstream s;
1272 s << "Error: increase memory to support random access reading (now at " << 100.0*m_blockSize/nrOfRow() << "%)";
1273 throw(s.str());
1274 }
1275 if(row<m_begin[band]||row>=m_end[band]){
1276 if(m_filename.size())
1277 returnValue = readNewBlock(row,band);
1278 }
1279 int index=(row-m_begin[band])*nrOfCol()+col;
1280 switch(getDataType()){
1281 case(GDT_Byte):
1282 dvalue=theScale*(static_cast<unsigned char*>(m_data[band])[index])+theOffset;
1283 break;
1284 case(GDT_Int16):
1285 dvalue=theScale*(static_cast<short*>(m_data[band])[index])+theOffset;
1286 break;
1287 case(GDT_UInt16):
1288 dvalue=theScale*(static_cast<unsigned short*>(m_data[band])[index])+theOffset;
1289 break;
1290 case(GDT_Int32):
1291 dvalue=theScale*(static_cast<int*>(m_data[band])[index])+theOffset;
1292 break;
1293 case(GDT_UInt32):
1294 dvalue=theScale*(static_cast<unsigned int*>(m_data[band])[index])+theOffset;
1295 break;
1296 case(GDT_Float32):
1297 dvalue=theScale*(static_cast<float*>(m_data[band])[index])+theOffset;
1298 break;
1299 case(GDT_Float64):
1300 dvalue=theScale*(static_cast<double*>(m_data[band])[index])+theOffset;
1301 break;
1302 default:
1303 std::string errorString="Error: data type not supported";
1304 throw(errorString);
1305 break;
1306 }
1307 value=static_cast<T>(dvalue);
1308 }
1309 else{
1310 //fetch raster band
1311 GDALRasterBand *poBand;
1312 poBand = m_gds->GetRasterBand(band+1);//GDAL uses 1 based index
1313 returnValue = poBand->RasterIO(GF_Read,col,row,1,1,&value,1,1,type2GDAL<T>(),0,0);
1314 dvalue=theScale*value+theOffset;
1315 value=static_cast<T>(dvalue);
1316 }
1317 }
1318 catch(std::string errorString){
1319 std::cerr << errorString << std::endl;
1320 throw;
1321 }
1322 catch(...){
1323 throw;
1324 }
1325 return(returnValue);
1326 }
1327
1328 template<typename T> CPLErr Jim::readData3D(T& value, std::size_t col, std::size_t row, std::size_t plane, std::size_t band)
1329 {
1330 try{
1331 if(nrOfBand()<=band){
1332 std::string errorString="Error: band number exceeds number of bands in input image";
1333 throw(errorString);
1334 }
1335 if(nrOfCol()<=col){
1336 std::string errorString="Error: col number exceeds number of cols in input image";
1337 throw(errorString);
1338 }
1339 if(nrOfRow()<=row){
1340 std::string errorString="Error: row number exceeds number of rows in input image";
1341 throw(errorString);
1342 }
1343 if(nrOfPlane()<=plane){
1344 std::string errorString="Error: plane number exceeds number of planes in input image";
1345 throw(errorString);
1346 }
1347 double dvalue=0;
1348 double theScale=1;
1349 double theOffset=0;
1350 if(m_scale.size()>band||m_offset.size()>band){
1351 if(m_scale.size()>band)
1352 theScale=m_scale[band];
1353 if(m_offset.size()>band)
1354 theOffset=m_offset[band];
1355 }
1356 if(m_data.size()){
1357 //only support random access reading if entire image is in memory for performance reasons
1358 if(m_blockSize!=nrOfRow()){
1359 std::ostringstream s;
1360 s << "Error: increase memory to support random access reading (now at " << 100.0*m_blockSize/nrOfRow() << "%)";
1361 throw(s.str());
1362 }
1363 if(row<m_begin[band]||row>=m_end[band]){
1364 if(m_filename.size())
1365 readNewBlock(row,band);
1366 }
1367 int index=(plane*nrOfRow()*nrOfCol())+(row-m_begin[band])*nrOfCol()+col;
1368 switch(getDataType()){
1369 case(GDT_Byte):
1370 dvalue=theScale*(static_cast<unsigned char*>(m_data[band])[index])+theOffset;
1371 break;
1372 case(GDT_Int16):
1373 dvalue=theScale*(static_cast<short*>(m_data[band])[index])+theOffset;
1374 break;
1375 case(GDT_UInt16):
1376 dvalue=theScale*(static_cast<unsigned short*>(m_data[band])[index])+theOffset;
1377 break;
1378 case(GDT_Int32):
1379 dvalue=theScale*(static_cast<int*>(m_data[band])[index])+theOffset;
1380 break;
1381 case(GDT_UInt32):
1382 dvalue=theScale*(static_cast<unsigned int*>(m_data[band])[index])+theOffset;
1383 break;
1384 case(GDT_Float32):
1385 dvalue=theScale*(static_cast<float*>(m_data[band])[index])+theOffset;
1386 break;
1387 case(GDT_Float64):
1388 dvalue=theScale*(static_cast<double*>(m_data[band])[index])+theOffset;
1389 break;
1390 default:
1391 std::string errorString="Error: data type not supported";
1392 throw(errorString);
1393 break;
1394 }
1395 value=static_cast<T>(dvalue);
1396 }
1397 else{
1398 std::ostringstream s;
1399 s << "Error: read 3D image only supported for in memory images";
1400 throw(s.str());
1401 }
1402 }
1403 catch(std::string errorString){
1404 std::cerr << errorString << std::endl;
1405 throw;
1406 }
1407 catch(...){
1408 throw;
1409 }
1410 return(CE_None);
1411 }
1412
1413 template<typename T> CPLErr Jim::readData3D(std::vector<T>& buffer, std::size_t minCol, std::size_t maxCol, std::size_t row, std::size_t plane, std::size_t band)
1414 {
1415 try{
1416 if(nrOfBand()<=band){
1417 std::string errorString="Error: band number exceeds number of bands in input image";
1418 throw(errorString);
1419 }
1420 if(nrOfRow()<=row){
1421 std::string errorString="Error: row number exceeds number of rows in input image";
1422 throw(errorString);
1423 }
1424 if(nrOfPlane()<=plane){
1425 std::string errorString="Error: plane number exceeds number of planes in input image";
1426 throw(errorString);
1427 }
1428 double theScale=1;
1429 double theOffset=0;
1430 if(m_scale.size()>band||m_offset.size()>band){
1431 if(m_scale.size()>band)
1432 theScale=m_scale[band];
1433 if(m_offset.size()>band)
1434 theOffset=m_offset[band];
1435 }
1436 if(m_data.size()){
1437 if(row<m_begin[band]||row>=m_end[band]){
1438 if(m_filename.size())
1439 readNewBlock(row,band);
1440 }
1441 if(buffer.size()!=maxCol-minCol+1)
1442 buffer.resize(maxCol-minCol+1);
1443 int index=plane*nrOfRow()*nrOfCol()+(row-m_begin[band])*nrOfCol();
1444 int minindex=(index+minCol);
1445 int maxindex=(index+maxCol);
1446 /* if(type2GDAL<T>()==getDataType()){//no conversion needed */
1447 /* buffer.assign(static_cast<T*>(m_data[band])+minindex,static_cast<T*>(m_data[band])+maxindex); */
1448 /* typename std::vector<T>::iterator bufit=buffer.begin(); */
1449 /* while(bufit!=buffer.end()){ */
1450 /* double dvalue=theScale*(*bufit)+theOffset; */
1451 /* *(bufit++)=static_cast<T>(dvalue); */
1452 /* } */
1453 /* } */
1454 /* else{ */
1455 typename std::vector<T>::iterator bufit=buffer.begin();
1456 for(index=minindex;index<=maxindex;++index,++bufit){
1457 double dvalue=0;
1458 switch(getDataType()){
1459 case(GDT_Byte):
1460 dvalue=theScale*(static_cast<unsigned char*>(m_data[band])[index])+theOffset;
1461 break;
1462 case(GDT_Int16):
1463 dvalue=theScale*(static_cast<short*>(m_data[band])[index])+theOffset;
1464 break;
1465 case(GDT_UInt16):
1466 dvalue=theScale*(static_cast<unsigned short*>(m_data[band])[index])+theOffset;
1467 break;
1468 case(GDT_Int32):
1469 dvalue=theScale*(static_cast<int*>(m_data[band])[index])+theOffset;
1470 break;
1471 case(GDT_UInt32):
1472 dvalue=theScale*(static_cast<unsigned int*>(m_data[band])[index])+theOffset;
1473 break;
1474 case(GDT_Float32):
1475 dvalue=theScale*(static_cast<float*>(m_data[band])[index])+theOffset;
1476 break;
1477 case(GDT_Float64):
1478 dvalue=theScale*(static_cast<double*>(m_data[band])[index])+theOffset;
1479 break;
1480 default:
1481 std::string errorString="Error: data type not supported";
1482 throw(errorString);
1483 break;
1484 }
1485 // double dvalue=theScale*(*(static_cast<double*>(m_data[band])+index))+theOffset;
1486 *(bufit)=static_cast<T>(dvalue);
1487 }
1488 }
1489 else{
1490 std::ostringstream s;
1491 s << "Error: read 3D image only supported for in memory images";
1492 throw(s.str());
1493 }
1494 }
1495 catch(std::string errorString){
1496 std::cerr << errorString << std::endl;
1497 throw;
1498 }
1499 catch(...){
1500 throw;
1501 }
1502 return(CE_None);
1503 }
1504
1505 /**
1506 * @param[out] buffer The vector with all cell values that were read
1507 * @param[in] minCol First column from where to start reading (counting starts from 0)
1508 * @param[in] maxCol Last column that must be read (counting starts from 0)
1509 * @param[in] row The row number to read (counting starts from 0)
1510 * @param[in] band The band number to read (counting starts from 0)
1511 **/
1512 template<typename T> CPLErr Jim::readData(std::vector<T>& buffer, int minCol, int maxCol, int row, int band)
1513 {
1514 CPLErr returnValue=CE_None;
1515 try{
1516 if(nrOfBand()<=band){
1517 std::string errorString="Error: band number exceeds number of bands in input image";
1518 throw(errorString);
1519 }
1520 if(maxCol<minCol){
1521 std::string errorString="Error: maxCol must be larger or equal to minCol";
1522 throw(errorString);
1523 }
1524 if(minCol<0){
1525 std::string errorString="Error: col number must be positive";
1526 throw(errorString);
1527 }
1528 if(maxCol<0){
1529 std::string errorString="Error: col number must be positive";
1530 throw(errorString);
1531 }
1532 if(row<0){
1533 std::string errorString="Error: row number must be positive";
1534 throw(errorString);
1535 }
1536 if(nrOfCol()<=minCol){
1537 std::string errorString="Error: col number exceeds number of cols in input image";
1538 throw(errorString);
1539 }
1540 if(nrOfCol()<=maxCol){
1541 std::string errorString="Error: col number exceeds number of cols in input image";
1542 throw(errorString);
1543 }
1544 if(nrOfRow()<=row){
1545 std::string errorString="Error: row number exceeds number of rows in input image";
1546 throw(errorString);
1547 }
1548 double theScale=1;
1549 double theOffset=0;
1550 if(m_scale.size()>band||m_offset.size()>band){
1551 if(m_scale.size()>band)
1552 theScale=m_scale[band];
1553 if(m_offset.size()>band)
1554 theOffset=m_offset[band];
1555 }
1556 if(m_data.size()){
1557 if(row<m_begin[band]||row>=m_end[band]){
1558 if(m_filename.size())
1559 returnValue=readNewBlock(row,band);
1560 }
1561 if(buffer.size()!=maxCol-minCol+1)
1562 buffer.resize(maxCol-minCol+1);
1563 int index=(row-m_begin[band])*nrOfCol();
1564 int minindex=(index+minCol);
1565 int maxindex=(index+maxCol);
1566 /* if(type2GDAL<T>()==getDataType()){//no conversion needed */
1567 /* buffer.assign(static_cast<T*>(m_data[band])+minindex,static_cast<T*>(m_data[band])+maxindex); */
1568 /* typename std::vector<T>::iterator bufit=buffer.begin(); */
1569 /* while(bufit!=buffer.end()){ */
1570 /* double dvalue=theScale*(*bufit)+theOffset; */
1571 /* *(bufit++)=static_cast<T>(dvalue); */
1572 /* } */
1573 /* } */
1574 /* else{ */
1575 typename std::vector<T>::iterator bufit=buffer.begin();
1576 for(index=minindex;index<=maxindex;++index,++bufit){
1577 double dvalue=0;
1578 switch(getDataType()){
1579 case(GDT_Byte):
1580 dvalue=theScale*(static_cast<unsigned char*>(m_data[band])[index])+theOffset;
1581 break;
1582 case(GDT_Int16):
1583 dvalue=theScale*(static_cast<short*>(m_data[band])[index])+theOffset;
1584 break;
1585 case(GDT_UInt16):
1586 dvalue=theScale*(static_cast<unsigned short*>(m_data[band])[index])+theOffset;
1587 break;
1588 case(GDT_Int32):
1589 dvalue=theScale*(static_cast<int*>(m_data[band])[index])+theOffset;
1590 break;
1591 case(GDT_UInt32):
1592 dvalue=theScale*(static_cast<unsigned int*>(m_data[band])[index])+theOffset;
1593 break;
1594 case(GDT_Float32):
1595 dvalue=theScale*(static_cast<float*>(m_data[band])[index])+theOffset;
1596 break;
1597 case(GDT_Float64):
1598 dvalue=theScale*(static_cast<double*>(m_data[band])[index])+theOffset;
1599 break;
1600 default:
1601 std::string errorString="Error: data type not supported";
1602 throw(errorString);
1603 break;
1604 }
1605 // double dvalue=theScale*(*(static_cast<double*>(m_data[band])+index))+theOffset;
1606 *(bufit)=static_cast<T>(dvalue);
1607 }
1608 }
1609 else{
1610 //fetch raster band
1611 GDALRasterBand *poBand;
1612 poBand = m_gds->GetRasterBand(band+1);//GDAL uses 1 based index
1613 if(buffer.size()!=maxCol-minCol+1)
1614 buffer.resize(maxCol-minCol+1);
1615 returnValue=poBand->RasterIO(GF_Read,minCol,row,buffer.size(),1,&(buffer[0]),buffer.size(),1,type2GDAL<T>(),0,0);
1616 if(m_scale.size()>band||m_offset.size()>band){
1617 for(int index=0;index<buffer.size();++index)
1618 buffer[index]=theScale*static_cast<double>(buffer[index])+theOffset;
1619 }
1620 }
1621 return(returnValue);
1622 }
1623 catch(std::string errorString){
1624 std::cerr << errorString << std::endl;
1625 throw;
1626 }
1627 catch(...){
1628 throw;
1629 }
1630 }
1631
1632 /**
1633 * @param[out] buffer The vector with all cell values that were read
1634 * @param[in] minCol First column from where to start reading (counting starts from 0)
1635 * @param[in] maxCol Last column that must be read (counting starts from 0)
1636 * @param[in] row The row number to read (counting starts from 0)
1637 * @param[in] band The band number to read (counting starts from 0)
1638 * @param[in] resample The resampling method (currently only BILINEAR and NEAR are supported)
1639 **/
1640 template<typename T> CPLErr Jim::readData(std::vector<T>& buffer, int minCol, int maxCol, double row, int band, RESAMPLE resample)
1641 {
1642 CPLErr returnValue=CE_None;
1643 std::vector<T> readBuffer_upper;
1644 std::vector<T> readBuffer_lower;
1645 if(buffer.size()!=maxCol-minCol+1)
1646 buffer.resize(maxCol-minCol+1);
1647 double upperRow=row-0.5;
1648 upperRow=static_cast<int>(upperRow+FLT_EPSILON);
1649 double lowerRow=row+0.5;
1650 lowerRow=static_cast<int>(lowerRow+FLT_EPSILON);
1651 switch(resample){
1652 case(BILINEAR):
1653 if(lowerRow>=nrOfRow())
1654 lowerRow=nrOfRow()-1;
1655 if(upperRow<0)
1656 upperRow=0;
1657 returnValue=readData(readBuffer_upper,minCol,maxCol,static_cast<int>(upperRow),band);
1658 returnValue=readData(readBuffer_lower,minCol,maxCol,static_cast<int>(lowerRow),band);
1659 //do interpolation in y
1660 for(int icol=0;icol<maxCol-minCol+1;++icol){
1661 //buffer[icol]=(lowerRow-row+0.5)*readBuffer_upper[icol]+(1-lowerRow+row-0.5)*readBuffer_lower[icol];
1662 double upperVal = readBuffer_upper[icol];
1663 double lowerVal = readBuffer_lower[icol];
1664 if (!isNoData(upperVal)) {
1665 if (!isNoData(lowerVal))
1666 buffer[icol]=(lowerRow-row+0.5)*upperVal+(1-lowerRow+row-0.5)*lowerVal;
1667 else
1668 buffer[icol] = upperVal;
1669 }
1670 else
1671 buffer[icol] = lowerVal;
1672 }
1673 break;
1674 default:
1675 //returnValue=readData(buffer,minCol,maxCol,static_cast<int>(row),band);
1676 returnValue=readData(buffer,minCol,maxCol,static_cast<int>(row+FLT_EPSILON),band);
1677 break;
1678 }
1679 return(returnValue);
1680 }
1681
1682 /**
1683 * @param[out] buffer2d Two dimensional vector of type Vector2d (stl vector of stl vector) representing [row][col]. This vector contains all cell values that were read
1684 * @param[in] minCol First column from where to start reading (counting starts from 0)
1685 * @param[in] maxCol Last column that must be read (counting starts from 0)
1686 * @param[in] minRow First row from where to start reading (counting starts from 0)
1687 * @param[in] maxRow Last row that must be read (counting starts from 0)
1688 * @param[in] band The band number to read (counting starts from 0)
1689 **/
1690 template<typename T> CPLErr Jim::readDataBlock(Vector2d<T>& buffer2d, int minCol, int maxCol, int minRow, int maxRow, int band)
1691 {
1692 CPLErr returnValue=CE_None;
1693 buffer2d.resize(maxRow-minRow+1,maxCol-minCol+1);
1694 typename std::vector<T> buffer;
1695 returnValue=readDataBlock(buffer,minCol,maxCol,minRow,maxRow,band);
1696 typename std::vector<T>::const_iterator startit=buffer.begin();
1697 typename std::vector<T>::const_iterator endit=startit;
1698 for(int irow=minRow;irow<=maxRow;++irow){
1699 //buffer2d[irow-minRow].resize(maxCol-minCol+1);
1700 endit+=maxCol-minCol+1;
1701 buffer2d[irow-minRow].assign(startit,endit);
1702 startit+=maxCol-minCol+1;
1703 }
1704 return(returnValue);
1705 }
1706
1707 template<typename T> CPLErr Jim::readDataBlock3D(Vector2d<T>& buffer2d, std::size_t minCol, std::size_t maxCol, std::size_t minRow, std::size_t maxRow, std::size_t plane, std::size_t band){
1708 CPLErr returnValue=CE_None;
1709 buffer2d.resize(maxRow-minRow+1,maxCol-minCol+1);
1710 typename std::vector<T> buffer;
1711 returnValue = readDataBlock3D(buffer,minCol,maxCol,minRow,maxRow,plane,band);
1712 typename std::vector<T>::const_iterator startit=buffer.begin();
1713 typename std::vector<T>::const_iterator endit=startit;
1714 for(int irow=minRow;irow<=maxRow;++irow){
1715 //buffer2d[irow-minRow].resize(maxCol-minCol+1);
1716 endit+=maxCol-minCol+1;
1717 buffer2d[irow-minRow].assign(startit,endit);
1718 startit+=maxCol-minCol+1;
1719 }
1720 return(returnValue);
1721 }
1722
1723 /**
1724 * @param[out] buffer One dimensional vector representing all pixel values read starting from upper left to lower right.
1725 * @param[in] minCol First column from where to start reading (counting starts from 0)
1726 * @param[in] maxCol Last column that must be read (counting starts from 0)
1727 * @param[in] minRow First row from where to start reading (counting starts from 0)
1728 * @param[in] maxRow Last row that must be read (counting starts from 0)
1729 * @param[in] band The band number to read (counting starts from 0)
1730 **/
1731 template<typename T> CPLErr Jim::readDataBlock(std::vector<T>& buffer, int minCol, int maxCol, int minRow, int maxRow, int band)
1732 {
1733 try{
1734 CPLErr returnValue=CE_None;
1735 double theScale=1;
1736 double theOffset=0;
1737 if(m_scale.size()>band)
1738 theScale=m_scale[band];
1739 if(m_offset.size()>band)
1740 theOffset=m_offset[band];
1741 if(minCol>=nrOfCol() ||
1742 (minCol<0) ||
1743 (maxCol>=nrOfCol()) ||
1744 (minCol>maxCol) ||
1745 (minRow>=nrOfRow()) ||
1746 (minRow<0) ||
1747 (maxRow>=nrOfRow()) ||
1748 (minRow>maxRow)){
1749 std::string errorString="block not within image boundaries";
1750 throw(errorString);
1751 }
1752 if(buffer.size()!=(maxRow-minRow+1)*(maxCol-minCol+1))
1753 buffer.resize((maxRow-minRow+1)*(maxCol-minCol+1));
1754 if(m_data.size()){
1755 typename std::vector<T>::iterator bufit=buffer.begin();
1756 for(int irow=minRow;irow<=maxRow;++irow){
1757 if(irow<m_begin[band]||irow>=m_end[band]){
1758 if(m_filename.size())
1759 returnValue=readNewBlock(irow,band);
1760 }
1761 int index=(irow-m_begin[band])*nrOfCol();
1762 int minindex=(index+minCol);
1763 int maxindex=(index+maxCol);
1764
1765 for(index=minindex;index<=maxindex;++index,++bufit){
1766 double dvalue=0;
1767 switch(getDataType()){
1768 case(GDT_Byte):
1769 dvalue=theScale*(static_cast<unsigned char*>(m_data[band])[index])+theOffset;
1770 break;
1771 case(GDT_Int16):
1772 dvalue=theScale*(static_cast<short*>(m_data[band])[index])+theOffset;
1773 break;
1774 case(GDT_UInt16):
1775 dvalue=theScale*(static_cast<unsigned short*>(m_data[band])[index])+theOffset;
1776 break;
1777 case(GDT_Int32):
1778 dvalue=theScale*(static_cast<int*>(m_data[band])[index])+theOffset;
1779 break;
1780 case(GDT_UInt32):
1781 dvalue=theScale*(static_cast<unsigned int*>(m_data[band])[index])+theOffset;
1782 break;
1783 case(GDT_Float32):
1784 dvalue=theScale*(static_cast<float*>(m_data[band])[index])+theOffset;
1785 break;
1786 case(GDT_Float64):
1787 dvalue=theScale*(static_cast<double*>(m_data[band])[index])+theOffset;
1788 break;
1789 default:
1790 std::string errorString="Error: data type not supported";
1791 throw(errorString);
1792 break;
1793 }
1794 *(bufit)=static_cast<T>(dvalue);
1795 }//for index
1796 }
1797 }
1798 else{
1799 //fetch raster band
1800 GDALRasterBand *poBand;
1801 if(nrOfBand()<=band){
1802 std::string errorString="Error: band number exceeds number of bands in input image";
1803 throw(errorString);
1804 }
1805 poBand = m_gds->GetRasterBand(band+1);//GDAL uses 1 based index
1806 returnValue=poBand->RasterIO(GF_Read,minCol,minRow,maxCol-minCol+1,maxRow-minRow+1,&(buffer[0]),(maxCol-minCol+1),(maxRow-minRow+1),type2GDAL<T>(),0,0);
1807 if(m_scale.size()>band||m_offset.size()>band){
1808 for(int index=0;index<buffer.size();++index)
1809 buffer[index]=theScale*buffer[index]+theOffset;
1810 }
1811 }
1812 return(returnValue);
1813 }
1814 catch(std::string errorString){
1815 std::cerr << errorString << std::endl;
1816 throw;
1817 }
1818 catch(...){
1819 throw;
1820 }
1821 }
1822
1823 template<typename T> CPLErr Jim::readDataBlock3D(std::vector<T>& buffer, std::size_t minCol, std::size_t maxCol, std::size_t minRow, std::size_t maxRow, std::size_t plane, std::size_t band)
1824 {
1825 CPLErr returnValue=CE_None;
1826 try{
1827 double theScale=1;
1828 double theOffset=0;
1829 if(m_scale.size()>band)
1830 theScale=m_scale[band];
1831 if(m_offset.size()>band)
1832 theOffset=m_offset[band];
1833 if(minCol>=nrOfCol() ||
1834 (minCol<0) ||
1835 (maxCol>=nrOfCol()) ||
1836 (minCol>maxCol) ||
1837 (minRow>=nrOfRow()) ||
1838 (minRow<0) ||
1839 (maxRow>=nrOfRow()) ||
1840 (minRow>maxRow) ||
1841 (plane>=nrOfPlane()) ||
1842 (plane<0)){
1843 std::string errorString="block not within image boundaries";
1844 throw(errorString);
1845 }
1846 if(buffer.size()!=(maxRow-minRow+1)*(maxCol-minCol+1))
1847 buffer.resize((maxRow-minRow+1)*(maxCol-minCol+1));
1848 if(m_data.size()){
1849 typename std::vector<T>::iterator bufit=buffer.begin();
1850 for(int irow=minRow;irow<=maxRow;++irow){
1851 if(irow<m_begin[band]||irow>=m_end[band]){
1852 if(m_filename.size())
1853 readNewBlock(irow,band);
1854 }
1855 /* int index=(irow-m_begin[band])*nrOfCol(); */
1856 std::size_t index=(plane*nrOfRow()*nrOfCol())+(irow-m_begin[band])*nrOfCol();
1857 std::size_t minindex=(index+minCol);
1858 std::size_t maxindex=(index+maxCol);
1859
1860 for(index=minindex;index<=maxindex;++index,++bufit){
1861 double dvalue=0;
1862 switch(getDataType()){
1863 case(GDT_Byte):
1864 dvalue=theScale*(static_cast<unsigned char*>(m_data[band])[index])+theOffset;
1865 break;
1866 case(GDT_Int16):
1867 dvalue=theScale*(static_cast<short*>(m_data[band])[index])+theOffset;
1868 break;
1869 case(GDT_UInt16):
1870 dvalue=theScale*(static_cast<unsigned short*>(m_data[band])[index])+theOffset;
1871 break;
1872 case(GDT_Int32):
1873 dvalue=theScale*(static_cast<int*>(m_data[band])[index])+theOffset;
1874 break;
1875 case(GDT_UInt32):
1876 dvalue=theScale*(static_cast<unsigned int*>(m_data[band])[index])+theOffset;
1877 break;
1878 case(GDT_Float32):
1879 dvalue=theScale*(static_cast<float*>(m_data[band])[index])+theOffset;
1880 break;
1881 case(GDT_Float64):
1882 dvalue=theScale*(static_cast<double*>(m_data[band])[index])+theOffset;
1883 break;
1884 default:
1885 std::string errorString="Error: data type not supported";
1886 throw(errorString);
1887 break;
1888 }
1889 *(bufit)=static_cast<T>(dvalue);
1890 }//for index
1891 }
1892 }
1893 }
1894 catch(std::string errorString){
1895 std::cerr << errorString << std::endl;
1896 throw;
1897 }
1898 catch(...){
1899 throw;
1900 }
1901 return(returnValue);
1902 }
1903
1904 /**
1905 * @param[out] buffer The vector with all cell values that were read
1906 * @param[in] row The row number to read (counting starts from 0)
1907 * @param[in] band The band number to read (counting starts from 0)
1908 **/
1909 template<typename T> CPLErr Jim::readData(std::vector<T>& buffer, int row, int band)
1910 {
1911 return(readData(buffer,0,nrOfCol()-1,row,band));
1912 }
1913
1914 /**
1915 * @param[out] buffer The vector with all cell values that were read
1916 * @param[in] row The row number to read (counting starts from 0)
1917 * @param[in] band The band number to read (counting starts from 0)
1918 * @param[in] resample The resampling method (currently only BILINEAR and NEAR are supported).
1919 **/
1920 template<typename T> CPLErr Jim::readData(std::vector<T>& buffer, double row, int band, RESAMPLE resample)
1921 {
1922 return(readData(buffer,0,nrOfCol()-1,row,band,resample));
1923 }
1924
1925 //From Writer
1926 /**
1927 * @param[in] value The cell value to write
1928 * @param[in] col The column number to write (counting starts from 0)
1929 * @param[in] row The row number to write (counting starts from 0)
1930 * @param[in] band The band number to write (counting starts from 0)
1931 * @return true if write successful
1932 **/
1933 template<typename T> CPLErr Jim::writeData(const T& value, int col, int row, int band)
1934 {
1935 CPLErr returnValue=CE_None;
1936 if(band>=nrOfBand()+1){
1937 std::ostringstream s;
1938 s << "Error: band (" << band << ") exceeds nrOfBand (" << nrOfBand() << ")";
1939 throw(s.str());
1940 }
1941 if(col>=nrOfCol()){
1942 std::ostringstream s;
1943 s << "Error: col (" << col << ") exceeds nrOfCol (" << nrOfCol() << ")";
1944 throw(s.str());
1945 }
1946 if(col<0){
1947 std::ostringstream s;
1948 s << "Error: col (" << col << ") is negative";
1949 throw(s.str());
1950 }
1951 if(row>=nrOfRow()){
1952 std::ostringstream s;
1953 s << "Error: row (" << row << ") exceeds nrOfRow (" << nrOfRow() << ")";
1954 throw(s.str());
1955 }
1956 if(row<0){
1957 std::ostringstream s;
1958 s << "Error: row (" << row << ") is negative";
1959 throw(s.str());
1960 }
1961 double theScale=1;
1962 double theOffset=0;
1963 if(m_scale.size()>band||m_offset.size()>band){
1964 if(m_scale.size()>band)
1965 theScale=m_scale[band];
1966 if(m_offset.size()>band)
1967 theOffset=m_offset[band];
1968 }
1969 if(m_data.size()){
1970 //only support random access writing if entire image is in memory
1971 if(m_blockSize!=nrOfRow()){
1972 std::ostringstream s;
1973 s << "Error: increase memory to support random access writing (now at " << 100.0*m_blockSize/nrOfRow() << "%)";
1974 throw(s.str());
1975 }
1976 int index=(row-m_begin[band])*nrOfCol()+col;
1977 double dvalue=theScale*value+theOffset;
1978 switch(getDataType()){
1979 case(GDT_Byte):
1980 static_cast<unsigned char*>(m_data[band])[index]=static_cast<unsigned char>(dvalue);
1981 break;
1982 case(GDT_Int16):
1983 static_cast<short*>(m_data[band])[index]=static_cast<short>(dvalue);
1984 break;
1985 case(GDT_UInt16):
1986 static_cast<unsigned short*>(m_data[band])[index]=static_cast<unsigned short>(dvalue);
1987 break;
1988 case(GDT_Int32):
1989 static_cast<int*>(m_data[band])[index]=static_cast<int>(dvalue);
1990 break;
1991 case(GDT_UInt32):
1992 static_cast<unsigned int*>(m_data[band])[index]=static_cast<unsigned int>(dvalue);
1993 break;
1994 case(GDT_Float32):
1995 static_cast<float*>(m_data[band])[index]=static_cast<float>(dvalue);
1996 break;
1997 case(GDT_Float64):
1998 static_cast<double*>(m_data[band])[index]=static_cast<double>(dvalue);
1999 break;
2000 default:
2001 std::string errorString="Error: data type not supported";
2002 throw(errorString);
2003 break;
2004 }
2005 }
2006 else{
2007 //fetch raster band
2008 GDALRasterBand *poBand;
2009 T dvalue=theScale*value+theOffset;
2010 returnValue=poBand->RasterIO(GF_Write,col,row,1,1,&dvalue,1,1,type2GDAL<T>(),0,0);
2011 }
2012 return(returnValue);
2013 }
2014
2015 template<typename T> CPLErr Jim::writeData(std::vector<T>& buffer, int minCol, int maxCol, int row, int band)
2016 {
2017 CPLErr returnValue=CE_None;
2018 if(buffer.size()!=maxCol-minCol+1){
2019 std::string errorstring="invalid size of buffer";
2020 throw(errorstring);
2021 }
2022 if(minCol>=nrOfCol()){
2023 std::ostringstream s;
2024 s << "minCol (" << minCol << ") exceeds nrOfCol (" << nrOfCol() << ")";
2025 throw(s.str());
2026 }
2027 if(minCol<0){
2028 std::ostringstream s;
2029 s << "mincol (" << minCol << ") is negative";
2030 throw(s.str());
2031 }
2032 if(maxCol>=nrOfCol()){
2033 std::ostringstream s;
2034 s << "maxCol (" << maxCol << ") exceeds nrOfCol (" << nrOfCol() << ")";
2035 throw(s.str());
2036 }
2037 if(maxCol<minCol){
2038 std::ostringstream s;
2039 s << "maxCol (" << maxCol << ") is less than minCol (" << minCol << ")";
2040 throw(s.str());
2041 }
2042 if(row>=nrOfRow()){
2043 std::ostringstream s;
2044 s << "row (" << row << ") exceeds nrOfRow (" << nrOfRow() << ")";
2045 throw(s.str());
2046 }
2047 if(row<0){
2048 std::ostringstream s;
2049 s << "row (" << row << ") is negative";
2050 throw(s.str());
2051 }
2052 if(m_data.size()){
2053 if(minCol>0){
2054 std::ostringstream s;
2055 s << "Error: increase memory to support random access writing (now at " << 100.0*m_blockSize/nrOfRow() << "%)";
2056 throw(s.str());
2057 }
2058 if(row>=m_end[band]){
2059 if(row>=m_end[band]+m_blockSize){
2060 std::ostringstream s;
2061 s << "Error: increase memory to support random access writing (now at " << 100.0*m_blockSize/nrOfRow() << "%)";
2062 throw(s.str());
2063 }
2064 else if(m_filename.size())
2065 returnValue=writeNewBlock(row,band);
2066 }
2067 int index=(row-m_begin[band])*nrOfCol();
2068 int minindex=(index+minCol);
2069 int maxindex=(index+maxCol);
2070 typename std::vector<T>::const_iterator bufit=buffer.begin();
2071 double theScale=1;
2072 double theOffset=0;
2073 if(m_scale.size()>band)
2074 theScale=m_scale[band];
2075 if(m_offset.size()>band)
2076 theOffset=m_offset[band];
2077 for(index=minindex;index<=maxindex;++index,++bufit){
2078 double dvalue=theScale*(*(bufit))+theOffset;
2079 switch(getDataType()){
2080 case(GDT_Byte):
2081 static_cast<unsigned char*>(m_data[band])[index]=static_cast<unsigned char>(dvalue);
2082 break;
2083 case(GDT_Int16):
2084 static_cast<short*>(m_data[band])[index]=static_cast<short>(dvalue);
2085 break;
2086 case(GDT_UInt16):
2087 static_cast<unsigned short*>(m_data[band])[index]=static_cast<unsigned short>(dvalue);
2088 break;
2089 case(GDT_Int32):
2090 static_cast<int*>(m_data[band])[index]=static_cast<int>(dvalue);
2091 break;
2092 case(GDT_UInt32):
2093 static_cast<unsigned int*>(m_data[band])[index]=static_cast<unsigned int>(dvalue);
2094 break;
2095 case(GDT_Float32):
2096 static_cast<float*>(m_data[band])[index]=static_cast<float>(dvalue);
2097 break;
2098 case(GDT_Float64):
2099 static_cast<double*>(m_data[band])[index]=static_cast<double>(dvalue);
2100 break;
2101 default:
2102 std::string errorString="Error: data type not supported";
2103 throw(errorString);
2104 break;
2105 }
2106 }
2107 }
2108 else{
2109 //todo: scaling and offset!
2110 //fetch raster band
2111 GDALRasterBand *poBand;
2112 if(band>=nrOfBand()+1){
2113 std::ostringstream s;
2114 s << "band (" << band << ") exceeds nrOfBand (" << nrOfBand() << ")";
2115 throw(s.str());
2116 }
2117 poBand = m_gds->GetRasterBand(band+1);//GDAL uses 1 based index
2118 returnValue=poBand->RasterIO(GF_Write,minCol,row,buffer.size(),1,&(buffer[0]),buffer.size(),1,type2GDAL<T>(),0,0);
2119 }
2120 return(returnValue);
2121 }
2122
2123 /* template<typename T> void Jim::writeData3D(std::vector<T>& buffer, std::size_t minCol, std::size_t maxCol, std::size_t row, std::size_t plane, std::size_t band) */
2124 /* { */
2125 /* if(buffer.size()!=maxCol-minCol+1){ */
2126 /* std::string errorstring="invalid size of buffer"; */
2127 /* throw(errorstring); */
2128 /* } */
2129 /* if(minCol>=nrOfCol()){ */
2130 /* std::ostringstream s; */
2131 /* s << "minCol (" << minCol << ") exceeds nrOfCol (" << nrOfCol() << ")"; */
2132 /* throw(s.str()); */
2133 /* } */
2134 /* if(minCol<0){ */
2135 /* std::ostringstream s; */
2136 /* s << "mincol (" << minCol << ") is negative"; */
2137 /* throw(s.str()); */
2138 /* } */
2139 /* if(maxCol>=nrOfCol()){ */
2140 /* std::ostringstream s; */
2141 /* s << "maxCol (" << maxCol << ") exceeds nrOfCol (" << nrOfCol() << ")"; */
2142 /* throw(s.str()); */
2143 /* } */
2144 /* if(maxCol<minCol){ */
2145 /* std::ostringstream s; */
2146 /* s << "maxCol (" << maxCol << ") is less than minCol (" << minCol << ")"; */
2147 /* throw(s.str()); */
2148 /* } */
2149 /* if(row>=nrOfRow()){ */
2150 /* std::ostringstream s; */
2151 /* s << "row (" << row << ") exceeds nrOfRow (" << nrOfRow() << ")"; */
2152 /* throw(s.str()); */
2153 /* } */
2154 /* if(row<0){ */
2155 /* std::ostringstream s; */
2156 /* s << "row (" << row << ") is negative"; */
2157 /* throw(s.str()); */
2158 /* } */
2159 /* if(plane>=nrOfPlane()){ */
2160 /* std::ostringstream s; */
2161 /* s << "plane (" << plane << ") exceeds nrOfPlane (" << nrOfPlane() << ")"; */
2162 /* throw(s.str()); */
2163 /* } */
2164 /* if(plane<0){ */
2165 /* std::ostringstream s; */
2166 /* s << "plane (" << plane << ") is negative"; */
2167 /* throw(s.str()); */
2168 /* } */
2169 /* if(m_data.size()){ */
2170 /* if(minCol>0){ */
2171 /* std::ostringstream s; */
2172 /* s << "Error: increase memory to support random access writing (now at " << 100.0*m_blockSize/nrOfRow() << "%)"; */
2173 /* throw(s.str()); */
2174 /* } */
2175 /* if(row>=m_end[band]){ */
2176 /* if(row>=m_end[band]+m_blockSize){ */
2177 /* std::ostringstream s; */
2178 /* s << "Error: increase memory to support random access writing (now at " << 100.0*m_blockSize/nrOfRow() << "%)"; */
2179 /* throw(s.str()); */
2180 /* } */
2181 /* else if(m_filename.size()) */
2182 /* writeNewBlock(row,band); */
2183 /* } */
2184 /* int index=plane*nrOfRow()*nrOfCol()+(row-m_begin[band])*nrOfCol(); */
2185 /* int minindex=(index+minCol); */
2186 /* int maxindex=(index+maxCol); */
2187 /* typename std::vector<T>::const_iterator bufit=buffer.begin(); */
2188 /* double theScale=1; */
2189 /* double theOffset=0; */
2190 /* if(m_scale.size()>band) */
2191 /* theScale=m_scale[band]; */
2192 /* if(m_offset.size()>band) */
2193 /* theOffset=m_offset[band]; */
2194 /* for(index=minindex;index<=maxindex;++index,++bufit){ */
2195 /* double dvalue=theScale*(*(bufit))+theOffset; */
2196 /* switch(getDataType()){ */
2197 /* case(GDT_Byte): */
2198 /* static_cast<unsigned char*>(m_data[band])[index]=static_cast<unsigned char>(dvalue); */
2199 /* break; */
2200 /* case(GDT_Int16): */
2201 /* static_cast<short*>(m_data[band])[index]=static_cast<short>(dvalue); */
2202 /* break; */
2203 /* case(GDT_UInt16): */
2204 /* static_cast<unsigned short*>(m_data[band])[index]=static_cast<unsigned short>(dvalue); */
2205 /* break; */
2206 /* case(GDT_Int32): */
2207 /* static_cast<int*>(m_data[band])[index]=static_cast<int>(dvalue); */
2208 /* break; */
2209 /* case(GDT_UInt32): */
2210 /* static_cast<unsigned int*>(m_data[band])[index]=static_cast<unsigned int>(dvalue); */
2211 /* break; */
2212 /* case(GDT_Float32): */
2213 /* static_cast<float*>(m_data[band])[index]=static_cast<float>(dvalue); */
2214 /* break; */
2215 /* case(GDT_Float64): */
2216 /* static_cast<double*>(m_data[band])[index]=static_cast<double>(dvalue); */
2217 /* break; */
2218 /* default: */
2219 /* std::string errorString="Error: data type not supported"; */
2220 /* throw(errorString); */
2221 /* break; */
2222 /* } */
2223 /* } */
2224 /* } */
2225 /* else{ */
2226 /* std::ostringstream s; */
2227 /* s << "writeData3D only supported for data in memory"; */
2228 /* throw(s.str()); */
2229 /* } */
2230 /* } */
2231
2232 /**
2233 * @param[in] buffer The vector with all cell values to write
2234 * @param[in] row The row number to write (counting starts from 0)
2235 * @param[in] band The band number to write (counting starts from 0)
2236 * @return true if write successful
2237 **/
2238 template<typename T> CPLErr Jim::writeData(std::vector<T>& buffer, int row, int band)
2239 {
2240 return writeData(buffer,0,nrOfCol()-1,row,band);
2241 }
2242
2243 /**
2244 * @param[in] buffer2d Two dimensional vector of type Vector2d (stl vector of stl vector) representing [row][col]. This vector contains all cell values that must be written
2245 * @param[in] minCol First column from where to start writing (counting starts from 0)
2246 * @param[in] maxCol Last column that must be written (counting starts from 0)
2247 * @param[in] row The row number to write (counting starts from 0)
2248 * @param[in] band The band number to write (counting starts from 0)
2249 * @return true if write successful
2250 **/
2251 template<typename T> CPLErr Jim::writeDataBlock(Vector2d<T>& buffer2d, int minCol, int maxCol, int minRow, int maxRow, int band)
2252 {
2253 CPLErr returnValue=CE_None;
2254 double theScale=1;
2255 double theOffset=0;
2256 if(m_scale.size()>band)
2257 theScale=m_scale[band];
2258 if(m_offset.size()>band)
2259 theOffset=m_offset[band];
2260 if(buffer2d.size()!=maxRow-minRow+1){
2261 std::string errorstring="invalid buffer size";
2262 throw(errorstring);
2263 }
2264 if(band>=nrOfBand()+1){
2265 std::ostringstream s;
2266 s << "band (" << band << ") exceeds nrOfBand (" << nrOfBand() << ")";
2267 throw(s.str());
2268 }
2269 if(minCol>=nrOfCol()){
2270 std::ostringstream s;
2271 s << "minCol (" << minCol << ") exceeds nrOfCol (" << nrOfCol() << ")";
2272 throw(s.str());
2273 }
2274 if(minCol<0){
2275 std::ostringstream s;
2276 s << "mincol (" << minCol << ") is negative";
2277 throw(s.str());
2278 }
2279 if(minCol>0){
2280 std::ostringstream s;
2281 s << "Error: increase memory to support random access writing (now at " << 100.0*m_blockSize/nrOfRow() << "%)";
2282 throw(s.str());
2283 }
2284 if(maxCol>=nrOfCol()){
2285 std::ostringstream s;
2286 s << "maxCol (" << maxCol << ") exceeds nrOfCol (" << nrOfCol() << ")";
2287 throw(s.str());
2288 }
2289 if(maxCol<minCol){
2290 std::ostringstream s;
2291 s << "maxCol (" << maxCol << ") is less than minCol (" << minCol << ")";
2292 throw(s.str());
2293 }
2294 if(m_data.size()){
2295 for(int irow=minRow;irow<=maxRow;++irow){
2296 if(irow>=nrOfRow()){
2297 std::ostringstream s;
2298 s << "row (" << irow << ") exceeds nrOfRow (" << nrOfRow() << ")";
2299 throw(s.str());
2300 }
2301 if(irow<0){
2302 std::ostringstream s;
2303 s << "row (" << irow << ") is negative";
2304 throw(s.str());
2305 }
2306 if(irow<m_begin[band]){
2307 std::ostringstream s;
2308 s << "Error: increase memory to support random access writing (now at " << 100.0*m_blockSize/nrOfRow() << "%)";
2309 throw(s.str());
2310 }
2311 if(irow>=m_end[band]){
2312 if(irow>=m_end[band]+m_blockSize){
2313 std::ostringstream s;
2314 s << "Error: increase memory to support random access writing (now at " << 100.0*m_blockSize/nrOfRow() << "%)";
2315 throw(s.str());
2316 }
2317 else if(m_filename.size())
2318 returnValue=writeNewBlock(irow,band);
2319 }
2320 int index=(irow-m_begin[band])*nrOfCol();
2321 int minindex=index+minCol;
2322 int maxindex=index+maxCol;
2323 typename std::vector<T>::iterator bufit=buffer2d[irow-minRow].begin();
2324 for(index=minindex;index<=maxindex;++index,++bufit){
2325 double dvalue=theScale*(*(bufit))+theOffset;
2326 switch(getDataType()){
2327 case(GDT_Byte):
2328 static_cast<unsigned char*>(m_data[band])[index]=static_cast<unsigned char>(dvalue);
2329 break;
2330 case(GDT_Int16):
2331 static_cast<short*>(m_data[band])[index]=static_cast<short>(dvalue);
2332 break;
2333 case(GDT_UInt16):
2334 static_cast<unsigned short*>(m_data[band])[index]=static_cast<unsigned short>(dvalue);
2335 break;
2336 case(GDT_Int32):
2337 static_cast<int*>(m_data[band])[index]=static_cast<int>(dvalue);
2338 break;
2339 case(GDT_UInt32):
2340 static_cast<unsigned int*>(m_data[band])[index]=static_cast<unsigned int>(dvalue);
2341 break;
2342 case(GDT_Float32):
2343 static_cast<float*>(m_data[band])[index]=static_cast<float>(dvalue);
2344 break;
2345 case(GDT_Float64):
2346 static_cast<double*>(m_data[band])[index]=static_cast<double>(dvalue);
2347 break;
2348 default:
2349 std::string errorString="Error: data type not supported";
2350 throw(errorString);
2351 break;
2352 }
2353 }
2354 }
2355 }
2356 else{
2357 //todo: apply scaling and offset!
2358 typename std::vector<T> buffer((maxRow-minRow+1)*(maxCol-minCol+1));
2359 //fetch raster band
2360 GDALRasterBand *poBand;
2361 // typename std::vector<T>::iterator startit=buffer.begin();
2362 for(int irow=minRow;irow<=maxRow;++irow){
2363 buffer.insert(buffer.begin()+(maxCol-minCol+1)*(irow-minRow),buffer2d[irow-minRow].begin(),buffer2d[irow-minRow].end());
2364 }
2365 poBand = m_gds->GetRasterBand(band+1);//GDAL uses 1 based index
2366 returnValue=poBand->RasterIO(GF_Write,minCol,minRow,maxCol-minCol+1,maxRow-minRow+1,&(buffer[0]),(maxCol-minCol+1),(maxRow-minRow+1),type2GDAL<T>(),0,0);
2367 }
2368 return(returnValue);
2369 }
2370
2371 template<typename T> CPLErr Jim::writeDataBlock(T value, int minCol, int maxCol, int minRow, int maxRow, int band){
2372 CPLErr returnValue=CE_None;
2373 double theScale=1;
2374 double theOffset=0;
2375 if(m_scale.size()>band)
2376 theScale=m_scale[band];
2377 if(m_offset.size()>band)
2378 theOffset=m_offset[band];
2379 if(band>=nrOfBand()+1){
2380 std::ostringstream s;
2381 s << "band (" << band << ") exceeds nrOfBand (" << nrOfBand() << ")";
2382 throw(s.str());
2383 }
2384 if(minCol>=nrOfCol()){
2385 std::ostringstream s;
2386 s << "minCol (" << minCol << ") exceeds nrOfCol (" << nrOfCol() << ")";
2387 throw(s.str());
2388 }
2389 if(minCol<0){
2390 std::ostringstream s;
2391 s << "mincol (" << minCol << ") is negative";
2392 throw(s.str());
2393 }
2394 if(minCol>0){
2395 std::ostringstream s;
2396 s << "Error: increase memory to support random access writing (now at " << 100.0*m_blockSize/nrOfRow() << "%)";
2397 throw(s.str());
2398 }
2399 if(maxCol>=nrOfCol()){
2400 std::ostringstream s;
2401 s << "maxCol (" << maxCol << ") exceeds nrOfCol (" << nrOfCol() << ")";
2402 throw(s.str());
2403 }
2404 if(maxCol<minCol){
2405 std::ostringstream s;
2406 s << "maxCol (" << maxCol << ") is less than minCol (" << minCol << ")";
2407 throw(s.str());
2408 }
2409 if(m_data.size()){
2410 for(int irow=minRow;irow<=maxRow;++irow){
2411 if(irow>=nrOfRow()){
2412 std::ostringstream s;
2413 s << "row (" << irow << ") exceeds nrOfRow (" << nrOfRow() << ")";
2414 throw(s.str());
2415 }
2416 if(irow<0){
2417 std::ostringstream s;
2418 s << "row (" << irow << ") is negative";
2419 throw(s.str());
2420 }
2421 if(irow<m_begin[band]){
2422 std::ostringstream s;
2423 s << "Error: increase memory to support random access writing (now at " << 100.0*m_blockSize/nrOfRow() << "%)";
2424 throw(s.str());
2425 }
2426 if(irow>=m_end[band]){
2427 if(irow>=m_end[band]+m_blockSize){
2428 std::ostringstream s;
2429 s << "Error: increase memory to support random access writing (now at " << 100.0*m_blockSize/nrOfRow() << "%)";
2430 throw(s.str());
2431 }
2432 else if(m_filename.size())
2433 returnValue=writeNewBlock(irow,band);
2434 }
2435 int index=(irow-m_begin[band])*nrOfCol();
2436 int minindex=index+minCol;
2437 int maxindex=index+maxCol;
2438 for(index=minindex;index<=maxindex;++index){
2439 double dvalue=value;
2440 switch(getDataType()){
2441 case(GDT_Byte):
2442 static_cast<unsigned char*>(m_data[band])[index]=static_cast<unsigned char>(dvalue);
2443 break;
2444 case(GDT_Int16):
2445 static_cast<short*>(m_data[band])[index]=static_cast<short>(dvalue);
2446 break;
2447 case(GDT_UInt16):
2448 static_cast<unsigned short*>(m_data[band])[index]=static_cast<unsigned short>(dvalue);
2449 break;
2450 case(GDT_Int32):
2451 static_cast<int*>(m_data[band])[index]=static_cast<int>(dvalue);
2452 break;
2453 case(GDT_UInt32):
2454 static_cast<unsigned int*>(m_data[band])[index]=static_cast<unsigned int>(dvalue);
2455 break;
2456 case(GDT_Float32):
2457 static_cast<float*>(m_data[band])[index]=static_cast<float>(dvalue);
2458 break;
2459 case(GDT_Float64):
2460 static_cast<double*>(m_data[band])[index]=static_cast<double>(dvalue);
2461 break;
2462 default:
2463 std::string errorString="Error: data type not supported";
2464 throw(errorString);
2465 break;
2466 }
2467 }
2468 }
2469 }
2470 else{
2471 //todo: apply scaling and offset!
2472 typename std::vector<T> buffer((maxRow-minRow+1)*(maxCol-minCol+1),value);
2473 //fetch raster band
2474 GDALRasterBand *poBand;
2475 poBand = m_gds->GetRasterBand(band+1);//GDAL uses 1 based index
2476 returnValue=poBand->RasterIO(GF_Write,minCol,minRow,maxCol-minCol+1,maxRow-minRow+1,&(buffer[0]),(maxCol-minCol+1),(maxRow-minRow+1),type2GDAL<T>(),0,0);
2477 }
2478 return(returnValue);
2479 }
2480
2481 #endif // _JIM_H_