Debian Codegraph @

src/imageclasses/jlextractimg_lib.h

raw symbols SCIP
1 /**********************************************************************
2 jlextractimg_lib.h: extract pixel values from raster image using a raster sample
3 Author(s): [email protected]
4 Copyright (C) 2016-2020 European Union (Joint Research Centre)
5
6 This file is part of jiplib.
7
8 jiplib is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
12
13 jiplib is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with jiplib. If not, see <https://www.gnu.org/licenses/>.
20 ***********************************************************************/
21 #ifndef _JLEXTRACTIMG_LIB_H_
22 #define _JLEXTRACTIMG_LIB_H_
23
24 #include <random>
25 #if JIPLIB_PROCESS_IN_PARALLEL == 1
26 #include <omp.h>
27 #endif
28 #include "imageclasses/Jim.h"
29 #include "imageclasses/VectorOgr.h"
30 #include "apps/AppFactory.h"
31
32 template<typename T> void Jim::extractImg_t(Jim& classReader, VectorOgr& ogrWriter, app::AppFactory& app){
33 Optionjl<std::string> output_opt("o", "output", "Output sample dataset");
34 Optionjl<std::string> layer_opt("ln", "ln", "output layer name","sample");
35 Optionjl<int> class_opt("c", "class", "Class(es) to extract from input sample image. Leave empty to extract all valid data pixels from sample dataset");
36 Optionjl<float> threshold_opt("t", "threshold", "Probability threshold for selecting samples (randomly). Provide probability in percentage (>0) or absolute (<0). If using raster land cover maps as a sample dataset, you can provide a threshold value for each class (e.g. -t 80 -t 60). Use value 100 to select all pixels for selected class(es)", 100);
37 Optionjl<std::string> ogrformat_opt("f", "oformat", "Output sample dataset format","SQLite");
38 Optionjl<std::string> option_opt("co", "co", "Creation option for output file. Multiple options can be specified.");
39 Optionjl<std::string> ftype_opt("ft", "ftype", "Field type (only Real or Integer)", "Real");
40 Optionjl<std::string> ltype_opt("lt", "ltype", "Label type: In16 or String", "Integer");
41 Optionjl<std::string> bandNames_opt("bn", "bandname", "Band name(s) corresponding to band index(es)","b");
42 Optionjl<std::string> planeNames_opt("bn", "planename", "Plane name(s) corresponding to plane index(es).");
43 Optionjl<double> srcnodata_opt("srcnodata", "srcnodata", "Invalid value for input image");
44 Optionjl<unsigned int> bndnodata_opt("bndnodata", "bndnodata", "Band in input image to check if pixel is valid (used for srcnodata)", 0);
45 Optionjl<std::string> attribute_opt("attribute", "attribute", "Name of the class label in the output vector dataset", "label");
46 Optionjl<std::string> fid_opt("fid", "fid", "Create extra field with field identifier (sequence in which the features have been read");
47 Optionjl<short> verbose_opt("v", "verbose", "Verbose mode if > 0", 0,2);
48
49 bndnodata_opt.setHide(1);
50 srcnodata_opt.setHide(1);
51 attribute_opt.setHide(1);
52 option_opt.setHide(1);
53
54 bool doProcess;//stop process when program was invoked with help option (-h --help)
55 try{
56 // doProcess=sample_opt.retrieveOption(app);
57 doProcess=output_opt.retrieveOption(app);
58 layer_opt.retrieveOption(app);
59 class_opt.retrieveOption(app);
60 threshold_opt.retrieveOption(app);
61 ogrformat_opt.retrieveOption(app);
62 option_opt.retrieveOption(app);
63 ftype_opt.retrieveOption(app);
64 ltype_opt.retrieveOption(app);
65 planeNames_opt.retrieveOption(app);
66 bandNames_opt.retrieveOption(app);
67 bndnodata_opt.retrieveOption(app);
68 srcnodata_opt.retrieveOption(app);
69 attribute_opt.retrieveOption(app);
70 fid_opt.retrieveOption(app);
71 verbose_opt.retrieveOption(app);
72 if(!doProcess){
73 std::cout << std::endl;
74 std::ostringstream helpStream;
75 helpStream << "short option -h shows basic options only, use long option --help to show all options" << std::endl;
76 throw(helpStream.str());//help was invoked, stop processing
77 }
78
79 std::vector<std::string> badKeys;
80 app.badKeys(badKeys);
81 if(badKeys.size()){
82 std::ostringstream errorStream;
83 if(badKeys.size()>1)
84 errorStream << "Error: unknown keys: ";
85 else
86 errorStream << "Error: unknown key: ";
87 for(int ikey=0;ikey<badKeys.size();++ikey){
88 errorStream << badKeys[ikey] << " ";
89 }
90 errorStream << std::endl;
91 throw(errorStream.str());
92 }
93 statfactory::StatFactory stat;
94 if(srcnodata_opt.size()){
95 while(srcnodata_opt.size()<bndnodata_opt.size())
96 srcnodata_opt.push_back(srcnodata_opt[0]);
97 stat.setNoDataValues(srcnodata_opt);
98 }
99 Vector2d<unsigned int> posdata;
100 /* unsigned long int nsample=0; */
101 /* unsigned long int ntotalvalid=0; */
102 /* unsigned long int ntotalinvalid=0; */
103
104 /* std::map<int,unsigned long int> nvalid; */
105 /* map<int,unsigned long int> ninvalid; */
106
107 /* map <int,short> classmap;//class->index */
108 /* for(int iclass=0;iclass<class_opt.size();++iclass){ */
109 /* nvalid[class_opt[iclass]]=0; */
110 /* ninvalid[class_opt[iclass]]=0; */
111 /* classmap[class_opt[iclass]]=iclass; */
112 /* } */
113
114 if(output_opt.empty()){
115 std::string errorString="Error: No output dataset provided (use option -o). Use --help for help information";
116 throw(errorString);
117 }
118
119 int nplane=nrOfPlane();
120 if(nplane>1){
121 if(planeNames_opt.size()<nplane){
122 planeNames_opt.clear();
123 for(size_t iplane=0;iplane<nplane;++iplane){
124 int thePlane=iplane;
125 std::ostringstream planestream;
126 planestream << "t" << thePlane;
127 planeNames_opt.push_back(planestream.str());
128 }
129 }
130 }
131 int nband=nrOfBand();
132
133 if(bandNames_opt.size()<nband){
134 std::string bandString=bandNames_opt[0];
135 bandNames_opt.clear();
136 bandNames_opt.resize(nband);
137 for(int iband=0;iband<nband;++iband){
138 std::ostringstream fs;
139 fs << bandString << iband;
140 bandNames_opt[iband]=fs.str();
141 }
142 }
143
144 if(verbose_opt[0]){
145 std::cout << planeNames_opt << std::endl;
146 std::cout << bandNames_opt << std::endl;
147 }
148 if(verbose_opt[0]>1){
149 std::cout << "Number of planes in input image: " << this->nrOfPlane() << std::endl;
150 std::cout << "Number of bands in input image: " << this->nrOfBand() << std::endl;
151 }
152
153 OGRFieldType fieldType;
154 OGRFieldType labelType;
155 int ogr_typecount=11;//hard coded for now!
156 if(verbose_opt[0]>1)
157 std::cout << "field and label types can be: ";
158 for(int iType = 0; iType < ogr_typecount; ++iType){
159 if(verbose_opt[0]>1)
160 std::cout << " " << OGRFieldDefn::GetFieldTypeName((OGRFieldType)iType);
161 if( OGRFieldDefn::GetFieldTypeName((OGRFieldType)iType) != NULL
162 && EQUAL(OGRFieldDefn::GetFieldTypeName((OGRFieldType)iType),
163 ftype_opt[0].c_str()))
164 fieldType=(OGRFieldType) iType;
165 if( OGRFieldDefn::GetFieldTypeName((OGRFieldType)iType) != NULL
166 && EQUAL(OGRFieldDefn::GetFieldTypeName((OGRFieldType)iType),
167 ltype_opt[0].c_str()))
168 labelType=(OGRFieldType) iType;
169 }
170 switch( fieldType ){
171 case OFTInteger:
172 case OFTReal:
173 case OFTRealList:
174 case OFTString:
175 if(verbose_opt[0]>1)
176 std::cout << std::endl << "field type is: " << OGRFieldDefn::GetFieldTypeName(fieldType) << std::endl;
177 break;
178 default:
179 std::ostringstream errorStream;
180 errorStream << "Error: field type " << OGRFieldDefn::GetFieldTypeName(fieldType) << " not supported";
181 throw(errorStream.str());
182 break;
183 }
184 switch( labelType ){
185 case OFTInteger:
186 case OFTReal:
187 case OFTRealList:
188 case OFTString:
189 if(verbose_opt[0]>1)
190 std::cout << std::endl << "label type is: " << OGRFieldDefn::GetFieldTypeName(labelType) << std::endl;
191 break;
192 default:
193 std::ostringstream errorStream;
194 errorStream << "Error: label type " << OGRFieldDefn::GetFieldTypeName(labelType) << " not supported";
195 throw(errorStream.str());
196 break;
197 }
198
199 srand(time(NULL));
200
201 size_t index=0;
202 unsigned short nclass=256;
203 std::vector< std::vector<size_t> > sample(nclass);//[class][index]
204 if(verbose_opt[0]>1)
205 std::cout << "extracting sample from image..." << std::endl;
206
207
208 std::vector<size_t> nvalid(nclass);
209 std::vector<size_t> ninvalid(nclass);
210 double x=0;//geo x coordinate
211 double y=0;//geo y coordinate
212 T* pim=0;
213
214 unsigned char* pmask=0;
215 for(size_t irow=0;irow<nrOfRow();++irow){
216 for(size_t icol=0;icol<nrOfCol();++icol){
217 bool validData=true;
218 bool validClass=class_opt.empty();//if no classes are defined, process all classes
219 index=icol+irow*nrOfCol();
220 if(srcnodata_opt.size()){
221 pim=static_cast<T*>(getDataPointer(bndnodata_opt[0]));
222 if(pim[index]==srcnodata_opt[0])
223 validData=false;
224 }
225 pmask=static_cast<unsigned char*>(classReader.getDataPointer(0));
226 unsigned short readClass=pmask[index];
227 if(validData){
228 if(class_opt.size()){
229 for(int iclass=0;iclass<class_opt.size();++iclass){
230 if(readClass==class_opt[iclass]){
231 validClass=true;//process this class
232 break;
233 }
234 }
235 }
236 }
237 if(validData&&validClass){
238 sample[readClass].push_back(index);
239 ++(nvalid[readClass]);
240 }
241 else
242 ++(ninvalid[readClass]);
243 }
244 }
245 char **papszOptions=NULL;
246 for(std::vector<std::string>::const_iterator optionIt=option_opt.begin();optionIt!=option_opt.end();++optionIt)
247 papszOptions=CSLAddString(papszOptions,optionIt->c_str());
248
249 if(ogrWriter.open(output_opt[0], layer_opt, ogrformat_opt[0], VectorOgr::string2geotype("wkbPoint"), this->getProjection(),papszOptions)!=OGRERR_NONE){
250 std::ostringstream fs;
251 fs << "open ogrWriter failed ";
252 fs << "output name: " << output_opt[0] << ", ";
253 fs << "format: "<< ogrformat_opt[0] << std::endl;
254 throw(fs.str());
255 }
256 std::map<std::string,double> pointAttributes;
257 ogrWriter.createField(attribute_opt[0],labelType);
258 if(fid_opt.size())
259 ogrWriter.createField(fid_opt[0],OFTInteger64);
260 for(size_t iplane=0;iplane<nplane;++iplane){
261 for(int iband=0;iband<nband;++iband){
262 int theBand=iband;
263 std::string fieldname;
264 std::ostringstream fs;
265 if(bandNames_opt.size()){
266 if(planeNames_opt.size())
267 fs << planeNames_opt[iplane];
268 fs << bandNames_opt[iband];
269 }
270 else{
271 if(planeNames_opt.size())
272 fs << planeNames_opt[iplane];
273 if(nband>1)
274 fs << "b" << theBand;
275 }
276 fieldname=fs.str();
277 ogrWriter.createField(fieldname,fieldType);
278 }
279 }
280 if(threshold_opt[0]!=100){
281 //todo (optimization): if selection is small, better select random sample than shuffle all...
282 #if JIPLIB_PROCESS_IN_PARALLEL == 1
283 #pragma omp parallel
284 {
285 // Each thread gets its own generator instance, seeded uniquely
286 // We use thread ID to ensure each thread shuffles differently
287 std::random_device rd;
288 std::mt19937 g(rd() ^ omp_get_thread_num());
289
290 #pragma omp for
291 for(unsigned short iclass=0; iclass<nclass; ++iclass) {
292 if(verbose_opt[0]){
293 if(nvalid[iclass]){
294 std::cout << "nvalid[" << iclass << "]: " << nvalid[iclass] << std::endl;
295 std::cout << "ninvalid[" << iclass << "]: " << ninvalid[iclass] << std::endl;
296 }
297 }
298 if(sample[iclass].size()) {
299 std::shuffle(sample[iclass].begin(), sample[iclass].end(), g);
300 }
301 }
302 }
303 #else
304 // Serial fallback
305 std::random_device rd;
306 std::mt19937 g(rd());
307 for(unsigned short iclass=0; iclass<nclass; ++iclass) {
308 if(verbose_opt[0]){
309 if(nvalid[iclass]){
310 std::cout << "nvalid[" << iclass << "]: " << nvalid[iclass] << std::endl;
311 std::cout << "ninvalid[" << iclass << "]: " << ninvalid[iclass] << std::endl;
312 }
313 }
314 if(sample[iclass].size()) {
315 std::shuffle(sample[iclass].begin(), sample[iclass].end(), g);
316 }
317 }
318 #endif
319 }
320
321 size_t fid=0;//unique field identifier
322 for(unsigned short iclass=0;iclass<nclass;++iclass){
323 if(sample[iclass].empty())
324 continue;
325 /* unsigned short theClass=(class_opt.size()) ? class_opt[iclass] : iclass; */
326 //select random indices for iclass
327 size_t nsample=sample[iclass].size();
328 double absThreshold=(threshold_opt.size()>iclass)?threshold_opt[iclass]:threshold_opt[0];
329 if(absThreshold<0){
330 absThreshold=-absThreshold;
331 if(absThreshold > sample[iclass].size())
332 absThreshold=sample[iclass].size();
333 }
334 else{
335 if(absThreshold > 100)
336 absThreshold=100;
337 absThreshold/=100;
338 absThreshold*=nsample;
339 }
340 for(size_t isample=0;isample<absThreshold;++isample){
341 size_t index=sample[iclass][isample];
342 int icol=static_cast<int>(index%nrOfCol());
343 int irow=static_cast<int>(index/nrOfCol());
344 image2geo(icol,irow,x,y);
345 pointAttributes[attribute_opt[0]]=iclass;
346 if(fid_opt.size())
347 pointAttributes[fid_opt[0]]=fid++;
348
349 for(size_t iplane=0;iplane<nplane;++iplane){
350 for(int iband=0;iband<nband;++iband){
351 int theBand=iband;
352 std::string fieldname;
353 std::ostringstream fs;
354 if(bandNames_opt.size()){
355 if(planeNames_opt.size())
356 fs << planeNames_opt[iplane];
357 fs << bandNames_opt[iband];
358 }
359 else{
360 if(planeNames_opt.size())
361 fs << planeNames_opt[iplane];
362 if(nband>1)
363 fs << "b" << theBand;
364 }
365 fieldname=fs.str();
366 size_t imindex=index+iplane*nrOfCol()*nrOfRow();
367 T* pim=static_cast<T*>(getDataPointer(iband));
368 pointAttributes[fieldname]=pim[imindex];
369 }
370 }
371 ogrWriter.addPoint(x,y,pointAttributes);
372 }
373 }
374 }
375 catch(std::string predefinedString){
376 std::cerr << predefinedString << std::endl;
377 throw;
378 }
379 }
380
381 #endif // _JLEXTRACTIMG_LIB_H_