View Javadoc
1   /*
2    * Copyright (C) 2017 Alberto Irurueta Carro (alberto@irurueta.com)
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *         http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package com.irurueta.geometry.refiners;
17  
18  import com.irurueta.algebra.Matrix;
19  import com.irurueta.geometry.CoordinatesType;
20  import com.irurueta.geometry.Point2D;
21  import com.irurueta.geometry.ProjectiveTransformation2D;
22  import com.irurueta.geometry.estimators.LockedException;
23  import com.irurueta.geometry.estimators.NotReadyException;
24  import com.irurueta.numerical.EvaluationException;
25  import com.irurueta.numerical.GradientEstimator;
26  import com.irurueta.numerical.fitting.LevenbergMarquardtMultiDimensionFitter;
27  import com.irurueta.numerical.fitting.LevenbergMarquardtMultiDimensionFunctionEvaluator;
28  import com.irurueta.numerical.robust.InliersData;
29  
30  import java.util.BitSet;
31  import java.util.List;
32  
33  /**
34   * A 2D projective transformation refiner using point correspondences.
35   * This class takes into account an initial estimation, inlier point matches
36   * and their residuals to find a solution that minimizes error of inliers in
37   * LMSE terms.
38   * Typically, a refiner is used by a robust estimator, however it can also be
39   * useful in some other situations.
40   */
41  @SuppressWarnings("DuplicatedCode")
42  public class PointCorrespondenceProjectiveTransformation2DRefiner extends
43          ProjectiveTransformation2DRefiner<Point2D, Point2D> {
44  
45      /**
46       * Point to be reused when computing residuals.
47       */
48      private final Point2D residualTestPoint = Point2D.create(CoordinatesType.HOMOGENEOUS_COORDINATES);
49  
50      /**
51       * Constructor.
52       */
53      public PointCorrespondenceProjectiveTransformation2DRefiner() {
54      }
55  
56      /**
57       * Constructor.
58       *
59       * @param initialEstimation           initial estimation to be set.
60       * @param keepCovariance              true if covariance of estimation must be kept after
61       *                                    refinement, false otherwise.
62       * @param inliers                     set indicating which of the provided matches are inliers.
63       * @param residuals                   residuals for matched samples.
64       * @param numInliers                  number of inliers on initial estimation.
65       * @param samples1                    1st set of paired samples.
66       * @param samples2                    2nd set of paired samples.
67       * @param refinementStandardDeviation standard deviation used for
68       *                                    Levenberg-Marquardt fitting.
69       */
70      public PointCorrespondenceProjectiveTransformation2DRefiner(
71              final ProjectiveTransformation2D initialEstimation, final boolean keepCovariance, final BitSet inliers,
72              final double[] residuals, final int numInliers, final List<Point2D> samples1, final List<Point2D> samples2,
73              final double refinementStandardDeviation) {
74          super(initialEstimation, keepCovariance, inliers, residuals, numInliers, samples1, samples2,
75                  refinementStandardDeviation);
76      }
77  
78      /**
79       * Constructor.
80       *
81       * @param initialEstimation           initial estimation to be set.
82       * @param keepCovariance              true if covariance of estimation must be kept after
83       *                                    refinement, false otherwise.
84       * @param inliersData                 inlier data, typically obtained from a robust
85       *                                    estimator.
86       * @param samples1                    1st set of paired samples.
87       * @param samples2                    2nd set of paired samples.
88       * @param refinementStandardDeviation standard deviation used for
89       *                                    Levenberg-Marquardt fitting.
90       */
91      public PointCorrespondenceProjectiveTransformation2DRefiner(
92              final ProjectiveTransformation2D initialEstimation, final boolean keepCovariance,
93              final InliersData inliersData, final List<Point2D> samples1, final List<Point2D> samples2,
94              final double refinementStandardDeviation) {
95          super(initialEstimation, keepCovariance, inliersData, samples1, samples2, refinementStandardDeviation);
96      }
97  
98      /**
99       * Refines provided initial estimation.
100      * This method always sets a value into provided result instance regardless
101      * of the fact that error has actually improved in LMSE terms or not.
102      *
103      * @param result instance where refined estimation will be stored.
104      * @return true if result improves (error decreases) in LMSE terms respect
105      * to initial estimation, false if no improvement has been achieved.
106      * @throws NotReadyException if not enough input data has been provided.
107      * @throws LockedException   if estimator is locked because refinement is
108      *                           already in progress.
109      * @throws RefinerException  if refinement fails for some reason (e.g. unable
110      *                           to converge to a result).
111      */
112     @Override
113     public boolean refine(final ProjectiveTransformation2D result) throws NotReadyException, LockedException,
114             RefinerException {
115         if (isLocked()) {
116             throw new LockedException();
117         }
118         if (!isReady()) {
119             throw new NotReadyException();
120         }
121 
122         locked = true;
123 
124         if (listener != null) {
125             listener.onRefineStart(this, initialEstimation);
126         }
127 
128         initialEstimation.normalize();
129 
130         final var initialTotalResidual = totalResidual(initialEstimation);
131 
132         try {
133             final var initParams = new double[
134                     ProjectiveTransformation2D.HOM_COORDS * ProjectiveTransformation2D.HOM_COORDS];
135             // copy values
136             System.arraycopy(initialEstimation.getT().getBuffer(), 0, initParams, 0, initParams.length);
137 
138             // output values to be fitted/optimized will contain residuals
139             final var y = new double[numInliers];
140             // input values will contain 2 sets of 2D points to compute residuals
141             final var nDims = 2 * Point2D.POINT2D_HOMOGENEOUS_COORDINATES_LENGTH;
142             final var x = new Matrix(numInliers, nDims);
143             final var nSamples = inliers.length();
144             var pos = 0;
145             for (var i = 0; i < nSamples; i++) {
146                 if (inliers.get(i)) {
147                     // sample is inlier
148                     final var inputPoint = samples1.get(i);
149                     final var outputPoint = samples2.get(i);
150                     inputPoint.normalize();
151                     outputPoint.normalize();
152                     x.setElementAt(pos, 0, inputPoint.getHomX());
153                     x.setElementAt(pos, 1, inputPoint.getHomY());
154                     x.setElementAt(pos, 2, inputPoint.getHomW());
155                     x.setElementAt(pos, 3, outputPoint.getHomX());
156                     x.setElementAt(pos, 4, outputPoint.getHomY());
157                     x.setElementAt(pos, 5, outputPoint.getHomW());
158 
159                     y[pos] = residuals[i];
160                     pos++;
161                 }
162             }
163 
164             final var evaluator = new LevenbergMarquardtMultiDimensionFunctionEvaluator() {
165 
166                 private final Point2D inputPoint = Point2D.create(CoordinatesType.HOMOGENEOUS_COORDINATES);
167 
168                 private final Point2D outputPoint = Point2D.create(CoordinatesType.HOMOGENEOUS_COORDINATES);
169 
170                 private final ProjectiveTransformation2D transformation = new ProjectiveTransformation2D();
171 
172                 private final GradientEstimator mGradientEstimator = new GradientEstimator(params -> {
173                     // copy values
174                     System.arraycopy(params, 0, transformation.getT().getBuffer(), 0, params.length);
175                     return residual(transformation, inputPoint, outputPoint);
176                 });
177 
178                 @Override
179                 public int getNumberOfDimensions() {
180                     return nDims;
181                 }
182 
183                 @Override
184                 public double[] createInitialParametersArray() {
185                     return initParams;
186                 }
187 
188                 @Override
189                 public double evaluate(final int i, final double[] point, final double[] params,
190                                        final double[] derivatives) throws EvaluationException {
191                     inputPoint.setHomogeneousCoordinates(point[0], point[1], point[2]);
192                     outputPoint.setHomogeneousCoordinates(point[3], point[4], point[5]);
193 
194                     // copy values
195                     System.arraycopy(params, 0, transformation.getT().getBuffer(), 0, params.length);
196 
197                     final var y = residual(transformation, inputPoint, outputPoint);
198                     mGradientEstimator.gradient(params, derivatives);
199 
200                     return y;
201                 }
202             };
203 
204             final var fitter = new LevenbergMarquardtMultiDimensionFitter(evaluator, x, y,
205                     getRefinementStandardDeviation());
206 
207             fitter.fit();
208 
209             // obtain estimated params
210             final var params = fitter.getA();
211 
212             // update transformation
213 
214             // copy values
215             System.arraycopy(params, 0, result.getT().getBuffer(), 0, params.length);
216 
217             if (keepCovariance) {
218                 // keep covariance
219                 covariance = fitter.getCovar();
220             }
221 
222             final var finalTotalResidual = totalResidual(result);
223             final var errorDecreased = finalTotalResidual < initialTotalResidual;
224 
225             if (listener != null) {
226                 listener.onRefineEnd(this, initialEstimation, result, errorDecreased);
227             }
228 
229             return errorDecreased;
230 
231         } catch (final Exception e) {
232             throw new RefinerException(e);
233         } finally {
234             locked = false;
235         }
236     }
237 
238     /**
239      * Computes the residual between the affine transformation and a pair of
240      * matched points.
241      *
242      * @param transformation a transformation.
243      * @param inputPoint     input 2D point.
244      * @param outputPoint    output 2D point.
245      * @return residual.
246      */
247     private double residual(final ProjectiveTransformation2D transformation, final Point2D inputPoint,
248                             final Point2D outputPoint) {
249         inputPoint.normalize();
250         outputPoint.normalize();
251 
252         transformation.transform(inputPoint, residualTestPoint);
253         return residualTestPoint.distanceTo(outputPoint);
254     }
255 
256     /**
257      * Computes total residual among all provided inlier samples.
258      *
259      * @param transformation a transformation.
260      * @return total residual.
261      */
262     private double totalResidual(final ProjectiveTransformation2D transformation) {
263         var result = 0.0;
264 
265         final var nSamples = inliers.length();
266         for (var i = 0; i < nSamples; i++) {
267             if (inliers.get(i)) {
268                 // sample is inlier
269                 final var inputPoint = samples1.get(i);
270                 final var outputPoint = samples2.get(i);
271                 inputPoint.normalize();
272                 outputPoint.normalize();
273                 result += residual(transformation, inputPoint, outputPoint);
274             }
275         }
276 
277         return result;
278     }
279 }