aruco_detector.hpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. // This file is part of OpenCV project.
  2. // It is subject to the license terms in the LICENSE file found in the top-level directory
  3. // of this distribution and at http://opencv.org/license.html
  4. #ifndef OPENCV_OBJDETECT_ARUCO_DETECTOR_HPP
  5. #define OPENCV_OBJDETECT_ARUCO_DETECTOR_HPP
  6. #include <opencv2/objdetect/aruco_dictionary.hpp>
  7. #include <opencv2/objdetect/aruco_board.hpp>
  8. namespace cv {
  9. namespace aruco {
  10. //! @addtogroup objdetect_aruco
  11. //! @{
  12. enum CornerRefineMethod{
  13. CORNER_REFINE_NONE, ///< Tag and corners detection based on the ArUco approach
  14. CORNER_REFINE_SUBPIX, ///< ArUco approach and refine the corners locations using corner subpixel accuracy
  15. CORNER_REFINE_CONTOUR, ///< ArUco approach and refine the corners locations using the contour-points line fitting
  16. CORNER_REFINE_APRILTAG, ///< Tag and corners detection based on the AprilTag 2 approach @cite wang2016iros
  17. };
  18. /** @brief struct DetectorParameters is used by ArucoDetector
  19. */
  20. struct CV_EXPORTS_W_SIMPLE DetectorParameters {
  21. CV_WRAP DetectorParameters() {
  22. adaptiveThreshWinSizeMin = 3;
  23. adaptiveThreshWinSizeMax = 23;
  24. adaptiveThreshWinSizeStep = 10;
  25. adaptiveThreshConstant = 7;
  26. minMarkerPerimeterRate = 0.03;
  27. maxMarkerPerimeterRate = 4.;
  28. polygonalApproxAccuracyRate = 0.03;
  29. minCornerDistanceRate = 0.05;
  30. minDistanceToBorder = 3;
  31. minMarkerDistanceRate = 0.05;
  32. cornerRefinementMethod = (int)CORNER_REFINE_NONE;
  33. cornerRefinementWinSize = 5;
  34. cornerRefinementMaxIterations = 30;
  35. cornerRefinementMinAccuracy = 0.1;
  36. markerBorderBits = 1;
  37. perspectiveRemovePixelPerCell = 4;
  38. perspectiveRemoveIgnoredMarginPerCell = 0.13;
  39. maxErroneousBitsInBorderRate = 0.35;
  40. minOtsuStdDev = 5.0;
  41. errorCorrectionRate = 0.6;
  42. aprilTagQuadDecimate = 0.0;
  43. aprilTagQuadSigma = 0.0;
  44. aprilTagMinClusterPixels = 5;
  45. aprilTagMaxNmaxima = 10;
  46. aprilTagCriticalRad = (float)(10* CV_PI /180);
  47. aprilTagMaxLineFitMse = 10.0;
  48. aprilTagMinWhiteBlackDiff = 5;
  49. aprilTagDeglitch = 0;
  50. detectInvertedMarker = false;
  51. useAruco3Detection = false;
  52. minSideLengthCanonicalImg = 32;
  53. minMarkerLengthRatioOriginalImg = 0.0;
  54. };
  55. /** @brief Read a new set of DetectorParameters from FileNode (use FileStorage.root()).
  56. */
  57. CV_WRAP bool readDetectorParameters(const FileNode& fn);
  58. /** @brief Write a set of DetectorParameters to FileStorage
  59. */
  60. CV_WRAP bool writeDetectorParameters(FileStorage& fs, const String& name = String());
  61. /// minimum window size for adaptive thresholding before finding contours (default 3).
  62. CV_PROP_RW int adaptiveThreshWinSizeMin;
  63. /// maximum window size for adaptive thresholding before finding contours (default 23).
  64. CV_PROP_RW int adaptiveThreshWinSizeMax;
  65. /// increments from adaptiveThreshWinSizeMin to adaptiveThreshWinSizeMax during the thresholding (default 10).
  66. CV_PROP_RW int adaptiveThreshWinSizeStep;
  67. /// constant for adaptive thresholding before finding contours (default 7)
  68. CV_PROP_RW double adaptiveThreshConstant;
  69. /** @brief determine minimum perimeter for marker contour to be detected.
  70. *
  71. * This is defined as a rate respect to the maximum dimension of the input image (default 0.03).
  72. */
  73. CV_PROP_RW double minMarkerPerimeterRate;
  74. /** @brief determine maximum perimeter for marker contour to be detected.
  75. *
  76. * This is defined as a rate respect to the maximum dimension of the input image (default 4.0).
  77. */
  78. CV_PROP_RW double maxMarkerPerimeterRate;
  79. /// minimum accuracy during the polygonal approximation process to determine which contours are squares. (default 0.03)
  80. CV_PROP_RW double polygonalApproxAccuracyRate;
  81. /// minimum distance between corners for detected markers relative to its perimeter (default 0.05)
  82. CV_PROP_RW double minCornerDistanceRate;
  83. /// minimum distance of any corner to the image border for detected markers (in pixels) (default 3)
  84. CV_PROP_RW int minDistanceToBorder;
  85. /** @brief minimum mean distance beetween two marker corners to be considered imilar, so that the smaller one is removed.
  86. *
  87. * The rate is relative to the smaller perimeter of the two markers (default 0.05).
  88. */
  89. CV_PROP_RW double minMarkerDistanceRate;
  90. /** @brief default value CORNER_REFINE_NONE */
  91. CV_PROP_RW int cornerRefinementMethod;
  92. /// window size for the corner refinement process (in pixels) (default 5).
  93. CV_PROP_RW int cornerRefinementWinSize;
  94. /// maximum number of iterations for stop criteria of the corner refinement process (default 30).
  95. CV_PROP_RW int cornerRefinementMaxIterations;
  96. /// minimum error for the stop cristeria of the corner refinement process (default: 0.1)
  97. CV_PROP_RW double cornerRefinementMinAccuracy;
  98. /// number of bits of the marker border, i.e. marker border width (default 1).
  99. CV_PROP_RW int markerBorderBits;
  100. /// number of bits (per dimension) for each cell of the marker when removing the perspective (default 4).
  101. CV_PROP_RW int perspectiveRemovePixelPerCell;
  102. /** @brief width of the margin of pixels on each cell not considered for the determination of the cell bit.
  103. *
  104. * Represents the rate respect to the total size of the cell, i.e. perspectiveRemovePixelPerCell (default 0.13)
  105. */
  106. CV_PROP_RW double perspectiveRemoveIgnoredMarginPerCell;
  107. /** @brief maximum number of accepted erroneous bits in the border (i.e. number of allowed white bits in the border).
  108. *
  109. * Represented as a rate respect to the total number of bits per marker (default 0.35).
  110. */
  111. CV_PROP_RW double maxErroneousBitsInBorderRate;
  112. /** @brief minimun standard deviation in pixels values during the decodification step to apply Otsu
  113. * thresholding (otherwise, all the bits are set to 0 or 1 depending on mean higher than 128 or not) (default 5.0)
  114. */
  115. CV_PROP_RW double minOtsuStdDev;
  116. /// error correction rate respect to the maximun error correction capability for each dictionary (default 0.6).
  117. CV_PROP_RW double errorCorrectionRate;
  118. /** @brief April :: User-configurable parameters.
  119. *
  120. * Detection of quads can be done on a lower-resolution image, improving speed at a cost of
  121. * pose accuracy and a slight decrease in detection rate. Decoding the binary payload is still
  122. */
  123. CV_PROP_RW float aprilTagQuadDecimate;
  124. /// what Gaussian blur should be applied to the segmented image (used for quad detection?)
  125. CV_PROP_RW float aprilTagQuadSigma;
  126. // April :: Internal variables
  127. /// reject quads containing too few pixels (default 5).
  128. CV_PROP_RW int aprilTagMinClusterPixels;
  129. /// how many corner candidates to consider when segmenting a group of pixels into a quad (default 10).
  130. CV_PROP_RW int aprilTagMaxNmaxima;
  131. /** @brief reject quads where pairs of edges have angles that are close to straight or close to 180 degrees.
  132. *
  133. * Zero means that no quads are rejected. (In radians) (default 10*PI/180)
  134. */
  135. CV_PROP_RW float aprilTagCriticalRad;
  136. /// when fitting lines to the contours, what is the maximum mean squared error
  137. CV_PROP_RW float aprilTagMaxLineFitMse;
  138. /** @brief add an extra check that the white model must be (overall) brighter than the black model.
  139. *
  140. * When we build our model of black & white pixels, we add an extra check that the white model must be (overall)
  141. * brighter than the black model. How much brighter? (in pixel values, [0,255]), (default 5)
  142. */
  143. CV_PROP_RW int aprilTagMinWhiteBlackDiff;
  144. /// should the thresholded image be deglitched? Only useful for very noisy images (default 0).
  145. CV_PROP_RW int aprilTagDeglitch;
  146. /** @brief to check if there is a white marker.
  147. *
  148. * In order to generate a "white" marker just invert a normal marker by using a tilde, ~markerImage. (default false)
  149. */
  150. CV_PROP_RW bool detectInvertedMarker;
  151. /** @brief enable the new and faster Aruco detection strategy.
  152. *
  153. * Proposed in the paper:
  154. * Romero-Ramirez et al: Speeded up detection of squared fiducial markers (2018)
  155. * https://www.researchgate.net/publication/325787310_Speeded_Up_Detection_of_Squared_Fiducial_Markers
  156. */
  157. CV_PROP_RW bool useAruco3Detection;
  158. /// minimum side length of a marker in the canonical image. Latter is the binarized image in which contours are searched.
  159. CV_PROP_RW int minSideLengthCanonicalImg;
  160. /// range [0,1], eq (2) from paper. The parameter tau_i has a direct influence on the processing speed.
  161. CV_PROP_RW float minMarkerLengthRatioOriginalImg;
  162. };
  163. /** @brief struct RefineParameters is used by ArucoDetector
  164. */
  165. struct CV_EXPORTS_W_SIMPLE RefineParameters {
  166. CV_WRAP RefineParameters(float minRepDistance = 10.f, float errorCorrectionRate = 3.f, bool checkAllOrders = true);
  167. /** @brief Read a new set of RefineParameters from FileNode (use FileStorage.root()).
  168. */
  169. CV_WRAP bool readRefineParameters(const FileNode& fn);
  170. /** @brief Write a set of RefineParameters to FileStorage
  171. */
  172. CV_WRAP bool writeRefineParameters(FileStorage& fs, const String& name = String());
  173. /** @brief minRepDistance minimum distance between the corners of the rejected candidate and the reprojected marker
  174. in order to consider it as a correspondence.
  175. */
  176. CV_PROP_RW float minRepDistance;
  177. /** @brief minRepDistance rate of allowed erroneous bits respect to the error correction capability of the used dictionary.
  178. *
  179. * -1 ignores the error correction step.
  180. */
  181. CV_PROP_RW float errorCorrectionRate;
  182. /** @brief checkAllOrders consider the four posible corner orders in the rejectedCorners array.
  183. *
  184. * If it set to false, only the provided corner order is considered (default true).
  185. */
  186. CV_PROP_RW bool checkAllOrders;
  187. };
  188. /** @brief The main functionality of ArucoDetector class is detection of markers in an image with detectMarkers() method.
  189. *
  190. * After detecting some markers in the image, you can try to find undetected markers from this dictionary with
  191. * refineDetectedMarkers() method.
  192. *
  193. * @see DetectorParameters, RefineParameters
  194. */
  195. class CV_EXPORTS_W ArucoDetector : public Algorithm
  196. {
  197. public:
  198. /** @brief Basic ArucoDetector constructor
  199. *
  200. * @param dictionary indicates the type of markers that will be searched
  201. * @param detectorParams marker detection parameters
  202. * @param refineParams marker refine detection parameters
  203. */
  204. CV_WRAP ArucoDetector(const Dictionary &dictionary = getPredefinedDictionary(cv::aruco::DICT_4X4_50),
  205. const DetectorParameters &detectorParams = DetectorParameters(),
  206. const RefineParameters& refineParams = RefineParameters());
  207. /** @brief Basic marker detection
  208. *
  209. * @param image input image
  210. * @param corners vector of detected marker corners. For each marker, its four corners
  211. * are provided, (e.g std::vector<std::vector<cv::Point2f> > ). For N detected markers,
  212. * the dimensions of this array is Nx4. The order of the corners is clockwise.
  213. * @param ids vector of identifiers of the detected markers. The identifier is of type int
  214. * (e.g. std::vector<int>). For N detected markers, the size of ids is also N.
  215. * The identifiers have the same order than the markers in the imgPoints array.
  216. * @param rejectedImgPoints contains the imgPoints of those squares whose inner code has not a
  217. * correct codification. Useful for debugging purposes.
  218. *
  219. * Performs marker detection in the input image. Only markers included in the specific dictionary
  220. * are searched. For each detected marker, it returns the 2D position of its corner in the image
  221. * and its corresponding identifier.
  222. * Note that this function does not perform pose estimation.
  223. * @note The function does not correct lens distortion or takes it into account. It's recommended to undistort
  224. * input image with corresponding camera model, if camera parameters are known
  225. * @sa undistort, estimatePoseSingleMarkers, estimatePoseBoard
  226. */
  227. CV_WRAP void detectMarkers(InputArray image, OutputArrayOfArrays corners, OutputArray ids,
  228. OutputArrayOfArrays rejectedImgPoints = noArray()) const;
  229. /** @brief Refine not detected markers based on the already detected and the board layout
  230. *
  231. * @param image input image
  232. * @param board layout of markers in the board.
  233. * @param detectedCorners vector of already detected marker corners.
  234. * @param detectedIds vector of already detected marker identifiers.
  235. * @param rejectedCorners vector of rejected candidates during the marker detection process.
  236. * @param cameraMatrix optional input 3x3 floating-point camera matrix
  237. * \f$A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$
  238. * @param distCoeffs optional vector of distortion coefficients
  239. * \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6],[s_1, s_2, s_3, s_4]])\f$ of 4, 5, 8 or 12 elements
  240. * @param recoveredIdxs Optional array to returns the indexes of the recovered candidates in the
  241. * original rejectedCorners array.
  242. *
  243. * This function tries to find markers that were not detected in the basic detecMarkers function.
  244. * First, based on the current detected marker and the board layout, the function interpolates
  245. * the position of the missing markers. Then it tries to find correspondence between the reprojected
  246. * markers and the rejected candidates based on the minRepDistance and errorCorrectionRate parameters.
  247. * If camera parameters and distortion coefficients are provided, missing markers are reprojected
  248. * using projectPoint function. If not, missing marker projections are interpolated using global
  249. * homography, and all the marker corners in the board must have the same Z coordinate.
  250. */
  251. CV_WRAP void refineDetectedMarkers(InputArray image, const Board &board,
  252. InputOutputArrayOfArrays detectedCorners,
  253. InputOutputArray detectedIds, InputOutputArrayOfArrays rejectedCorners,
  254. InputArray cameraMatrix = noArray(), InputArray distCoeffs = noArray(),
  255. OutputArray recoveredIdxs = noArray()) const;
  256. CV_WRAP const Dictionary& getDictionary() const;
  257. CV_WRAP void setDictionary(const Dictionary& dictionary);
  258. CV_WRAP const DetectorParameters& getDetectorParameters() const;
  259. CV_WRAP void setDetectorParameters(const DetectorParameters& detectorParameters);
  260. CV_WRAP const RefineParameters& getRefineParameters() const;
  261. CV_WRAP void setRefineParameters(const RefineParameters& refineParameters);
  262. /** @brief Stores algorithm parameters in a file storage
  263. */
  264. virtual void write(FileStorage& fs) const override;
  265. /** @brief simplified API for language bindings
  266. */
  267. CV_WRAP inline void write(FileStorage& fs, const String& name) { Algorithm::write(fs, name); }
  268. /** @brief Reads algorithm parameters from a file storage
  269. */
  270. CV_WRAP virtual void read(const FileNode& fn) override;
  271. protected:
  272. struct ArucoDetectorImpl;
  273. Ptr<ArucoDetectorImpl> arucoDetectorImpl;
  274. };
  275. /** @brief Draw detected markers in image
  276. *
  277. * @param image input/output image. It must have 1 or 3 channels. The number of channels is not altered.
  278. * @param corners positions of marker corners on input image.
  279. * (e.g std::vector<std::vector<cv::Point2f> > ). For N detected markers, the dimensions of
  280. * this array should be Nx4. The order of the corners should be clockwise.
  281. * @param ids vector of identifiers for markers in markersCorners .
  282. * Optional, if not provided, ids are not painted.
  283. * @param borderColor color of marker borders. Rest of colors (text color and first corner color)
  284. * are calculated based on this one to improve visualization.
  285. *
  286. * Given an array of detected marker corners and its corresponding ids, this functions draws
  287. * the markers in the image. The marker borders are painted and the markers identifiers if provided.
  288. * Useful for debugging purposes.
  289. */
  290. CV_EXPORTS_W void drawDetectedMarkers(InputOutputArray image, InputArrayOfArrays corners,
  291. InputArray ids = noArray(), Scalar borderColor = Scalar(0, 255, 0));
  292. /** @brief Generate a canonical marker image
  293. *
  294. * @param dictionary dictionary of markers indicating the type of markers
  295. * @param id identifier of the marker that will be returned. It has to be a valid id in the specified dictionary.
  296. * @param sidePixels size of the image in pixels
  297. * @param img output image with the marker
  298. * @param borderBits width of the marker border.
  299. *
  300. * This function returns a marker image in its canonical form (i.e. ready to be printed)
  301. */
  302. CV_EXPORTS_W void generateImageMarker(const Dictionary &dictionary, int id, int sidePixels, OutputArray img,
  303. int borderBits = 1);
  304. //! @}
  305. }
  306. }
  307. #endif