Ransac.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. namespace VisualMath.Accord.MachineLearning
  2. {
  3. using System;
  4. /// <summary>
  5. /// Multipurpose RANSAC algorithm.
  6. /// </summary>
  7. /// <typeparam name="TModel">The model type to be trained by RANSAC.</typeparam>
  8. /// <remarks>
  9. /// RANSAC is an abbreviation for "RANdom SAmple Consensus". It is an iterative
  10. /// method to estimate parameters of a mathematical model from a set of observed
  11. /// data which contains outliers. It is a non-deterministic algorithm in the sense
  12. /// that it produces a reasonable result only with a certain probability, with this
  13. /// probability increasing as more iterations are allowed.
  14. /// </remarks>
  15. ///
  16. public class RANSAC<TModel> where TModel : class
  17. {
  18. // Ransac parameters
  19. private int s; // number of samples
  20. private double t; // inlier threshold
  21. private int maxSamplings = 100;
  22. private int maxEvaluations = 1000;
  23. private double probability = 0.99;
  24. // Ransac functions
  25. private Func<int[], TModel> fitting;
  26. private Func<TModel, double, int[]> distances;
  27. private Func<int[], bool> degenerate;
  28. #region Properties
  29. /// <summary>
  30. /// Model fitting function.
  31. /// </summary>
  32. public Func<int[], TModel> Fitting
  33. {
  34. get { return fitting; }
  35. set { fitting = value; }
  36. }
  37. /// <summary>
  38. /// Degenerative set detection function.
  39. /// </summary>
  40. public Func<int[], bool> Degenerate
  41. {
  42. get { return degenerate; }
  43. set { degenerate = value; }
  44. }
  45. /// <summary>
  46. /// Distance function.
  47. /// </summary>
  48. public Func<TModel, double, int[]> Distances
  49. {
  50. get { return distances; }
  51. set { distances = value; }
  52. }
  53. /// <summary>
  54. /// Gets or sets the minimum distance between a data point and
  55. /// the model used to decide whether the point is an inlier or not.
  56. /// </summary>
  57. public double Threshold
  58. {
  59. get { return t; }
  60. set { t = value; }
  61. }
  62. /// <summary>
  63. /// Gets or sets the minimum number of samples from the data
  64. /// required by the fitting function to fit a model.
  65. /// </summary>
  66. public int Samples
  67. {
  68. get { return s; }
  69. set { s = value; }
  70. }
  71. /// <summary>
  72. /// Maximum number of attempts to select a non-degenerate data set.
  73. /// </summary>
  74. /// <remarks>
  75. /// The default value is 100.
  76. /// </remarks>
  77. public int MaxSamplings
  78. {
  79. get { return maxSamplings; }
  80. set { maxSamplings = value; }
  81. }
  82. /// <summary>
  83. /// Maximum number of iterations.
  84. /// </summary>
  85. /// <remarks>
  86. /// The default value is 1000.
  87. /// </remarks>
  88. public int MaxEvaluations
  89. {
  90. get { return maxEvaluations; }
  91. set { maxEvaluations = value; }
  92. }
  93. /// <summary>
  94. /// Gets or sets the probability of obtaining a random
  95. /// sample of the input points that contains no outliers.
  96. /// </summary>
  97. public double Probability
  98. {
  99. get { return probability; }
  100. set { probability = value; }
  101. }
  102. #endregion
  103. /// <summary>
  104. /// Constructs a new RANSAC algorithm.
  105. /// </summary>
  106. /// <param name="minSamples">
  107. /// The minimum number of samples from the data
  108. /// required by the fitting function to fit a model.
  109. /// </param>
  110. public RANSAC(int minSamples)
  111. {
  112. this.s = minSamples;
  113. }
  114. /// <summary>
  115. /// Constructs a new RANSAC algorithm.
  116. /// </summary>
  117. /// <param name="minSamples">
  118. /// The minimum number of samples from the data
  119. /// required by the fitting function to fit a model.
  120. /// </param>
  121. /// <param name="threshold">
  122. /// The minimum distance between a data point and
  123. /// the model used to decide whether the point is
  124. /// an inlier or not.
  125. /// </param>
  126. public RANSAC(int minSamples, double threshold)
  127. {
  128. this.s = minSamples;
  129. this.t = threshold;
  130. }
  131. /// <summary>
  132. /// Constructs a new RANSAC algorithm.
  133. /// </summary>
  134. /// <param name="minSamples">
  135. /// The minimum number of samples from the data
  136. /// required by the fitting function to fit a model.
  137. /// </param>
  138. /// <param name="threshold">
  139. /// The minimum distance between a data point and
  140. /// the model used to decide whether the point is
  141. /// an inlier or not.
  142. /// </param>
  143. /// <param name="probability">
  144. /// The probability of obtaining a random sample of
  145. /// the input points that contains no outliers.
  146. /// </param>
  147. public RANSAC(int minSamples, double threshold, double probability)
  148. {
  149. if (minSamples < 0) throw new ArgumentOutOfRangeException("minSamples");
  150. if (threshold < 0) throw new ArgumentOutOfRangeException("threshold");
  151. if (probability > 1.0 || probability < 0.0)
  152. throw new ArgumentException("Probability should be a value between 0 and 1", "probability");
  153. this.s = minSamples;
  154. this.t = threshold;
  155. this.probability = probability;
  156. }
  157. /// <summary>
  158. /// Computes the model using the RANSAC algorithm.
  159. /// </summary>
  160. /// <param name="size">The total number of points in the data set.</param>
  161. public TModel Compute(int size)
  162. {
  163. int[] inliers;
  164. return Compute(size, out inliers);
  165. }
  166. /// <summary>
  167. /// Computes the model using the RANSAC algorithm.
  168. /// </summary>
  169. /// <param name="size">The total number of points in the data set.</param>
  170. /// <param name="inliers">The indexes of the outlier points in the data set.</param>
  171. public TModel Compute(int size, out int[] inliers)
  172. {
  173. // We are going to find the best model (which fits
  174. // the maximum number of inlier points as possible).
  175. TModel bestModel = null;
  176. int[] bestInliers = null;
  177. int maxInliers = 0;
  178. // For this we are going to search for random samples
  179. // of the original points which contains no outliers.
  180. int count = 0; // Total number of trials performed
  181. double N = maxEvaluations; // Estimative of number of trials needed.
  182. // While the number of trials is less than our estimative,
  183. // and we have not surpassed the maximum number of trials
  184. while (count < N && count < maxEvaluations)
  185. {
  186. TModel model = null;
  187. int[] sample = null;
  188. int samplings = 0;
  189. // While the number of samples attempted is less
  190. // than the maximum limit of attempts
  191. while (samplings < maxSamplings)
  192. {
  193. // Select at random s datapoints to form a trial model.
  194. sample = Statistics.Tools.Random(size, s);
  195. // If the sampled points are not in a degenerate configuration,
  196. if (!degenerate(sample))
  197. {
  198. // Fit model using the random selection of points
  199. model = fitting(sample);
  200. break; // Exit the while loop.
  201. }
  202. samplings++; // Increase the samplings counter
  203. }
  204. // Now, evaluate the distances between total points and the model returning the
  205. // indices of the points that are inliers (according to a distance threshold t).
  206. inliers = distances(model, t);
  207. // Check if the model was the model which highest number of inliers:
  208. if (inliers.Length > maxInliers)
  209. {
  210. // Yes, this model has the highest number of inliers.
  211. maxInliers = inliers.Length; // Set the new maximum,
  212. bestModel = model; // This is the best model found so far,
  213. bestInliers = inliers; // Store the indices of the current inliers.
  214. // Update estimate of N, the number of trials to ensure we pick,
  215. // with probability p, a data set with no outliers.
  216. double pInlier = (double)inliers.Length / (double)size;
  217. double pNoOutliers = 1.0 - System.Math.Pow(pInlier, s);
  218. N = System.Math.Log(1.0 - probability) / System.Math.Log(pNoOutliers);
  219. }
  220. count++; // Increase the trial counter.
  221. }
  222. inliers = bestInliers;
  223. return bestModel;
  224. }
  225. }
  226. }