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.geometry.CoordinatesType;
19  import com.irurueta.geometry.PinholeCamera;
20  import com.irurueta.geometry.Point2D;
21  import com.irurueta.geometry.Point3D;
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.ArrayList;
29  import java.util.List;
30  
31  /**
32   * Finds the best pinhole camera for provided collections of matched 2D/3D
33   * points using LMedS + DLT algorithms.
34   */
35  @SuppressWarnings("DuplicatedCode")
36  public class LMedSDLTPointCorrespondencePinholeCameraRobustEstimator extends
37          DLTPointCorrespondencePinholeCameraRobustEstimator {
38  
39      /**
40       * Default value to be used for stop threshold. Stop threshold can be used
41       * to keep the algorithm iterating in case that best estimated threshold
42       * using median of residuals is not small enough. Once a solution is found
43       * that generates a threshold below this value, the algorithm will stop.
44       * The stop threshold can be used to prevent the LMedS algorithm iterating
45       * too many times in cases where samples have a very similar accuracy.
46       * For instance, in cases where proportion of outliers is very small (close
47       * to 0%), and samples are very accurate (i.e. 1e-6), the algorithm would
48       * iterate for a long time trying to find the best solution when indeed
49       * there is no need to do that if a reasonable threshold has already been
50       * reached.
51       * Because of this behaviour the stop threshold can be set to a value much
52       * lower than the one typically used in RANSAC, and yet the algorithm could
53       * still produce even smaller thresholds in estimated results.
54       */
55      public static final double DEFAULT_STOP_THRESHOLD = 1.0;
56  
57      /**
58       * Minimum allowed stop threshold value.
59       */
60      public static final double MIN_STOP_THRESHOLD = 0.0;
61  
62      /**
63       * Threshold to be used to keep the algorithm iterating in case that best
64       * estimated threshold using median of residuals is not small enough. Once
65       * a solution is found that generates a threshold below this value, the
66       * algorithm will stop.
67       * The stop threshold can be used to prevent the LMedS algorithm iterating
68       * too many times in cases where samples have a very similar accuracy.
69       * For instance, in cases where proportion of outliers is very small (close
70       * to 0%), and samples are very accurate (i.e. 1e-6), the algorithm would
71       * iterate for a long time trying to find the best solution when indeed
72       * there is no need to do that if a reasonable threshold has already been
73       * reached.
74       * Because of this behaviour the stop threshold can be set to a value much
75       * lower than the one typically used in RANSAC, and yet the algorithm could
76       * still produce even smaller thresholds in estimated results.
77       */
78      private double stopThreshold;
79  
80      /**
81       * Constructor.
82       */
83      public LMedSDLTPointCorrespondencePinholeCameraRobustEstimator() {
84          super();
85          stopThreshold = DEFAULT_STOP_THRESHOLD;
86      }
87  
88      /**
89       * Constructor with lists of points to be used to estimate a pinhole camera.
90       * Points in the list located at the same position are considered to be
91       * matched. Hence, both lists must have the same size, and their size must
92       * be greater or equal than MIN_NUMBER_OF_POINT_CORRESPONDENCES.
93       *
94       * @param points3D list of 3D points used to estimate a pinhole camera.
95       * @param points2D list of corresponding projected 2D points used to
96       *                 estimate a pinhole camera.
97       * @throws IllegalArgumentException if provided lists of points don't have
98       *                                  the same size or their size is smaller than required minimum size
99       *                                  (6 correspondences).
100      */
101     public LMedSDLTPointCorrespondencePinholeCameraRobustEstimator(
102             final List<Point3D> points3D, final List<Point2D> points2D) {
103         super(points3D, points2D);
104         stopThreshold = DEFAULT_STOP_THRESHOLD;
105     }
106 
107     /**
108      * Constructor.
109      *
110      * @param listener listener to be notified of events such as when estimation
111      *                 starts, ends or its progress significantly changes.
112      */
113     public LMedSDLTPointCorrespondencePinholeCameraRobustEstimator(
114             final PinholeCameraRobustEstimatorListener listener) {
115         super(listener);
116         stopThreshold = DEFAULT_STOP_THRESHOLD;
117     }
118 
119     /**
120      * Constructor with listener and lists of points to be used ot estimate a
121      * pinhole camera.
122      * Points in the list located at the same position are considered to be
123      * matched. Hence, both lists must have the same size, and their size must
124      * be greater or equal than MIN_NUMBER_OF_POINT_CORRESPONDENCES.
125      *
126      * @param listener listener to be notified of events such as when estimation
127      *                 starts, ends or its progress significantly changes.
128      * @param points3D list of 3D points used to estimate a pinhole camera.
129      * @param points2D list of corresponding projected 2D points used to
130      *                 estimate a pinhole camera.
131      * @throws IllegalArgumentException if provided lists of points don't have
132      *                                  the same size or their size is smaller than required minimum size
133      *                                  (6 correspondences).
134      */
135     public LMedSDLTPointCorrespondencePinholeCameraRobustEstimator(
136             final PinholeCameraRobustEstimatorListener listener,
137             final List<Point3D> points3D, final List<Point2D> points2D) {
138         super(listener, points3D, points2D);
139         stopThreshold = DEFAULT_STOP_THRESHOLD;
140     }
141 
142     /**
143      * Returns threshold to be used to keep the algorithm iterating in case that
144      * best estimated threshold using median of residuals is not small enough.
145      * Once a solution is found that generates a threshold below this value, the
146      * algorithm will stop.
147      * The stop threshold can be used to prevent the LMedS algorithm iterating
148      * too many times in cases where samples have a very similar accuracy.
149      * For instance, in cases where proportion of outliers is very small (close
150      * to 0%), and samples are very accurate (i.e. 1e-6), the algorithm would
151      * iterate for a long time trying to find the best solution when indeed
152      * there is no need to do that if a reasonable threshold has already been
153      * reached.
154      * Because of this behaviour the stop threshold can be set to a value much
155      * lower than the one typically used in RANSAC, and yet the algorithm could
156      * still produce even smaller thresholds in estimated results.
157      *
158      * @return stop threshold to stop the algorithm prematurely when a certain
159      * accuracy has been reached.
160      */
161     public double getStopThreshold() {
162         return stopThreshold;
163     }
164 
165     /**
166      * Sets threshold to be used to keep the algorithm iterating in case that
167      * best estimated threshold using median of residuals is not small enough.
168      * Once a solution is found that generates a threshold below this value, the
169      * algorithm will stop.
170      * The stop threshold can be used to prevent the LMedS algorithm iterating
171      * too many times in cases where samples have a very similar accuracy.
172      * For instance, in cases where proportion of outliers is very small (close
173      * to 0%), and samples are very accurate (i.e. 1e-6), the algorithm would
174      * iterate for a long time trying to find the best solution when indeed
175      * there is no need to do that if a reasonable threshold has already been
176      * reached.
177      * Because of this behaviour the stop threshold can be set to a value much
178      * lower than the one typically used in RANSAC, and yet the algorithm could
179      * still produce even smaller thresholds in estimated results.
180      *
181      * @param stopThreshold stop threshold to stop the algorithm prematurely
182      *                      when a certain accuracy has been reached.
183      * @throws IllegalArgumentException if provided value is zero or negative.
184      * @throws LockedException          if robust estimator is locked because an
185      *                                  estimation is already in progress.
186      */
187     public void setStopThreshold(final double stopThreshold) throws LockedException {
188         if (isLocked()) {
189             throw new LockedException();
190         }
191         if (stopThreshold <= MIN_STOP_THRESHOLD) {
192             throw new IllegalArgumentException();
193         }
194 
195         this.stopThreshold = stopThreshold;
196     }
197 
198     /**
199      * Estimates a pinhole camera using a robust estimator and
200      * the best set of matched 2D/3D point correspondences or 2D line/3D plane
201      * correspondences found using the robust estimator.
202      *
203      * @return a pinhole camera.
204      * @throws LockedException          if robust estimator is locked because an
205      *                                  estimation is already in progress.
206      * @throws NotReadyException        if provided input data is not enough to start
207      *                                  the estimation.
208      * @throws RobustEstimatorException if estimation fails for any reason
209      *                                  (i.e. numerical instability, no solution available, etc).
210      */
211     @Override
212     public PinholeCamera estimate() throws LockedException, NotReadyException, RobustEstimatorException {
213         if (isLocked()) {
214             throw new LockedException();
215         }
216         if (!isReady()) {
217             throw new NotReadyException();
218         }
219 
220         // pinhole camera estimator using DLT (Direct Linear Transform) algorithm
221         final var nonRobustEstimator = new DLTPointCorrespondencePinholeCameraEstimator();
222 
223         nonRobustEstimator.setLMSESolutionAllowed(false);
224         nonRobustEstimator.setPointCorrespondencesNormalized(normalizeSubsetPointCorrespondences);
225 
226         // suggestions
227         nonRobustEstimator.setSuggestSkewnessValueEnabled(isSuggestSkewnessValueEnabled());
228         nonRobustEstimator.setSuggestedSkewnessValue(getSuggestedSkewnessValue());
229         nonRobustEstimator.setSuggestHorizontalFocalLengthEnabled(isSuggestHorizontalFocalLengthEnabled());
230         nonRobustEstimator.setSuggestedHorizontalFocalLengthValue(getSuggestedHorizontalFocalLengthValue());
231         nonRobustEstimator.setSuggestVerticalFocalLengthEnabled(isSuggestVerticalFocalLengthEnabled());
232         nonRobustEstimator.setSuggestedVerticalFocalLengthValue(getSuggestedVerticalFocalLengthValue());
233         nonRobustEstimator.setSuggestAspectRatioEnabled(isSuggestAspectRatioEnabled());
234         nonRobustEstimator.setSuggestedAspectRatioValue(getSuggestedAspectRatioValue());
235         nonRobustEstimator.setSuggestPrincipalPointEnabled(isSuggestPrincipalPointEnabled());
236         nonRobustEstimator.setSuggestedPrincipalPointValue(getSuggestedPrincipalPointValue());
237         nonRobustEstimator.setSuggestRotationEnabled(isSuggestRotationEnabled());
238         nonRobustEstimator.setSuggestedRotationValue(getSuggestedRotationValue());
239         nonRobustEstimator.setSuggestCenterEnabled(isSuggestCenterEnabled());
240         nonRobustEstimator.setSuggestedCenterValue(getSuggestedCenterValue());
241 
242         final var innerEstimator = new LMedSRobustEstimator<>(new LMedSRobustEstimatorListener<PinholeCamera>() {
243 
244             // point to be reused when computing residuals
245             private final Point2D testPoint = Point2D.create(CoordinatesType.HOMOGENEOUS_COORDINATES);
246 
247             // 3D points for a subset of samples
248             private final List<Point3D> subset3D = new ArrayList<>();
249 
250             // 2D points for a subset of samples
251             private final List<Point2D> subset2D = new ArrayList<>();
252 
253             @Override
254             public int getTotalSamples() {
255                 return points3D.size();
256             }
257 
258             @Override
259             public int getSubsetSize() {
260                 return PointCorrespondencePinholeCameraRobustEstimator.MIN_NUMBER_OF_POINT_CORRESPONDENCES;
261             }
262 
263             @Override
264             public void estimatePreliminarSolutions(final int[] samplesIndices, final List<PinholeCamera> solutions) {
265                 subset3D.clear();
266                 subset3D.add(points3D.get(samplesIndices[0]));
267                 subset3D.add(points3D.get(samplesIndices[1]));
268                 subset3D.add(points3D.get(samplesIndices[2]));
269                 subset3D.add(points3D.get(samplesIndices[3]));
270                 subset3D.add(points3D.get(samplesIndices[4]));
271                 subset3D.add(points3D.get(samplesIndices[5]));
272 
273                 subset2D.clear();
274                 subset2D.add(points2D.get(samplesIndices[0]));
275                 subset2D.add(points2D.get(samplesIndices[1]));
276                 subset2D.add(points2D.get(samplesIndices[2]));
277                 subset2D.add(points2D.get(samplesIndices[3]));
278                 subset2D.add(points2D.get(samplesIndices[4]));
279                 subset2D.add(points2D.get(samplesIndices[5]));
280 
281                 try {
282                     nonRobustEstimator.setLists(subset3D, subset2D);
283 
284                     final var cam = nonRobustEstimator.estimate();
285                     solutions.add(cam);
286                 } catch (final Exception e) {
287                     // if points configuration is degenerate, no solution is added
288                 }
289             }
290 
291             @Override
292             public double computeResidual(final PinholeCamera currentEstimation, final int i) {
293                 // pick i-th points
294                 final var point3D = points3D.get(i);
295                 final var point2D = points2D.get(i);
296 
297                 // project point3D into test point
298                 currentEstimation.project(point3D, testPoint);
299 
300                 // compare test point and 2D point
301                 return testPoint.distanceTo(point2D);
302             }
303 
304             @Override
305             public boolean isReady() {
306                 return LMedSDLTPointCorrespondencePinholeCameraRobustEstimator.this.isReady();
307             }
308 
309             @Override
310             public void onEstimateStart(final RobustEstimator<PinholeCamera> estimator) {
311                 if (listener != null) {
312                     listener.onEstimateStart(LMedSDLTPointCorrespondencePinholeCameraRobustEstimator.this);
313                 }
314             }
315 
316             @Override
317             public void onEstimateEnd(final RobustEstimator<PinholeCamera> estimator) {
318                 if (listener != null) {
319                     listener.onEstimateEnd(LMedSDLTPointCorrespondencePinholeCameraRobustEstimator.this);
320                 }
321             }
322 
323             @Override
324             public void onEstimateNextIteration(final RobustEstimator<PinholeCamera> estimator, final int iteration) {
325                 if (listener != null) {
326                     listener.onEstimateNextIteration(
327                             LMedSDLTPointCorrespondencePinholeCameraRobustEstimator.this, iteration);
328                 }
329             }
330 
331             @Override
332             public void onEstimateProgressChange(final RobustEstimator<PinholeCamera> estimator, final float progress) {
333                 if (listener != null) {
334                     listener.onEstimateProgressChange(
335                             LMedSDLTPointCorrespondencePinholeCameraRobustEstimator.this, progress);
336                 }
337             }
338         });
339 
340         try {
341             locked = true;
342             inliersData = null;
343             innerEstimator.setConfidence(confidence);
344             innerEstimator.setMaxIterations(maxIterations);
345             innerEstimator.setProgressDelta(progressDelta);
346             innerEstimator.setStopThreshold(stopThreshold);
347             final var result = innerEstimator.estimate();
348             inliersData = innerEstimator.getInliersData();
349             return attemptRefine(result, nonRobustEstimator.getMaxSuggestionWeight());
350         } catch (final com.irurueta.numerical.LockedException e) {
351             throw new LockedException(e);
352         } catch (final com.irurueta.numerical.NotReadyException e) {
353             throw new NotReadyException(e);
354         } finally {
355             locked = false;
356         }
357     }
358 
359     /**
360      * Returns method being used for robust estimation.
361      *
362      * @return method being used for robust estimation.
363      */
364     @Override
365     public RobustEstimatorMethod getMethod() {
366         return RobustEstimatorMethod.LMEDS;
367     }
368 
369     /**
370      * Gets standard deviation used for Levenberg-Marquardt fitting during
371      * refinement.
372      * Returned value gives an indication of how much variance each residual
373      * has.
374      * Typically, this value is related to the threshold used on each robust
375      * estimation, since residuals of found inliers are within the range of
376      * such threshold.
377      *
378      * @return standard deviation used for refinement.
379      */
380     @Override
381     protected double getRefinementStandardDeviation() {
382         final var inliersData = (LMedSRobustEstimator.LMedSInliersData) getInliersData();
383 
384         // avoid setting a threshold too strict
385         final var threshold = inliersData.getEstimatedThreshold();
386         return Math.max(threshold, stopThreshold);
387     }
388 }