View Javadoc
1   /*
2    * Copyright (C) 2015 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.estimators;
17  
18  import com.irurueta.algebra.AlgebraException;
19  import com.irurueta.geometry.CoincidentLinesException;
20  import com.irurueta.geometry.Line2D;
21  import com.irurueta.geometry.ProjectiveTransformation2D;
22  import com.irurueta.numerical.robust.LMedSRobustEstimator;
23  import com.irurueta.numerical.robust.LMedSRobustEstimatorListener;
24  import com.irurueta.numerical.robust.RobustEstimator;
25  import com.irurueta.numerical.robust.RobustEstimatorException;
26  import com.irurueta.numerical.robust.RobustEstimatorMethod;
27  
28  import java.util.List;
29  
30  /**
31   * Finds the best projective 2D transformation for provided collections of
32   * matched 2D lines using LMedS algorithm.
33   */
34  @SuppressWarnings("DuplicatedCode")
35  public class LMedSLineCorrespondenceProjectiveTransformation2DRobustEstimator
36          extends LineCorrespondenceProjectiveTransformation2DRobustEstimator {
37  
38      /**
39       * Default value to be used for stop threshold. Stop threshold can be used
40       * to keep the algorithm iterating in case that best estimated threshold
41       * using median of residuals is not small enough. Once a solution is found
42       * that generates a threshold below this value, the algorithm will stop.
43       * The stop threshold can be used to prevent the LMedS algorithm iterating
44       * too many times in cases where samples have a very similar accuracy.
45       * For instance, in cases where proportion of outliers is very small (close
46       * to 0%), and samples are very accurate (i.e. 1e-6), the algorithm would
47       * iterate for a long time trying to find the best solution when indeed
48       * there is no need to do that if a reasonable threshold has already been
49       * reached.
50       * Because of this behaviour the stop threshold can be set to a value much
51       * lower than the one typically used in RANSAC, and yet the algorithm could
52       * still produce even smaller thresholds in estimated results.
53       */
54      public static final double DEFAULT_STOP_THRESHOLD = 1e-6;
55  
56      /**
57       * Minimum allowed stop threshold value.
58       */
59      public static final double MIN_STOP_THRESHOLD = 0.0;
60  
61      /**
62       * Threshold to be used to keep the algorithm iterating in case that best
63       * estimated threshold using median of residuals is not small enough. Once
64       * a solution is found that generates a threshold below this value, the
65       * algorithm will stop.
66       * The stop threshold can be used to prevent the LMedS algorithm iterating
67       * too many times in cases where samples have a very similar accuracy.
68       * For instance, in cases where proportion of outliers is very small (close
69       * to 0%), and samples are very accurate (i.e. 1e-6), the algorithm would
70       * iterate for a long time trying to find the best solution when indeed
71       * there is no need to do that if a reasonable threshold has already been
72       * reached.
73       * Because of this behaviour the stop threshold can be set to a value much
74       * lower than the one typically used in RANSAC, and yet the algorithm could
75       * still produce even smaller thresholds in estimated results.
76       */
77      private double stopThreshold;
78  
79  
80      /**
81       * Constructor.
82       */
83      public LMedSLineCorrespondenceProjectiveTransformation2DRobustEstimator() {
84          super();
85          stopThreshold = DEFAULT_STOP_THRESHOLD;
86      }
87  
88      /**
89       * Constructor with lists of lines to be used to estimate a projective 2D
90       * transformation.
91       * Lines in the list located at the same position are considered to be
92       * matched. Hence, both lists must have the same size, and their size must
93       * be greater or equal than MINIMUM_SIZE.
94       *
95       * @param inputLines  list of input lines to be used to estimate a projective
96       *                    2D transformation.
97       * @param outputLines list of output lines to be used to estimate a
98       *                    projective 2D transformation.
99       * @throws IllegalArgumentException if provided lists of lines don't have
100      *                                  the same size or their size is smaller than MINIMUM_SIZE.
101      */
102     public LMedSLineCorrespondenceProjectiveTransformation2DRobustEstimator(
103             final List<Line2D> inputLines, final List<Line2D> outputLines) {
104         super(inputLines, outputLines);
105         stopThreshold = DEFAULT_STOP_THRESHOLD;
106     }
107 
108     /**
109      * Constructor.
110      *
111      * @param listener listener to be notified of events such as when estimation
112      *                 starts, ends or its progress significantly changes.
113      */
114     public LMedSLineCorrespondenceProjectiveTransformation2DRobustEstimator(
115             final ProjectiveTransformation2DRobustEstimatorListener listener) {
116         super(listener);
117         stopThreshold = DEFAULT_STOP_THRESHOLD;
118     }
119 
120     /**
121      * Constructor with listener and lists of lines to be used to estimate a
122      * projective 2D transformation.
123      * Lines in the list located at the same position are considered to be
124      * matched. Hence, both lists must have the same size, and their size must
125      * be greater or equal than MINIMUM_SIZE.
126      *
127      * @param listener    listener to be notified of events such as when estimation
128      *                    starts, ends or its progress significantly changes.
129      * @param inputLines  list of input lines to be used to estimate a projective
130      *                    2D transformation.
131      * @param outputLines list of output lines to be used to estimate a
132      *                    projective 2D transformation.
133      * @throws IllegalArgumentException if provided lists of lines don't have
134      *                                  the same size or their size is smaller than MINIMUM_SIZE.
135      */
136     public LMedSLineCorrespondenceProjectiveTransformation2DRobustEstimator(
137             final ProjectiveTransformation2DRobustEstimatorListener listener,
138             final List<Line2D> inputLines, final List<Line2D> outputLines) {
139         super(listener, inputLines, outputLines);
140         stopThreshold = DEFAULT_STOP_THRESHOLD;
141     }
142 
143     /**
144      * Returns threshold to be used to keep the algorithm iterating in case that
145      * best estimated threshold using median of residuals is not small enough.
146      * Once a solution is found that generates a threshold below this value, the
147      * algorithm will stop.
148      * The stop threshold can be used to prevent the LMedS algorithm iterating
149      * too many times in cases where samples have a very similar accuracy.
150      * For instance, in cases where proportion of outliers is very small (close
151      * to 0%), and samples are very accurate (i.e. 1e-6), the algorithm would
152      * iterate for a long time trying to find the best solution when indeed
153      * there is no need to do that if a reasonable threshold has already been
154      * reached.
155      * Because of this behaviour the stop threshold can be set to a value much
156      * lower than the one typically used in RANSAC, and yet the algorithm could
157      * still produce even smaller thresholds in estimated results.
158      *
159      * @return stop threshold to stop the algorithm prematurely when a certain
160      * accuracy has been reached.
161      */
162     public double getStopThreshold() {
163         return stopThreshold;
164     }
165 
166     /**
167      * Sets threshold to be used to keep the algorithm iterating in case that
168      * best estimated threshold using median of residuals is not small enough.
169      * Once a solution is found that generates a threshold below this value, the
170      * algorithm will stop.
171      * The stop threshold can be used to prevent the LMedS algorithm iterating
172      * too many times in cases where samples have a very similar accuracy.
173      * For instance, in cases where proportion of outliers is very small (close
174      * to 0%), and samples are very accurate (i.e. 1e-6), the algorithm would
175      * iterate for a long time trying to find the best solution when indeed
176      * there is no need to do that if a reasonable threshold has already been
177      * reached.
178      * Because of this behaviour the stop threshold can be set to a value much
179      * lower than the one typically used in RANSAC, and yet the algorithm could
180      * still produce even smaller thresholds in estimated results.
181      *
182      * @param stopThreshold stop threshold to stop the algorithm prematurely
183      *                      when a certain accuracy has been reached.
184      * @throws IllegalArgumentException if provided value is zero or negative.
185      * @throws LockedException          if robust estimator is locked because an
186      *                                  estimation is already in progress.
187      */
188     public void setStopThreshold(final double stopThreshold) throws LockedException {
189         if (isLocked()) {
190             throw new LockedException();
191         }
192         if (stopThreshold <= MIN_STOP_THRESHOLD) {
193             throw new IllegalArgumentException();
194         }
195 
196         this.stopThreshold = stopThreshold;
197     }
198 
199     /**
200      * Estimates a projective 2D transformation using a robust estimator and
201      * the best set of matched 2D lines correspondences found using the robust
202      * estimator.
203      *
204      * @return a projective 2D transformation.
205      * @throws LockedException          if robust estimator is locked because an
206      *                                  estimation is already in progress.
207      * @throws NotReadyException        if provided input data is not enough to start
208      *                                  the estimation.
209      * @throws RobustEstimatorException if estimation fails for any reason
210      *                                  (i.e. numerical instability, no solution available, etc).
211      */
212     @Override
213     public ProjectiveTransformation2D estimate() throws LockedException, NotReadyException, RobustEstimatorException {
214         if (isLocked()) {
215             throw new LockedException();
216         }
217         if (!isReady()) {
218             throw new NotReadyException();
219         }
220 
221         final var innerEstimator = new LMedSRobustEstimator<>(
222                 new LMedSRobustEstimatorListener<ProjectiveTransformation2D>() {
223 
224                     // line to be reused when computing residuals
225                     private final Line2D testLine = new Line2D();
226 
227                     @Override
228                     public int getTotalSamples() {
229                         return inputLines.size();
230                     }
231 
232                     @Override
233                     public int getSubsetSize() {
234                         return ProjectiveTransformation2DRobustEstimator.MINIMUM_SIZE;
235                     }
236 
237                     @Override
238                     public void estimatePreliminarSolutions(
239                             final int[] samplesIndices, final List<ProjectiveTransformation2D> solutions) {
240                         final var inputLine1 = inputLines.get(samplesIndices[0]);
241                         final var inputLine2 = inputLines.get(samplesIndices[1]);
242                         final var inputLine3 = inputLines.get(samplesIndices[2]);
243                         final var inputLine4 = inputLines.get(samplesIndices[3]);
244 
245                         final var outputLine1 = outputLines.get(samplesIndices[0]);
246                         final var outputLine2 = outputLines.get(samplesIndices[1]);
247                         final var outputLine3 = outputLines.get(samplesIndices[2]);
248                         final var outputLine4 = outputLines.get(samplesIndices[3]);
249 
250                         try {
251                             final var transformation = new ProjectiveTransformation2D(inputLine1, inputLine2,
252                                     inputLine3, inputLine4, outputLine1, outputLine2, outputLine3, outputLine4);
253                             solutions.add(transformation);
254                         } catch (final CoincidentLinesException e) {
255                             // if lines are coincident, no solution is added
256                         }
257                     }
258 
259                     @Override
260                     public double computeResidual(final ProjectiveTransformation2D currentEstimation, final int i) {
261                         final var inputLine = inputLines.get(i);
262                         final var outputLine = outputLines.get(i);
263 
264                         // transform input line and store result in mTestLine
265                         try {
266                             currentEstimation.transform(inputLine, testLine);
267 
268                             return getResidual(outputLine, testLine);
269                         } catch (final AlgebraException e) {
270                             // this happens when internal matrix of affine transformation
271                             // cannot be reverse (i.e. transformation is not well-defined,
272                             // numerical instabilities, etc.)
273                             return Double.MAX_VALUE;
274                         }
275                     }
276 
277                     @Override
278                     public boolean isReady() {
279                         return LMedSLineCorrespondenceProjectiveTransformation2DRobustEstimator.this.isReady();
280                     }
281 
282                     @Override
283                     public void onEstimateStart(final RobustEstimator<ProjectiveTransformation2D> estimator) {
284                         if (listener != null) {
285                             listener.onEstimateStart(
286                                     LMedSLineCorrespondenceProjectiveTransformation2DRobustEstimator.this);
287                         }
288                     }
289 
290                     @Override
291                     public void onEstimateEnd(final RobustEstimator<ProjectiveTransformation2D> estimator) {
292                         if (listener != null) {
293                             listener.onEstimateEnd(
294                                     LMedSLineCorrespondenceProjectiveTransformation2DRobustEstimator.this);
295                         }
296                     }
297 
298                     @Override
299                     public void onEstimateNextIteration(
300                             final RobustEstimator<ProjectiveTransformation2D> estimator, final int iteration) {
301                         if (listener != null) {
302                             listener.onEstimateNextIteration(
303                                     LMedSLineCorrespondenceProjectiveTransformation2DRobustEstimator.this,
304                                     iteration);
305                         }
306                     }
307 
308                     @Override
309                     public void onEstimateProgressChange(
310                             final RobustEstimator<ProjectiveTransformation2D> estimator, final float progress) {
311                         if (listener != null) {
312                             listener.onEstimateProgressChange(
313                                     LMedSLineCorrespondenceProjectiveTransformation2DRobustEstimator.this,
314                                     progress);
315                         }
316                     }
317                 });
318 
319         try {
320             locked = true;
321             inliersData = null;
322             innerEstimator.setConfidence(confidence);
323             innerEstimator.setMaxIterations(maxIterations);
324             innerEstimator.setProgressDelta(progressDelta);
325             innerEstimator.setStopThreshold(stopThreshold);
326             final var transformation = innerEstimator.estimate();
327             inliersData = innerEstimator.getInliersData();
328             return attemptRefine(transformation);
329         } catch (final com.irurueta.numerical.LockedException e) {
330             throw new LockedException(e);
331         } catch (final com.irurueta.numerical.NotReadyException e) {
332             throw new NotReadyException(e);
333         } finally {
334             locked = false;
335         }
336     }
337 
338     /**
339      * Returns method being used for robust estimation
340      *
341      * @return method being used for robust estimation
342      */
343     @Override
344     public RobustEstimatorMethod getMethod() {
345         return RobustEstimatorMethod.LMEDS;
346     }
347 
348     /**
349      * Gets standard deviation used for Levenberg-Marquardt fitting during
350      * refinement.
351      * Returned value gives an indication of how much variance each residual
352      * has.
353      * Typically, this value is related to the threshold used on each robust
354      * estimation, since residuals of found inliers are within the range of
355      * such threshold.
356      *
357      * @return standard deviation used for refinement.
358      */
359     @Override
360     protected double getRefinementStandardDeviation() {
361         final var inliersData = (LMedSRobustEstimator.LMedSInliersData) getInliersData();
362 
363         // avoid setting a threshold too strict
364         final var threshold = inliersData.getEstimatedThreshold();
365         return Math.max(threshold, stopThreshold);
366     }
367 }