File: otbRefineSensorModel.cxx

package info (click to toggle)
otb 7.2.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 1,005,476 kB
  • sloc: cpp: 270,143; xml: 128,722; ansic: 4,367; sh: 1,768; python: 1,084; perl: 92; makefile: 72
file content (376 lines) | stat: -rw-r--r-- 13,559 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
/*
 * Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// Wrappers
#include "otbWrapperApplicationFactory.h"
#include "otbWrapperChoiceParameter.h"
#include "otbWrapperElevationParametersHandler.h"
#include "otbWrapperMapProjectionParametersHandler.h"
#include "otbSensorModelAdapter.h"
#include "itkPoint.h"
#include "itkEuclideanDistanceMetric.h"
#include "otbGenericRSTransform.h"
#include "otbOGRDataSourceWrapper.h"
#include "ogrsf_frmts.h"

namespace otb
{
namespace Wrapper
{
class RefineSensorModel : public Application
{
public:
  /** Standard class typedefs. */
  typedef RefineSensorModel             Self;
  typedef Application                   Superclass;
  typedef itk::SmartPointer<Self>       Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;

  typedef itk::Point<double, 3> PointType;
  typedef itk::Statistics::EuclideanDistanceMetric<PointType> DistanceType;

  typedef std::pair<PointType, PointType> TiePointType;
  typedef std::vector<TiePointType> TiePointsType;

  typedef otb::GenericRSTransform<double, 3, 3> RSTransformType;

  /** Standard macro */
  itkNewMacro(Self);
  itkTypeMacro(RefineSensorModel, otb::Application);

private:
  void DoInit() override
  {
    SetName("RefineSensorModel");
    SetDescription("Perform least-square fit of a sensor model to a set of tie points");

    SetDocLongDescription(
        "This application reads a geom file containing a sensor model and a text file containing a list of ground control point, and performs a least-square "
        "fit of the sensor model adjustable parameters to these tie points. It produces an updated geom file as output, as well as an optional ground control "
        "points based statistics file and a vector file containing residues. The output geom file can then be used to ortho-rectify the data more accurately. "
        "Plaease note that for a proper use of the application, elevation must be correctly set (including DEM and geoid file). The map parameters allows one "
        "to choose a map projection in which the accuracy will be estimated in meters.");

    AddDocTag(Tags::Geometry);

    SetDocLimitations("None");
    SetDocSeeAlso("OrthoRectification,HomologousPointsExtraction");
    SetDocAuthors("OTB-Team");

    AddParameter(ParameterType_InputFilename, "ingeom", "Input geom file");
    SetParameterDescription("ingeom", "Geom file containing the sensor model to refine");

    AddParameter(ParameterType_OutputFilename, "outgeom", "Output geom file");
    SetParameterDescription("outgeom", "Geom file containing the refined sensor model");

    AddParameter(ParameterType_InputFilename, "inpoints", "Input file containing tie points");
    SetParameterDescription("inpoints",
                            "Input file containing tie points. Points are stored in following format: row col lon lat. Line beginning with # are ignored.");

    AddParameter(ParameterType_OutputFilename, "outstat", "Output file containing output precision statistics");
    SetParameterDescription("outstat",
                            "Output file containing the following info: ref_lon ref_lat elevation predicted_lon predicted_lat x_error_ref(meters) "
                            "y_error_ref(meters) global_error_ref(meters) x_error(meters) y_error(meters) overall_error(meters)");
    MandatoryOff("outstat");
    DisableParameter("outstat");

    AddParameter(ParameterType_OutputFilename, "outvector", "Output vector file with residues");
    SetParameterDescription("outvector", "File containing segments representing residues");
    MandatoryOff("outvector");
    DisableParameter("outvector");

    // Build the Output Map Projection
    MapProjectionParametersHandler::AddMapProjectionParameters(this, "map");

    // Elevation
    ElevationParametersHandler::AddElevationParameters(this, "elev");

    // Doc example parameter settings
    SetDocExampleParameterValue("ingeom", "input.geom");
    SetDocExampleParameterValue("outgeom", "output.geom");
    SetDocExampleParameterValue("inpoints", "points.txt");
    SetDocExampleParameterValue("map", "epsg");
    SetDocExampleParameterValue("map.epsg.code", "32631");

    SetOfficialDocLink();
  }

  void DoUpdateParameters() override
  {
    // Nothing to do here : all parameters are independent
  }

  void DoExecute() override
  {
    OGRMultiLineString mls;

    otb::SensorModelAdapter::Pointer sm     = otb::SensorModelAdapter::New();
    otb::SensorModelAdapter::Pointer sm_ref = otb::SensorModelAdapter::New();

    // Read the geom file
    bool isRead = sm->ReadGeomFile(GetParameterString("ingeom"));
    sm_ref->ReadGeomFile(GetParameterString("ingeom"));

    if (!isRead)
      otbAppLogFATAL("Can't read the input geom file!");

    // Setup the DEM Handler
    otb::Wrapper::ElevationParametersHandler::SetupDEMHandlerFromElevationParameters(this, "elev");

    // Parse the input file for ground control points
    std::ifstream ifs;
    ifs.open(GetParameterString("inpoints"));

    TiePointsType tiepoints;

    while (!ifs.eof())
    {
      std::string line;
      std::getline(ifs, line);

      double x, y, z, lat, lon;

      // Avoid commented lines or too short ones
      if (!line.empty() && line[0] != '#')
      {
        // retrieve the x component
        std::string::size_type pos     = 0;
        std::string::size_type nextpos = line.find_first_of("\t", pos);
        x                              = atof(line.substr(pos, nextpos).c_str());
        pos                            = nextpos + 1;
        nextpos                        = line.find_first_of("\t", pos);
        y                              = atof(line.substr(pos, nextpos).c_str());
        pos                            = nextpos + 1;
        nextpos                        = line.find_first_of("\t", pos);
        lon                            = atof(line.substr(pos, nextpos).c_str());
        pos                            = nextpos + 1;
        nextpos                        = line.find_first_of("\t", pos);
        lat                            = atof(line.substr(pos, nextpos).c_str());

        z = otb::DEMHandler::Instance()->GetHeightAboveEllipsoid(lon, lat);

        otbAppLogDEBUG("Adding tie point x=" << x << ", y=" << y << ", z=" << z << ", lon=" << lon << ", lat=" << lat);

        sm->AddTiePoint(x, y, z, lon, lat);

        PointType p1, p2;
        p1[0] = x;
        p1[1] = y;
        p1[2] = z;
        p2[0] = lon;
        p2[1] = lat;
        p2[2] = z;

        tiepoints.push_back(std::make_pair(p1, p2));
      }
    }
    ifs.close();

    otbAppLogINFO("Optimization in progress ...");
    sm->Optimize();
    otbAppLogINFO("Done.\n");

    sm->WriteGeomFile(GetParameterString("outgeom"));

    double rmse  = 0;
    double rmsex = 0;
    double rmsey = 0;

    double meanx = 0;
    double meany = 0;

    double rmse_ref  = 0;
    double rmsex_ref = 0;
    double rmsey_ref = 0;

    double meanx_ref = 0;
    double meany_ref = 0;


    DistanceType::Pointer distance = DistanceType::New();

    RSTransformType::Pointer rsTransform = RSTransformType::New();
    rsTransform->SetOutputProjectionRef(MapProjectionParametersHandler::GetProjectionRefFromChoice(this, "map"));
    rsTransform->InstantiateTransform();

    std::ofstream ofs;
    ofs << std::fixed;
    ofs.precision(12);
    if (IsParameterEnabled("outstat"))
    {
      ofs.open(GetParameterString("outstat"));
      ofs << "#ref_lon ref_lat elevation predicted_lon predicted_lat predicted_elev x_error_ref(meters) y_error_ref(meters) global_error_ref(meters) "
             "x_error(meters) y_error(meters) global_error(meters)"
          << std::endl;
    }

    size_t validPoints = 0;
    for (TiePointsType::const_iterator it = tiepoints.begin(); it != tiepoints.end(); ++it)
    {
      PointType tmpPoint, tmpPoint_ref, ref;
      sm->ForwardTransformPoint(it->first[0], it->first[1], it->first[2], tmpPoint[0], tmpPoint[1], tmpPoint[2]);
      sm_ref->ForwardTransformPoint(it->first[0], it->first[1], it->first[2], tmpPoint_ref[0], tmpPoint_ref[1], tmpPoint_ref[2]);

      if (!(std::isfinite(tmpPoint[0]) && std::isfinite(tmpPoint[1]) && std::isfinite(tmpPoint[2])))
      {
        otbAppLogWARNING("Can't project tie point at [" << it->first[0] << "," << it->first[1] << "," << it->first[2] << "] with optimized model!");
        continue;
      }

      if (!(std::isfinite(tmpPoint_ref[0]) && std::isfinite(tmpPoint_ref[1]) && std::isfinite(tmpPoint_ref[2])))
      {
        otbAppLogWARNING("Can't project tie point at [" << it->first[0] << "," << it->first[1] << "," << it->first[2] << "] with original model!");
        continue;
      }

      tmpPoint     = rsTransform->TransformPoint(tmpPoint);
      tmpPoint_ref = rsTransform->TransformPoint(tmpPoint_ref);

      ref[0] = it->second[0];
      ref[1] = it->second[1];
      ref[2] = it->second[2];

      ref = rsTransform->TransformPoint(ref);

      OGRLineString ls;
      ls.addPoint(tmpPoint[0], tmpPoint[1]);
      ls.addPoint(ref[0], ref[1]);
      mls.addGeometry(&ls);

      double gerror = distance->Evaluate(ref, tmpPoint);
      double xerror = ref[0] - tmpPoint[0];
      double yerror = ref[1] - tmpPoint[1];

      double gerror_ref = distance->Evaluate(ref, tmpPoint_ref);
      double xerror_ref = ref[0] - tmpPoint_ref[0];
      double yerror_ref = ref[1] - tmpPoint_ref[1];


      if (IsParameterEnabled("outstat"))
        ofs << ref[0] << "\t" << ref[1] << "\t" << it->first[2] << "\t" << tmpPoint[0] << "\t" << tmpPoint[1] << "\t" << tmpPoint[2] << "\t" << xerror_ref
            << "\t" << yerror_ref << "\t" << gerror_ref << "\t" << xerror << "\t" << yerror << "\t" << gerror << std::endl;

      rmse += gerror * gerror;
      rmsex += xerror * xerror;
      rmsey += yerror * yerror;

      meanx += xerror;
      meany += yerror;

      rmse_ref += gerror_ref * gerror_ref;
      rmsex_ref += xerror_ref * xerror_ref;
      rmsey_ref += yerror_ref * yerror_ref;

      meanx_ref += xerror_ref;
      meany_ref += yerror_ref;

      validPoints++;
    }

    if (!validPoints)
    {
      otbAppLogFATAL("No valid points to compute RMSE !");
    }

    rmse /= validPoints;

    rmsex /= validPoints;

    rmsey /= validPoints;


    meanx /= validPoints;
    meany /= validPoints;


    rmse_ref /= validPoints;

    rmsex_ref /= validPoints;

    rmsey_ref /= validPoints;


    meanx_ref /= validPoints;
    meany_ref /= validPoints;


    double stdevx = std::sqrt(rmsex - meanx * meanx);
    double stdevy = std::sqrt(rmsey - meany * meany);

    double stdevx_ref = std::sqrt(rmsex_ref - meanx_ref * meanx_ref);
    double stdevy_ref = std::sqrt(rmsey_ref - meany_ref * meany_ref);


    rmse  = std::sqrt(rmse);
    rmsex = std::sqrt(rmsex);
    rmsey = std::sqrt(rmsey);

    rmse_ref  = std::sqrt(rmse_ref);
    rmsex_ref = std::sqrt(rmsex_ref);
    rmsey_ref = std::sqrt(rmsey_ref);

    otbAppLogINFO("Estimation of input geom file accuracy: ");
    otbAppLogINFO("Overall Root Mean Square Error: " << rmse_ref << " meters");
    otbAppLogINFO("X Mean Error: " << meanx_ref << " meters");
    otbAppLogINFO("X standard deviation: " << stdevx_ref << " meters");
    otbAppLogINFO("X Root Mean Square Error: " << rmsex_ref << " meters");
    otbAppLogINFO("Y Mean Error: " << meany_ref << " meters");
    otbAppLogINFO("Y standard deviation: " << stdevy_ref << " meters");
    otbAppLogINFO("Y Root Mean Square Error: " << rmsey_ref << " meters\n");

    otbAppLogINFO("Estimation of final accuracy: ");

    otbAppLogINFO("Overall Root Mean Square Error: " << rmse << " meters");
    otbAppLogINFO("X Mean Error: " << meanx << " meters");
    otbAppLogINFO("X standard deviation: " << stdevx << " meters");
    otbAppLogINFO("X Root Mean Square Error: " << rmsex << " meters");
    otbAppLogINFO("Y Mean Error: " << meany << " meters");
    otbAppLogINFO("Y standard deviation: " << stdevy << " meters");
    otbAppLogINFO("Y Root Mean Square Error: " << rmsey << " meters");


    if (IsParameterEnabled("outstat"))
      ofs.close();


    if (IsParameterEnabled("outvector"))
    {
      // Create the datasource (for matches export)
      otb::ogr::Layer               layer(nullptr, false);
      otb::ogr::DataSource::Pointer ogrDS;

      ogrDS                       = otb::ogr::DataSource::New(GetParameterString("outvector"), otb::ogr::DataSource::Modes::Overwrite);
      std::string         projref = MapProjectionParametersHandler::GetProjectionRefFromChoice(this, "map");
      OGRSpatialReference oSRS(projref.c_str());

      // and create the layer
      layer                = ogrDS->CreateLayer("matches", &oSRS, wkbMultiLineString);
      OGRFeatureDefn& defn = layer.GetLayerDefn();
      ogr::Feature    feature(defn);

      feature.SetGeometry(&mls);
      layer.CreateFeature(feature);
    }
  }
};
}
}

OTB_APPLICATION_EXPORT(otb::Wrapper::RefineSensorModel)