Debian Codegraph @

src/imageclasses/jlfilter1d_lib.cc

raw symbols SCIP
1 /**********************************************************************
2 jlfilter1d_lib.cc: program to filter raster images: median, min/max, morphological, filtering
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 #include <assert.h>
22 #include <iostream>
23 #include <string>
24 #include <fstream>
25 #include <memory>
26 // #include <math.h>
27 #include <cmath>
28 #include <sys/types.h>
29 #include <stdio.h>
30 extern "C" {
31 #include <gsl/gsl_sort.h>
32 #include <gsl/gsl_wavelet.h>
33 }
34 #include "base/Optionjl.h"
35 #include "fileclasses/FileReaderAscii.h"
36 #include "imageclasses/Jim.h"
37 #include "algorithms/StatFactory.h"
38 #include "algorithms/Filter.h"
39 #include "apps/AppFactory.h"
40 #include "jlfilter1d_lib.h"
41
42 using namespace std;
43 using namespace app;
44 using namespace filter;
45
46 /**
47 * @param filter (type: std::string) filter function (nvalid, median, var, min, max, sum, mean, dilate, erode, close, open, mode (majority voting), only for classes), smoothnodata (smooth nodata values only) values, ismin, ismax, order (rank pixels in order), stdev, mrf, dwt, dwti, dwt_cut, dwt_cut_from, savgolay, percentile, proportion)
48 * @param srf (type: std::string) list of ASCII files containing spectral response functions (two columns: wavelength response)
49 * @param fwhm (type: double) list of full width half to apply spectral filtering (-fwhm band1 -fwhm band2 ...)
50 * @param dz (type: int) (default: 3) filter kernel size in z (spectral/temporal dimension), must be odd (example: 3).
51 * @param nodata (type: double) nodata value(s) (e.g., used for smoothnodata filter)
52 * @param wavelet (type: std::string) (default: daubechies) wavelet type: daubechies,daubechies_centered, haar, haar_centered, bspline, bspline_centered
53 * @param family (type: int) (default: 4) wavelet family (vanishing moment, see also http://www.gnu.org/software/gsl/manual/html_node/DWT-Initialization.html)
54 * @param nl (type: int) (default: 2) Number of leftward (past) data points used in Savitzky-Golay filter)
55 * @param nr (type: int) (default: 2) Number of rightward (future) data points used in Savitzky-Golay filter)
56 * @param ld (type: int) (default: 0) order of the derivative desired in Savitzky-Golay filter (e.g., ld=0 for smoothed function)
57 * @param m (type: int) (default: 2) order of the smoothing polynomial in Savitzky-Golay filter, also equal to the highest conserved moment; usual values are m = 2 or m = 4)
58 * @param class (type: short) class value(s) to use for density, erosion, dilation, openening and closing, thresholding
59 * @param threshold (type: double) (default: 0) threshold value(s) to use for threshold filter (one for each class), or threshold to cut for dwt_cut (use 0 to keep all) or dwt_cut_from, or sigma for shift
60 * @param tapz (type: double) taps used for spectral filtering
61 * @param pad (type: std::string) (default: symmetric) Padding method for filtering (how to handle edge effects). Choose between: symmetric, replicate, circular, zero (pad with 0).
62 * @param wavelengthIn (type: double) list of wavelengths in input spectrum (-win band1 -win band2 ...)
63 * @param wavelengthOut (type: double) list of wavelengths in output spectrum (-wout band1 -wout band2 ...)
64 * @param down (type: short) (default: 1) down sampling factor. Use value 1 for no downsampling. Use value n>1 for downsampling (aggregation)
65 * @param interp (type: std::string) (default: akima) type of interpolation for spectral filtering (see http://www.gnu.org/software/gsl/manual/html_node/Interpolation-Types.html)
66 * @param otype (type: std::string) Data type for output image ({Byte/Int16/UInt16/UInt32/Int32/Float32/Float64/CInt16/CInt32/CFloat32/CFloat64}). Empty string: inherit type from input image
67 * @param ct (type: std::string) color table (file with 5 columns: id R G B ALFA (0: transparent, 255: solid). Use none to omit color table
68 * @return shared pointer to image object
69 **/
70
71 shared_ptr<Jim> Jim::filter1d(app::AppFactory& app){
72 try{
73 shared_ptr<Jim> imgWriter=createImg();
74 filter1d(*imgWriter, app);
75 return(imgWriter);
76 }
77 catch(std::string helpString){
78 cerr << helpString << endl;
79 throw;
80 }
81 }
82
83 /**
84 * @param filter (type: std::string) filter function (nvalid, median, var, min, max, sum, mean, dilate, erode, close, open, mode (majority voting), only for classes), smoothnodata (smooth nodata values only) values, ismin, ismax, order (rank pixels in order), stdev, mrf, dwt, dwti, dwt_cut, dwt_cut_from, savgolay, percentile, proportion)
85 * @param srf (type: std::string) list of ASCII files containing spectral response functions (two columns: wavelength response)
86 * @param fwhm (type: double) list of full width half to apply spectral filtering (-fwhm band1 -fwhm band2 ...)
87 * @param dz (type: int) (default: 3) filter kernel size in z (spectral/temporal dimension), must be odd (example: 3).
88 * @param nodata (type: double) nodata value(s) (e.g., used for smoothnodata filter)
89 * @param wavelet (type: std::string) (default: daubechies) wavelet type: daubechies,daubechies_centered, haar, haar_centered, bspline, bspline_centered
90 * @param family (type: int) (default: 4) wavelet family (vanishing moment, see also http://www.gnu.org/software/gsl/manual/html_node/DWT-Initialization.html)
91 * @param nl (type: int) (default: 2) Number of leftward (past) data points used in Savitzky-Golay filter)
92 * @param nr (type: int) (default: 2) Number of rightward (future) data points used in Savitzky-Golay filter)
93 * @param ld (type: int) (default: 0) order of the derivative desired in Savitzky-Golay filter (e.g., ld=0 for smoothed function)
94 * @param m (type: int) (default: 2) order of the smoothing polynomial in Savitzky-Golay filter, also equal to the highest conserved moment; usual values are m = 2 or m = 4)
95 * @param class (type: short) class value(s) to use for density, erosion, dilation, openening and closing, thresholding
96 * @param threshold (type: double) (default: 0) threshold value(s) to use for threshold filter (one for each class), or threshold to cut for dwt_cut (use 0 to keep all) or dwt_cut_from, or sigma for shift
97 * @param tapz (type: double) taps used for spectral filtering
98 * @param pad (type: std::string) (default: symmetric) Padding method for filtering (how to handle edge effects). Choose between: symmetric, replicate, circular, zero (pad with 0).
99 * @param wavelengthIn (type: double) list of wavelengths in input spectrum (-win band1 -win band2 ...)
100 * @param wavelengthOut (type: double) list of wavelengths in output spectrum (-wout band1 -wout band2 ...)
101 * @param down (type: short) (default: 1) down sampling factor. Use value 1 for no downsampling. Use value n>1 for downsampling (aggregation)
102 * @param interp (type: std::string) (default: akima) type of interpolation for spectral filtering (see http://www.gnu.org/software/gsl/manual/html_node/Interpolation-Types.html)
103 * @param otype (type: std::string) Data type for output image ({Byte/Int16/UInt16/UInt32/Int32/Float32/Float64/CInt16/CInt32/CFloat32/CFloat64}). Empty string: inherit type from input image
104 * @param ct (type: std::string) color table (file with 5 columns: id R G B ALFA (0: transparent, 255: solid). Use none to omit color table
105 **/
106 void Jim::filter1d(Jim& imgWriter, app::AppFactory& app){
107 Optionjl<std::string> method_opt("f", "filter", "filter function (nvalid, median, var, min, max, sum, mean, dilate, erode, close, open, mode (majority voting), only for classes), smoothnodata (smooth nodata values only) values, ismin, ismax, order (rank pixels in order), stdev, mrf, dwt, dwti, dwt_cut, dwt_cut_from, savgolay, percentile, proportion)");
108 Optionjl<int> dimZ_opt("dz", "dz", "filter kernel size in z (spectral/temporal dimension), must be odd (example: 3).",3);
109 Optionjl<std::string> wavelet_type_opt("wt", "wavelet", "wavelet type: daubechies,daubechies_centered, haar, haar_centered, bspline, bspline_centered", "daubechies");
110 Optionjl<int> family_opt("wf", "family", "wavelet family (vanishing moment, see also http://www.gnu.org/software/gsl/manual/html_node/DWT-Initialization.html)", 4);
111 Optionjl<int> savgolay_nl_opt("nl", "nl", "Number of leftward (past) data points used in Savitzky-Golay filter)", 2);
112 Optionjl<int> savgolay_nr_opt("nr", "nr", "Number of rightward (future) data points used in Savitzky-Golay filter)", 2);
113 Optionjl<int> savgolay_ld_opt("ld", "ld", "order of the derivative desired in Savitzky-Golay filter (e.g., ld=0 for smoothed function)", 0);
114 Optionjl<int> savgolay_m_opt("m", "m", "order of the smoothing polynomial in Savitzky-Golay filter, also equal to the highest conserved moment; usual values are m = 2 or m = 4)", 2);
115 Optionjl<short> class_opt("class", "class", "class value(s) to use for density, erosion, dilation, openening and closing, thresholding");
116 Optionjl<double> threshold_opt("t", "threshold", "threshold value(s) to use for threshold filter (one for each class), or threshold to cut for dwt_cut (use 0 to keep all) or dwt_cut_from, or sigma for shift", 0);
117 Optionjl<double> nodata_opt("nodata", "nodata", "nodata value(s) (e.g., used for smoothnodata filter)");
118 Optionjl<double> tapz_opt("tapz", "tapz", "taps used for spectral filtering");
119 Optionjl<std::string> padding_opt("pad","pad", "Padding method for filtering (how to handle edge effects). Choose between: symmetric, replicate, circular, zero (pad with 0).", "symmetric");
120 Optionjl<double> fwhm_opt("fwhm", "fwhm", "list of full width half to apply spectral filtering (-fwhm band1 -fwhm band2 ...)");
121 Optionjl<std::string> srf_opt("srf", "srf", "list of ASCII files containing spectral response functions (two columns: wavelength response)");
122 Optionjl<double> wavelengthIn_opt("win", "wavelengthIn", "list of wavelengths in input spectrum (-win band1 -win band2 ...)");
123 Optionjl<double> wavelengthOut_opt("wout", "wavelengthOut", "list of wavelengths in output spectrum (-wout band1 -wout band2 ...)");
124 Optionjl<std::string> interpolationType_opt("interp", "interp", "type of interpolation for spectral filtering (see http://www.gnu.org/software/gsl/manual/html_node/Interpolation-Types.html)","akima");
125 Optionjl<std::string> otype_opt("ot", "otype", "Data type for output image ({Byte/Int16/UInt16/UInt32/Int32/Float32/Float64/CInt16/CInt32/CFloat32/CFloat64}). Empty string: inherit type from input image");
126 Optionjl<std::string> colorTable_opt("ct", "ct", "color table (file with 5 columns: id R G B ALFA (0: transparent, 255: solid). Use none to omit color table");
127 Optionjl<short> down_opt("d", "down", "down sampling factor. Use value 1 for no downsampling. Use value n>1 for downsampling (aggregation)", 1);
128 Optionjl<short> verbose_opt("v", "verbose", "verbose mode if > 0", 0,2);
129
130 wavelet_type_opt.setHide(1);
131 family_opt.setHide(1);
132 savgolay_nl_opt.setHide(1);
133 savgolay_nr_opt.setHide(1);
134 savgolay_ld_opt.setHide(1);
135 savgolay_m_opt.setHide(1);
136 class_opt.setHide(1);
137 threshold_opt.setHide(1);
138 tapz_opt.setHide(1);
139 padding_opt.setHide(1);
140 wavelengthIn_opt.setHide(1);
141 wavelengthOut_opt.setHide(1);
142 down_opt.setHide(1);
143 // eps_opt.setHide(1);
144 // l1_opt.setHide(1);
145 // l2_opt.setHide(1);
146 // a1_opt.setHide(1);
147 // a2_opt.setHide(1);
148 interpolationType_opt.setHide(1);
149 otype_opt.setHide(1);
150 colorTable_opt.setHide(1);
151
152 bool doProcess;//stop process when program was invoked with help option (-h --help)
153 try{
154 doProcess=method_opt.retrieveOption(app);
155 // angle_opt.retrieveOption(app);
156 srf_opt.retrieveOption(app);
157 fwhm_opt.retrieveOption(app);
158 dimZ_opt.retrieveOption(app);
159 nodata_opt.retrieveOption(app);
160 wavelet_type_opt.retrieveOption(app);
161 family_opt.retrieveOption(app);
162 savgolay_nl_opt.retrieveOption(app);
163 savgolay_nr_opt.retrieveOption(app);
164 savgolay_ld_opt.retrieveOption(app);
165 savgolay_m_opt.retrieveOption(app);
166 class_opt.retrieveOption(app);
167 threshold_opt.retrieveOption(app);
168 tapz_opt.retrieveOption(app);
169 padding_opt.retrieveOption(app);
170 wavelengthIn_opt.retrieveOption(app);
171 wavelengthOut_opt.retrieveOption(app);
172 down_opt.retrieveOption(app);
173 // eps_opt.retrieveOption(app);
174 // l1_opt.retrieveOption(app);
175 // l2_opt.retrieveOption(app);
176 // a1_opt.retrieveOption(app);
177 // a2_opt.retrieveOption(app);
178 interpolationType_opt.retrieveOption(app);
179 otype_opt.retrieveOption(app);
180 colorTable_opt.retrieveOption(app);
181 verbose_opt.retrieveOption(app);
182 if(!doProcess){
183 cout << endl;
184 std::ostringstream helpStream;
185 helpStream << "short option -h shows basic options only, use long option --help to show all options" << std::endl;
186 throw(helpStream.str());//help was invoked, stop processing
187 }
188
189 GDALDataType theType=GDT_Unknown;
190 if(otype_opt.size()){
191 theType=string2GDAL(otype_opt[0]);
192 if(theType==GDT_Unknown)
193 std::cout << "Warning: unknown output pixel type: " << otype_opt[0] << ", using input type as default" << std::endl;
194 }
195
196 if(theType==GDT_Unknown)
197 theType=this->getGDALDataType();
198
199 if(verbose_opt[0])
200 std::cout << "Output pixel type: " << GDALGetDataTypeName(theType) << endl;
201
202 std::string errorString;
203 unsigned int nband=this->nrOfBand();
204
205 if(fwhm_opt.size())
206 nband=fwhm_opt.size();
207 else if(srf_opt.size())
208 nband=srf_opt.size();
209 else if(tapz_opt.size())
210 nband=this->nrOfBand();
211 else{
212 if(method_opt.empty()){
213 errorString="Error: no filter selected, use option -f";
214 throw(errorString);
215 }
216 else if(verbose_opt[0])
217 std::cout << "filter method: " << method_opt[0] << "=" << filter::Filter::getFilterType(method_opt[0]) << std::endl;
218 // std::cout << "filter method: "<< filter::Filter::getFilterType(method_opt[0]) << std::endl;
219 switch(filter::Filter::getFilterType(method_opt[0])){
220 case(filter::dilate):
221 case(filter::erode):
222 case(filter::close):
223 case(filter::open):
224 case(filter::smooth):
225 //implemented in spectral/temporal domain (dimZ>1) and spatial domain
226 if(dimZ_opt.size())
227 assert(dimZ_opt[0]>1);
228 nband=this->nrOfBand();
229 break;
230 case(filter::dwt):
231 case(filter::dwti):
232 case(filter::dwt_cut):
233 case(filter::smoothnodata):
234 //implemented in spectral/temporal/spatial domain and nband always this->nrOfBand()
235 nband=this->nrOfBand();
236 break;
237 case(filter::savgolay):
238 nband=this->nrOfBand();
239 if(dimZ_opt.empty())
240 dimZ_opt.push_back(1);
241 case(filter::dwt_cut_from):
242 //only implemented in spectral/temporal domain
243 if(dimZ_opt.size()){
244 nband=this->nrOfBand();
245 assert(threshold_opt.size());
246 }
247 break;
248 //implemented in spectral/temporal/spatial domain and nband 1 if dimZ>0
249 case(filter::sum):
250 case(filter::mean):
251 case(filter::min):
252 case(filter::max):
253 case(filter::var):
254 case(filter::stdev):
255 case(filter::nvalid):
256 case(filter::median):
257 case(filter::percentile):
258 case(filter::proportion):
259 //implemented in spectral/temporal/spatial domain and nband 1 if dimZ==1
260 if(dimZ_opt.size()==1)
261 if(dimZ_opt[0]==1)
262 nband=1;
263 else
264 nband=this->nrOfBand();
265 break;
266 default:{
267 cout << endl;
268 std::ostringstream errorStream;
269 errorStream << "filter method: " << method_opt[0] << "=" << filter::Filter::getFilterType(method_opt[0]) << " not implemented"<< std::endl;
270 // errorStream << "filter " << method_opt[0] << " (" << )"<< " not implemented";
271 throw(errorStream.str());
272 break;
273 }
274 }
275 }
276 imgWriter.open((this->nrOfCol()+down_opt[0]-1)/down_opt[0],(this->nrOfRow()+down_opt[0]-1)/down_opt[0],nband,theType);
277 imgWriter.setProjection(this->getProjection());
278 double gt[6];
279 this->getGeoTransform(gt);
280 gt[1]*=down_opt[0];//dx
281 gt[5]*=down_opt[0];//dy
282 imgWriter.setGeoTransform(gt);
283
284 if(colorTable_opt.size()){
285 if(colorTable_opt[0]!="none"){
286 if(verbose_opt[0])
287 cout << "set colortable " << colorTable_opt[0] << endl;
288 assert(imgWriter.getDataType()==GDT_Byte);
289 imgWriter.setColorTable(colorTable_opt[0]);
290 }
291 }
292 else if(this->getColorTable()!=NULL)
293 imgWriter.setColorTable(this->getColorTable());
294
295 if(nodata_opt.size()){
296 for(unsigned int iband=0;iband<imgWriter.nrOfBand();++iband)
297 imgWriter.GDALSetNoDataValue(nodata_opt[0],iband);
298 }
299
300 filter::Filter filter1d;
301 if(verbose_opt[0])
302 cout << "Set padding to " << padding_opt[0] << endl;
303 filter1d.setPadding(padding_opt[0]);
304 if(class_opt.size()){
305 if(verbose_opt[0])
306 std::cout<< "class values: ";
307 for(int iclass=0;iclass<class_opt.size();++iclass){
308 filter1d.pushClass(class_opt[iclass]);
309 if(verbose_opt[0])
310 std::cout<< class_opt[iclass] << " ";
311 }
312 if(verbose_opt[0])
313 std::cout<< std::endl;
314 }
315
316 if(nodata_opt.size()){
317 if(verbose_opt[0])
318 std::cout<< "mask values: ";
319 for(unsigned int imask=0;imask<nodata_opt.size();++imask){
320 if(verbose_opt[0])
321 std::cout<< nodata_opt[imask] << " ";
322 filter1d.pushNoDataValue(nodata_opt[imask]);
323 }
324 if(verbose_opt[0])
325 std::cout<< std::endl;
326 }
327 filter1d.setThresholds(threshold_opt);
328
329 if(tapz_opt.size()){
330 if(verbose_opt[0]){
331 std::cout << "taps: ";
332 for(int itap=0;itap<tapz_opt.size();++itap)
333 std::cout<< tapz_opt[itap] << " ";
334 std::cout<< std::endl;
335 }
336 filter1d.setTaps(tapz_opt);
337 //todo:this->filter3D.filter(imgWriter);
338 filter1d.filter(*this,imgWriter);
339 // filter1d.filter(input,output);
340 }
341 else if(fwhm_opt.size()){
342 if(verbose_opt[0])
343 std::cout << "spectral filtering to " << fwhm_opt.size() << " bands with provided fwhm " << std::endl;
344 assert(wavelengthOut_opt.size()==fwhm_opt.size());
345 assert(wavelengthIn_opt.size());
346
347 Vector2d<double> lineInput(this->nrOfBand(),this->nrOfCol());
348 Vector2d<double> lineOutput(wavelengthOut_opt.size(),this->nrOfCol());
349 const char* pszMessage;
350 // void* pProgressArg=NULL;
351 // GDALProgressFunc pfnProgress=GDALTermProgress;
352 // double progress=0;
353 // pfnProgress(progress,pszMessage,pProgressArg);
354 for(unsigned int y=0;y<this->nrOfRow();++y){
355 if((y+1+down_opt[0]/2)%down_opt[0])
356 continue;
357 for(unsigned int iband=0;iband<this->nrOfBand();++iband)
358 this->readData(lineInput[iband],y,iband);
359 filter1d.applyFwhm<double>(wavelengthIn_opt,lineInput,wavelengthOut_opt,fwhm_opt, interpolationType_opt[0], lineOutput, down_opt[0], verbose_opt[0]);
360 for(unsigned int iband=0;iband<imgWriter.nrOfBand();++iband){
361 imgWriter.writeData(lineOutput[iband],y/down_opt[0],iband);
362 }
363 // progress=(1.0+y)/imgWriter.nrOfRow();
364 // pfnProgress(progress,pszMessage,pProgressArg);
365 }
366 }
367 else if(srf_opt.size()){
368 if(verbose_opt[0])
369 std::cout << "spectral filtering to " << srf_opt.size() << " bands with provided SRF " << std::endl;
370 assert(wavelengthIn_opt.size());
371 vector< Vector2d<double> > srf(srf_opt.size());//[0] srf_nr, [1]: wavelength, [2]: response
372 ifstream srfFile;
373 for(int isrf=0;isrf<srf_opt.size();++isrf){
374 srf[isrf].resize(2);
375 srfFile.open(srf_opt[isrf].c_str());
376 double v;
377 //add 0 to make sure srf is 0 at boundaries after interpolation step
378 srf[isrf][0].push_back(0);
379 srf[isrf][1].push_back(0);
380 srf[isrf][0].push_back(1);
381 srf[isrf][1].push_back(0);
382 while(srfFile >> v){
383 srf[isrf][0].push_back(v);
384 srfFile >> v;
385 srf[isrf][1].push_back(v);
386 }
387 srfFile.close();
388 //add 0 to make sure srf[isrf] is 0 at boundaries after interpolation step
389 srf[isrf][0].push_back(srf[isrf][0].back()+1);
390 srf[isrf][1].push_back(0);
391 srf[isrf][0].push_back(srf[isrf][0].back()+1);
392 srf[isrf][1].push_back(0);
393 if(verbose_opt[0])
394 cout << "srf file details: " << srf[isrf][0].size() << " wavelengths defined" << endl;
395 }
396 assert(imgWriter.nrOfBand()==srf.size());
397 double centreWavelength=0;
398 Vector2d<double> lineInput(this->nrOfBand(),this->nrOfCol());
399 const char* pszMessage;
400 // void* pProgressArg=NULL;
401 // GDALProgressFunc pfnProgress=GDALTermProgress;
402 // double progress=0;
403 // pfnProgress(progress,pszMessage,pProgressArg);
404 for(unsigned int y=0;y<this->nrOfRow();++y){
405 if((y+1+down_opt[0]/2)%down_opt[0])
406 continue;
407 for(unsigned int iband=0;iband<this->nrOfBand();++iband)
408 this->readData(lineInput[iband],y,iband);
409 for(unsigned int isrf=0;isrf<srf.size();++isrf){
410 vector<double> lineOutput(imgWriter.nrOfCol());
411 double delta=1.0;
412 bool normalize=true;
413 centreWavelength=filter1d.applySrf<double>(wavelengthIn_opt,lineInput,srf[isrf], interpolationType_opt[0], lineOutput, delta, normalize);
414 if(verbose_opt[0])
415 std::cout << "centre wavelength srf " << isrf << ": " << centreWavelength << std::endl;
416 imgWriter.writeData(lineOutput,y/down_opt[0],isrf);
417 }
418 // progress=(1.0+y)/imgWriter.nrOfRow();
419 // pfnProgress(progress,pszMessage,pProgressArg);
420 }
421
422 }
423 else{
424 switch(filter::Filter::getFilterType(method_opt[0])){
425 case(filter::dilate):
426 if(down_opt[0]!=1){
427 std::cerr << "Error: down option not supported for morphological operator" << std::endl;
428 exit(1);
429 }
430 if(verbose_opt[0])
431 std::cout<< "1-D filtering: dilate" << std::endl;
432 filter1d.morphology(*this,imgWriter,"dilate",dimZ_opt[0],verbose_opt[0]);
433 break;
434 case(filter::erode):
435 if(down_opt[0]!=1){
436 std::cerr << "Error: down option not supported for morphological operator" << std::endl;
437 exit(1);
438 }
439 if(verbose_opt[0])
440 std::cout<< "1-D filtering: erode" << std::endl;
441 filter1d.morphology(*this,imgWriter,"erode",dimZ_opt[0],verbose_opt[0]);
442 break;
443 case(filter::close):{//closing
444 if(down_opt[0]!=1){
445 std::cerr << "Error: down option not supported for morphological operator" << std::endl;
446 exit(1);
447 }
448 filter1d.morphology(*this,imgWriter,"dilate",dimZ_opt[0]);
449 filter1d.morphology(imgWriter,imgWriter,"erode",dimZ_opt[0]);
450 break;
451 }
452 case(filter::open):{//opening
453 if(down_opt[0]!=1){
454 std::cerr << "Error: down option not supported for morphological operator" << std::endl;
455 exit(1);
456 }
457 filter1d.morphology(*this,imgWriter,"erode",dimZ_opt[0],verbose_opt[0]);
458 filter1d.morphology(imgWriter,imgWriter,"dilate",dimZ_opt[0]);
459 break;
460 }
461 case(filter::smooth):{//Smoothing filter
462 if(down_opt[0]!=1){
463 std::cerr << "Error: down option not supported for this filter" << std::endl;
464 exit(1);
465 }
466 if(verbose_opt[0])
467 std::cout<< "1-D filtering: smooth" << std::endl;
468 filter1d.smooth(*this,imgWriter,dimZ_opt[0]);
469 break;
470 }
471 case(filter::smoothnodata):{//Smoothing filter
472 if(down_opt[0]!=1){
473 std::cerr << "Error: down option not supported for this filter" << std::endl;
474 exit(1);
475 }
476 if(verbose_opt[0])
477 std::cout<< "1-D filtering: smooth" << std::endl;
478 filter1d.smoothNoData(*this,interpolationType_opt[0],imgWriter);
479 break;
480 }
481 case(filter::dwt):
482 if(down_opt[0]!=1){
483 std::cerr << "Error: down option not supported for this filter" << std::endl;
484 exit(1);
485 }
486 if(verbose_opt[0])
487 std::cout<< "DWT in spectral domain" << std::endl;
488 filter1d.dwtForward(*this, imgWriter, wavelet_type_opt[0], family_opt[0]);
489 break;
490 case(filter::dwti):
491 if(down_opt[0]!=1){
492 std::cerr << "Error: down option not supported for this filter" << std::endl;
493 exit(1);
494 }
495 if(verbose_opt[0])
496 std::cout<< "inverse DWT in spectral domain" << std::endl;
497 filter1d.dwtInverse(*this, imgWriter, wavelet_type_opt[0], family_opt[0]);
498 break;
499 case(filter::dwt_cut):
500 if(down_opt[0]!=1){
501 std::cerr << "Error: down option not supported for this filter" << std::endl;
502 exit(1);
503 }
504 if(verbose_opt[0])
505 std::cout<< "DWT approximation in spectral domain" << std::endl;
506 filter1d.dwtCut(*this, imgWriter, wavelet_type_opt[0], family_opt[0], threshold_opt[0]);
507 break;
508 case(filter::dwt_cut_from):
509 if(down_opt[0]!=1){
510 std::cerr << "Error: down option not supported for this filter" << std::endl;
511 exit(1);
512 }
513 if(verbose_opt[0])
514 std::cout<< "DWT approximation in spectral domain" << std::endl;
515 filter1d.dwtCutFrom(*this,imgWriter, wavelet_type_opt[0], family_opt[0], static_cast<int>(threshold_opt[0]));
516 break;
517 case(filter::savgolay):{
518 assert(savgolay_nl_opt.size());
519 assert(savgolay_nr_opt.size());
520 assert(savgolay_ld_opt.size());
521 assert(savgolay_m_opt.size());
522 if(verbose_opt[0])
523 std::cout << "Calculating Savitzky-Golay coefficients: " << endl;
524 filter1d.getSavGolayCoefficients(tapz_opt, this->nrOfBand(), savgolay_nl_opt[0], savgolay_nr_opt[0], savgolay_ld_opt[0], savgolay_m_opt[0]);
525 if(verbose_opt[0]){
526 std::cout << "taps (size is " << tapz_opt.size() << "): ";
527 for(int itap=0;itap<tapz_opt.size();++itap)
528 std::cout<< tapz_opt[itap] << " ";
529 std::cout<< std::endl;
530 }
531 filter1d.setTaps(tapz_opt);
532 filter1d.filter(*this,imgWriter);
533 break;
534 }
535 case(filter::percentile)://deliberate fall through
536 case(filter::threshold):{//deliberate fall through
537 if(threshold_opt.empty()){
538 std::string errorString="Error: thresholds not set";
539 throw(errorString);
540 }
541 filter1d.setThresholds(threshold_opt);
542 }
543 default:{
544 if(dimZ_opt[0]==1)
545 filter1d.stat(*this,imgWriter,method_opt[0]);
546 else{
547 if(down_opt[0]!=1){
548 std::string errorString="Error: down not implemented for this filter";
549 throw(errorString);
550 }
551 filter1d.filter(*this,imgWriter,method_opt[0],dimZ_opt[0]);
552 }
553 break;
554 }
555 }
556 }
557 }
558 catch(std::string predefinedString){
559 std::cout << predefinedString << std::endl;
560 throw;
561 }
562 }
563
564 std::shared_ptr<Jim> Jim::firfilter1d(app::AppFactory& app){
565 try{
566 shared_ptr<Jim> imgWriter=createImg();
567 firfilter1d(*imgWriter, app);
568 return(imgWriter);
569 }
570 catch(std::string helpString){
571 cerr << helpString << endl;
572 throw;
573 }
574 }
575
576 void Jim::firfilter1d(Jim& imgWriter, app::AppFactory& app){
577 imgWriter.open(nrOfCol(),nrOfRow(),nrOfBand(),nrOfPlane(),GDT_Float64);
578 imgWriter.setProjection(this->getProjection());
579 double gt[6];
580 this->getGeoTransform(gt);
581 imgWriter.setGeoTransform(gt);
582 switch(getDataType()){
583 case(GDT_Byte):
584 firfilter1d_t<unsigned char>(imgWriter,app);
585 break;
586 case(GDT_Int16):
587 firfilter1d_t<short>(imgWriter,app);
588 break;
589 case(GDT_UInt16):
590 firfilter1d_t<unsigned short>(imgWriter,app);
591 break;
592 case(GDT_Int32):
593 firfilter1d_t<int>(imgWriter,app);
594 break;
595 case(GDT_UInt32):
596 firfilter1d_t<unsigned int>(imgWriter,app);
597 break;
598 case(GDT_Float32):
599 firfilter1d_t<float>(imgWriter,app);
600 break;
601 case(GDT_Float64):
602 firfilter1d_t<double>(imgWriter,app);
603 break;
604 default:
605 std::string errorString="Error: data type not supported";
606 throw(errorString);
607 break;
608 }
609 }
610
611 std::shared_ptr<Jim> Jim::savgolay(app::AppFactory& app){
612 try{
613 shared_ptr<Jim> imgWriter=createImg();
614 savgolay(*imgWriter, app);
615 return(imgWriter);
616 }
617 catch(std::string helpString){
618 cerr << helpString << endl;
619 throw;
620 }
621 }
622
623 void Jim::savgolay(Jim& imgWriter, app::AppFactory& app){
624 Optionjl<int> savgolay_nl_opt("nl", "nl", "Number of leftward (past) data points used in Savitzky-Golay filter)", 2);
625 Optionjl<int> savgolay_nr_opt("nr", "nr", "Number of rightward (future) data points used in Savitzky-Golay filter)", 2);
626 Optionjl<int> savgolay_ld_opt("ld", "ld", "order of the derivative desired in Savitzky-Golay filter (e.g., ld=0 for smoothed function)", 0);
627 Optionjl<int> savgolay_m_opt("m", "m", "order of the smoothing polynomial in Savitzky-Golay filter, also equal to the highest conserved moment; usual values are m = 2 or m = 4)", 2);
628 Optionjl<short> verbose_opt("v", "verbose", "verbose mode if > 0", 0,2);
629
630 bool doProcess;//stop process when program was invoked with help option (-h --help)
631 try{
632 doProcess=savgolay_nl_opt.retrieveOption(app);
633 savgolay_nr_opt.retrieveOption(app);
634 savgolay_ld_opt.retrieveOption(app);
635 savgolay_m_opt.retrieveOption(app);
636 verbose_opt.retrieveOption(app);
637 if(!doProcess){
638 cout << endl;
639 std::ostringstream helpStream;
640 helpStream << "short option -h shows basic options only, use long option --help to show all options" << std::endl;
641 throw(helpStream.str());//help was invoked, stop processing
642 }
643
644 filter::Filter filter1d;
645 std::vector<double> taps_opt;
646 filter1d.getSavGolayCoefficients(taps_opt, this->nrOfPlane(), savgolay_nl_opt[0], savgolay_nr_opt[0], savgolay_ld_opt[0], savgolay_m_opt[0]);
647 std::vector<double>::iterator vit;
648 for(vit=taps_opt.begin();vit!=taps_opt.end();++vit){
649 if(verbose_opt[0]>0){
650 std::cout << type2string<double>(*vit) << " ";
651 }
652 app.pushLongOption("taps",type2string<double>(*vit));
653 }
654
655 if(verbose_opt[0]>0)
656 std::cout << std::endl;
657
658 if(verbose_opt[0]>0)
659 std::cout << "opening imgWriter" << std::endl;
660 imgWriter.open(nrOfCol(),nrOfRow(),nrOfBand(),nrOfPlane(),GDT_Float64);
661 imgWriter.setProjection(this->getProjection());
662 double gt[6];
663 this->getGeoTransform(gt);
664 imgWriter.setGeoTransform(gt);
665 switch(getDataType()){
666 case(GDT_Byte):
667 firfilter1d_t<unsigned char>(imgWriter,app);
668 break;
669 case(GDT_Int16):
670 firfilter1d_t<short>(imgWriter,app);
671 break;
672 case(GDT_UInt16):
673 firfilter1d_t<unsigned short>(imgWriter,app);
674 break;
675 case(GDT_Int32):
676 firfilter1d_t<int>(imgWriter,app);
677 break;
678 case(GDT_UInt32):
679 firfilter1d_t<unsigned int>(imgWriter,app);
680 break;
681 case(GDT_Float32):
682 firfilter1d_t<float>(imgWriter,app);
683 break;
684 case(GDT_Float64):
685 firfilter1d_t<double>(imgWriter,app);
686 break;
687 default:
688 std::string errorString="Error: data type not supported";
689 throw(errorString);
690 break;
691 }
692 }
693 catch(std::string predefinedString ){
694 std::cout << predefinedString << std::endl;
695 throw;
696 }
697 }
698
699 shared_ptr<Jim> Jim::dwt1d(app::AppFactory& app){
700 try{
701 shared_ptr<Jim> imgWriter=clone();
702 imgWriter->d_dwt1d(app);
703 return(imgWriter);
704 }
705 catch(std::string helpString){
706 cerr << helpString << endl;
707 throw;
708 }
709 }
710
711 void Jim::d_dwt1d(app::AppFactory& app){
712 Optionjl<std::string> wavelet_type_opt("wt", "wavelet", "wavelet type: daubechies,daubechies_centered, haar, haar_centered, bspline, bspline_centered", "daubechies");
713 Optionjl<int> family_opt("wf", "family", "wavelet family (vanishing moment, see also https://www.gnu.org/software/gsl/doc/html/dwt.html)", 4);
714 bool doProcess;//stop process when program was invoked with help option (-h --help)
715 try{
716 doProcess=wavelet_type_opt.retrieveOption(app);
717 family_opt.retrieveOption(app);
718 if(!doProcess){
719 cout << endl;
720 std::ostringstream helpStream;
721 helpStream << "short option -h shows basic options only, use long option --help to show all options" << std::endl;
722 throw(helpStream.str());//help was invoked, stop processing
723 }
724
725 if(getDataType()!=GDT_Float64){
726 std::ostringstream errorStream;
727 errorStream << "Error: data type must be GDT_Float64" << std::endl;
728 throw(errorStream.str());
729 }
730 //make sure number of planes is power of 2 by adding extra planes
731 int origPlanes=nrOfPlane();
732 app::AppFactory capp;
733 capp.setLongOption("plane",nrOfPlane()-1);
734 std::shared_ptr<Jim> backPlane=cropPlane(capp);
735 while(nrOfPlane()&(nrOfPlane()-1))
736 d_stackPlane(*backPlane);
737 size_t nsize=nrOfPlane();
738 #if JIPLIB_PROCESS_IN_PARALLEL == 1
739 #pragma omp parallel for
740 #else
741 #endif
742 for(size_t iband=0;iband<nrOfBand();++iband){
743 gsl_wavelet *w;
744 gsl_wavelet_workspace *work;
745 w=gsl_wavelet_alloc(Filter::getWaveletType(wavelet_type_opt[0]),family_opt[0]);
746 work=gsl_wavelet_workspace_alloc(nsize);
747 double* pin=static_cast<double*>(getDataPointer(iband));
748 for(size_t index=0;index<nrOfCol()*nrOfRow();++index){
749 gsl_wavelet_transform_forward(w,pin+index,nrOfCol()*nrOfRow(),nsize,work);
750 }
751 gsl_wavelet_free (w);
752 gsl_wavelet_workspace_free (work);
753 }
754 capp.clearOption("plane");
755 for(size_t iplane=0;iplane<origPlanes;++iplane)
756 capp.pushLongOption("plane",iplane);
757 d_cropPlane(capp);
758 }
759 catch(std::string predefinedString ){
760 std::cout << predefinedString << std::endl;
761 throw;
762 }
763 }
764
765 shared_ptr<Jim> Jim::dwti1d(app::AppFactory& app){
766 try{
767 shared_ptr<Jim> imgWriter=clone();
768 imgWriter->d_dwti1d(app);
769 return(imgWriter);
770 }
771 catch(std::string helpString){
772 cerr << helpString << endl;
773 throw;
774 }
775 }
776
777 void Jim::d_dwti1d(app::AppFactory& app){
778 Optionjl<std::string> wavelet_type_opt("wt", "wavelet", "wavelet type: daubechies,daubechies_centered, haar, haar_centered, bspline, bspline_centered", "daubechies");
779 Optionjl<int> family_opt("wf", "family", "wavelet family (vanishing moment, see also http://www.gnu.org/software/gsl/manual/html_node/DWT-Initialization.html)", 4);
780 bool doProcess;//stop process when program was invoked with help option (-h --help)
781 try{
782 doProcess=wavelet_type_opt.retrieveOption(app);
783 family_opt.retrieveOption(app);
784 if(!doProcess){
785 cout << endl;
786 std::ostringstream helpStream;
787 helpStream << "short option -h shows basic options only, use long option --help to show all options" << std::endl;
788 throw(helpStream.str());//help was invoked, stop processing
789 }
790
791 if(getDataType()!=GDT_Float64){
792 std::ostringstream errorStream;
793 errorStream << "Error: data type must be GDT_Float64" << std::endl;
794 throw(errorStream.str());
795 }
796 //make sure number of planes is power of 2 by adding extra planes
797 int origPlanes=nrOfPlane();
798 app::AppFactory capp;
799 capp.setLongOption("plane",nrOfPlane()-1);
800 std::shared_ptr<Jim> backPlane=cropPlane(capp);
801 while(nrOfPlane()&(nrOfPlane()-1))
802 d_stackPlane(*backPlane);
803 size_t nsize=nrOfPlane();
804 #if JIPLIB_PROCESS_IN_PARALLEL == 1
805 #pragma omp parallel for
806 #else
807 #endif
808 for(size_t iband=0;iband<nrOfBand();++iband){
809 gsl_wavelet *w;
810 gsl_wavelet_workspace *work;
811 w=gsl_wavelet_alloc(Filter::getWaveletType(wavelet_type_opt[0]),family_opt[0]);
812 work=gsl_wavelet_workspace_alloc(nsize);
813 double* pin=static_cast<double*>(getDataPointer(iband));
814 for(size_t index=0;index<nrOfCol()*nrOfRow();++index){
815 gsl_wavelet_transform_inverse(w,pin+index,nrOfCol()*nrOfRow(),nsize,work);
816 }
817 gsl_wavelet_free (w);
818 gsl_wavelet_workspace_free (work);
819 }
820 capp.clearOption("plane");
821 for(size_t iplane=0;iplane<origPlanes;++iplane)
822 capp.pushLongOption("plane",iplane);
823 d_cropPlane(capp);
824 }
825 catch(std::string predefinedString ){
826 std::cout << predefinedString << std::endl;
827 throw;
828 }
829 }
830
831 shared_ptr<Jim> Jim::smoothNoData1d(app::AppFactory& app){
832 try{
833 shared_ptr<Jim> imgWriter=createImg();
834 smoothNoData1d(*imgWriter, app);
835 return(imgWriter);
836 }
837 catch(std::string helpString){
838 cerr << helpString << endl;
839 throw;
840 }
841 }
842
843 void Jim::smoothNoData1d(Jim& imgWriter, app::AppFactory& app){
844 imgWriter.open(*this,false);
845 switch(getDataType()){
846 case(GDT_Byte):
847 smoothNoData1d_t<unsigned char>(imgWriter,app);
848 break;
849 case(GDT_Int16):
850 smoothNoData1d_t<short>(imgWriter,app);
851 break;
852 case(GDT_UInt16):
853 smoothNoData1d_t<unsigned short>(imgWriter,app);
854 break;
855 case(GDT_Int32):
856 smoothNoData1d_t<int>(imgWriter,app);
857 break;
858 case(GDT_UInt32):
859 smoothNoData1d_t<unsigned int>(imgWriter,app);
860 break;
861 case(GDT_Float32):
862 smoothNoData1d_t<float>(imgWriter,app);
863 break;
864 case(GDT_Float64):
865 smoothNoData1d_t<double>(imgWriter,app);
866 break;
867 default:
868 std::string errorString="Error: data type not supported";
869 throw(errorString);
870 break;
871 }
872 }
873
874 shared_ptr<Jim> Jim::stats1d(app::AppFactory& app){
875 try{
876 shared_ptr<Jim> imgWriter=createImg();
877 stats1d(*imgWriter, app);
878 return(imgWriter);
879 }
880 catch(std::string helpString){
881 cerr << helpString << endl;
882 throw;
883 }
884 }
885
886 void Jim::stats1d(Jim& imgWriter, app::AppFactory& app){
887 switch(getDataType()){
888 case(GDT_Byte):
889 stats1d_t<unsigned char>(imgWriter,app);
890 break;
891 case(GDT_Int16):
892 stats1d_t<short>(imgWriter,app);
893 break;
894 case(GDT_UInt16):
895 stats1d_t<unsigned short>(imgWriter,app);
896 break;
897 case(GDT_Int32):
898 stats1d_t<int>(imgWriter,app);
899 break;
900 case(GDT_UInt32):
901 stats1d_t<unsigned int>(imgWriter,app);
902 break;
903 case(GDT_Float32):
904 stats1d_t<float>(imgWriter,app);
905 break;
906 case(GDT_Float64):
907 stats1d_t<double>(imgWriter,app);
908 break;
909 default:
910 std::string errorString="Error: data type not supported";
911 throw(errorString);
912 break;
913 }
914 }