ArUcoExample.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. using OpenCVForUnity.Calib3dModule;
  2. using OpenCVForUnity.CoreModule;
  3. using OpenCVForUnity.ObjdetectModule;
  4. using OpenCVForUnity.UnityUtils;
  5. using System.Collections.Generic;
  6. using UnityEngine;
  7. using UnityEngine.SceneManagement;
  8. using UnityEngine.UI;
  9. namespace OpenCVForUnityExample
  10. {
  11. /// <summary>
  12. /// ArUco Example
  13. /// An example of marker-based AR view and camera pose estimation using the objdetect and aruco module.
  14. /// Referring to https://github.com/opencv/opencv_contrib/blob/4.x/modules/aruco/samples/detect_markers.cpp
  15. /// http://docs.opencv.org/3.1.0/d5/dae/tutorial_aruco_detection.html
  16. /// https://github.com/opencv/opencv/blob/4.x/modules/objdetect/test/test_arucodetection.cpp
  17. /// </summary>
  18. public class ArUcoExample : MonoBehaviour
  19. {
  20. /// <summary>
  21. /// The image texture.
  22. /// </summary>
  23. public Texture2D imgTexture;
  24. [Space(10)]
  25. /// <summary>
  26. /// The dictionary identifier.
  27. /// </summary>
  28. public ArUcoDictionary dictionaryId = ArUcoDictionary.DICT_6X6_250;
  29. /// <summary>
  30. /// The dictionary id dropdown.
  31. /// </summary>
  32. public Dropdown dictionaryIdDropdown;
  33. /// <summary>
  34. /// Determines if shows rejected corners.
  35. /// </summary>
  36. public bool showRejectedCorners = false;
  37. /// <summary>
  38. /// The shows rejected corners toggle.
  39. /// </summary>
  40. public Toggle showRejectedCornersToggle;
  41. /// <summary>
  42. /// Determines if applied the pose estimation.
  43. /// </summary>
  44. public bool applyEstimationPose = true;
  45. /// <summary>
  46. /// The length of the markers' side. Normally, unit is meters.
  47. /// </summary>
  48. public float markerLength = 0.1f;
  49. /// <summary>
  50. /// The AR game object.
  51. /// </summary>
  52. public GameObject arGameObject;
  53. /// <summary>
  54. /// The AR camera.
  55. /// </summary>
  56. public Camera arCamera;
  57. [Space(10)]
  58. /// <summary>
  59. /// Determines if request the AR camera moving.
  60. /// </summary>
  61. public bool shouldMoveARCamera = false;
  62. /// <summary>
  63. /// The rgb mat.
  64. /// </summary>
  65. Mat rgbMat;
  66. /// <summary>
  67. /// The undistorted rgb mat.
  68. /// </summary>
  69. Mat undistortedRgbMat;
  70. /// <summary>
  71. /// The texture.
  72. /// </summary>
  73. Texture2D texture;
  74. // Use this for initialization
  75. void Start()
  76. {
  77. rgbMat = new Mat(imgTexture.height, imgTexture.width, CvType.CV_8UC3);
  78. texture = new Texture2D(rgbMat.cols(), rgbMat.rows(), TextureFormat.RGBA32, false);
  79. gameObject.GetComponent<Renderer>().material.mainTexture = texture;
  80. dictionaryIdDropdown.value = (int)dictionaryId;
  81. showRejectedCornersToggle.isOn = showRejectedCorners;
  82. undistortedRgbMat = new Mat();
  83. DetectMarkers();
  84. }
  85. // Update is called once per frame
  86. void Update()
  87. {
  88. }
  89. private void DetectMarkers()
  90. {
  91. //if true, The error log of the Native side OpenCV will be displayed on the Unity Editor Console.
  92. Utils.setDebugMode(true);
  93. Utils.texture2DToMat(imgTexture, rgbMat);
  94. Debug.Log("imgMat dst ToString " + rgbMat.ToString());
  95. gameObject.transform.localScale = new Vector3(imgTexture.width, imgTexture.height, 1);
  96. Debug.Log("Screen.width " + Screen.width + " Screen.height " + Screen.height + " Screen.orientation " + Screen.orientation);
  97. float width = rgbMat.width();
  98. float height = rgbMat.height();
  99. float imageSizeScale = 1.0f;
  100. float widthScale = (float)Screen.width / width;
  101. float heightScale = (float)Screen.height / height;
  102. if (widthScale < heightScale)
  103. {
  104. Camera.main.orthographicSize = (width * (float)Screen.height / (float)Screen.width) / 2;
  105. imageSizeScale = (float)Screen.height / (float)Screen.width;
  106. }
  107. else
  108. {
  109. Camera.main.orthographicSize = height / 2;
  110. }
  111. // set camera parameters.
  112. int max_d = (int)Mathf.Max(width, height);
  113. double fx = max_d;
  114. double fy = max_d;
  115. double cx = width / 2.0f;
  116. double cy = height / 2.0f;
  117. Mat camMatrix = new Mat(3, 3, CvType.CV_64FC1);
  118. camMatrix.put(0, 0, fx);
  119. camMatrix.put(0, 1, 0);
  120. camMatrix.put(0, 2, cx);
  121. camMatrix.put(1, 0, 0);
  122. camMatrix.put(1, 1, fy);
  123. camMatrix.put(1, 2, cy);
  124. camMatrix.put(2, 0, 0);
  125. camMatrix.put(2, 1, 0);
  126. camMatrix.put(2, 2, 1.0f);
  127. Debug.Log("camMatrix " + camMatrix.dump());
  128. MatOfDouble distCoeffs = new MatOfDouble(0, 0, 0, 0);
  129. Debug.Log("distCoeffs " + distCoeffs.dump());
  130. // calibration camera matrix values.
  131. Size imageSize = new Size(width * imageSizeScale, height * imageSizeScale);
  132. double apertureWidth = 0;
  133. double apertureHeight = 0;
  134. double[] fovx = new double[1];
  135. double[] fovy = new double[1];
  136. double[] focalLength = new double[1];
  137. Point principalPoint = new Point(0, 0);
  138. double[] aspectratio = new double[1];
  139. Calib3d.calibrationMatrixValues(camMatrix, imageSize, apertureWidth, apertureHeight, fovx, fovy, focalLength, principalPoint, aspectratio);
  140. Debug.Log("imageSize " + imageSize.ToString());
  141. Debug.Log("apertureWidth " + apertureWidth);
  142. Debug.Log("apertureHeight " + apertureHeight);
  143. Debug.Log("fovx " + fovx[0]);
  144. Debug.Log("fovy " + fovy[0]);
  145. Debug.Log("focalLength " + focalLength[0]);
  146. Debug.Log("principalPoint " + principalPoint.ToString());
  147. Debug.Log("aspectratio " + aspectratio[0]);
  148. // To convert the difference of the FOV value of the OpenCV and Unity.
  149. double fovXScale = (2.0 * Mathf.Atan((float)(imageSize.width / (2.0 * fx)))) / (Mathf.Atan2((float)cx, (float)fx) + Mathf.Atan2((float)(imageSize.width - cx), (float)fx));
  150. double fovYScale = (2.0 * Mathf.Atan((float)(imageSize.height / (2.0 * fy)))) / (Mathf.Atan2((float)cy, (float)fy) + Mathf.Atan2((float)(imageSize.height - cy), (float)fy));
  151. Debug.Log("fovXScale " + fovXScale);
  152. Debug.Log("fovYScale " + fovYScale);
  153. // Adjust Unity Camera FOV https://github.com/opencv/opencv/commit/8ed1945ccd52501f5ab22bdec6aa1f91f1e2cfd4
  154. if (widthScale < heightScale)
  155. {
  156. arCamera.fieldOfView = (float)(fovx[0] * fovXScale);
  157. }
  158. else
  159. {
  160. arCamera.fieldOfView = (float)(fovy[0] * fovYScale);
  161. }
  162. // Display objects near the camera.
  163. arCamera.nearClipPlane = 0.01f;
  164. Mat ids = new Mat();
  165. List<Mat> corners = new List<Mat>();
  166. List<Mat> rejectedCorners = new List<Mat>();
  167. Mat rotMat = new Mat(3, 3, CvType.CV_64FC1);
  168. MatOfPoint3f objPoints = new MatOfPoint3f(
  169. new Point3(-markerLength / 2f, markerLength / 2f, 0),
  170. new Point3(markerLength / 2f, markerLength / 2f, 0),
  171. new Point3(markerLength / 2f, -markerLength / 2f, 0),
  172. new Point3(-markerLength / 2f, -markerLength / 2f, 0)
  173. );
  174. Dictionary dictionary = Objdetect.getPredefinedDictionary((int)dictionaryId);
  175. DetectorParameters detectorParams = new DetectorParameters();
  176. detectorParams.set_useAruco3Detection(true);
  177. detectorParams.set_cornerRefinementMethod(Objdetect.CORNER_REFINE_SUBPIX);
  178. RefineParameters refineParameters = new RefineParameters(10f, 3f, true);
  179. ArucoDetector arucoDetector = new ArucoDetector(dictionary, detectorParams, refineParameters);
  180. // undistort image.
  181. Calib3d.undistort(rgbMat, undistortedRgbMat, camMatrix, distCoeffs);
  182. // detect markers.
  183. arucoDetector.detectMarkers(undistortedRgbMat, corners, ids, rejectedCorners);
  184. if (corners.Count == ids.total() || ids.total() == 0)
  185. Objdetect.drawDetectedMarkers(undistortedRgbMat, corners, ids, new Scalar(0, 255, 0));
  186. // if at least one marker detected
  187. if (ids.total() > 0)
  188. {
  189. // estimate pose.
  190. if (applyEstimationPose)
  191. {
  192. for (int i = 0; i < ids.total(); i++)
  193. {
  194. using (Mat rvec = new Mat(1, 1, CvType.CV_64FC3))
  195. using (Mat tvec = new Mat(1, 1, CvType.CV_64FC3))
  196. using (Mat corner_4x1 = corners[i].reshape(2, 4)) // 1*4*CV_32FC2 => 4*1*CV_32FC2
  197. using (MatOfPoint2f imagePoints = new MatOfPoint2f(corner_4x1))
  198. {
  199. // Calculate pose for each marker
  200. Calib3d.solvePnP(objPoints, imagePoints, camMatrix, distCoeffs, rvec, tvec);
  201. // In this example we are processing with RGB color image, so Axis-color correspondences are X: blue, Y: green, Z: red. (Usually X: red, Y: green, Z: blue)
  202. Calib3d.drawFrameAxes(undistortedRgbMat, camMatrix, distCoeffs, rvec, tvec, markerLength * 0.5f);
  203. // This example can display the ARObject on only first detected marker.
  204. if (i == 0)
  205. {
  206. // Get translation vector
  207. double[] tvecArr = new double[3];
  208. tvec.get(0, 0, tvecArr);
  209. // Get rotation vector
  210. Mat rvec_3x1 = rvec.reshape(1, 3);
  211. // Convert rotation vector to rotation matrix.
  212. Calib3d.Rodrigues(rvec_3x1, rotMat);
  213. double[] rotMatArr = new double[rotMat.total()];
  214. rotMat.get(0, 0, rotMatArr);
  215. // Convert OpenCV camera extrinsic parameters to Unity Matrix4x4.
  216. Matrix4x4 transformationM = new Matrix4x4(); // from OpenCV
  217. transformationM.SetRow(0, new Vector4((float)rotMatArr[0], (float)rotMatArr[1], (float)rotMatArr[2], (float)tvecArr[0]));
  218. transformationM.SetRow(1, new Vector4((float)rotMatArr[3], (float)rotMatArr[4], (float)rotMatArr[5], (float)tvecArr[1]));
  219. transformationM.SetRow(2, new Vector4((float)rotMatArr[6], (float)rotMatArr[7], (float)rotMatArr[8], (float)tvecArr[2]));
  220. transformationM.SetRow(3, new Vector4(0, 0, 0, 1));
  221. Debug.Log("transformationM " + transformationM.ToString());
  222. Matrix4x4 invertYM = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, new Vector3(1, -1, 1));
  223. Debug.Log("invertYM " + invertYM.ToString());
  224. // right-handed coordinates system (OpenCV) to left-handed one (Unity)
  225. // https://stackoverflow.com/questions/30234945/change-handedness-of-a-row-major-4x4-transformation-matrix
  226. Matrix4x4 ARM = invertYM * transformationM * invertYM;
  227. if (shouldMoveARCamera)
  228. {
  229. ARM = arGameObject.transform.localToWorldMatrix * ARM.inverse;
  230. Debug.Log("ARM " + ARM.ToString());
  231. ARUtils.SetTransformFromMatrix(arCamera.transform, ref ARM);
  232. }
  233. else
  234. {
  235. ARM = arCamera.transform.localToWorldMatrix * ARM;
  236. Debug.Log("ARM " + ARM.ToString());
  237. ARUtils.SetTransformFromMatrix(arGameObject.transform, ref ARM);
  238. }
  239. }
  240. }
  241. }
  242. }
  243. }
  244. if (showRejectedCorners && rejectedCorners.Count > 0)
  245. Objdetect.drawDetectedMarkers(undistortedRgbMat, rejectedCorners, new Mat(), new Scalar(255, 0, 0));
  246. Utils.matToTexture2D(undistortedRgbMat, texture);
  247. Utils.setDebugMode(false, false);
  248. }
  249. private void ResetObjectTransform()
  250. {
  251. // reset AR object transform.
  252. Matrix4x4 i = Matrix4x4.identity;
  253. ARUtils.SetTransformFromMatrix(arCamera.transform, ref i);
  254. ARUtils.SetTransformFromMatrix(arGameObject.transform, ref i);
  255. }
  256. /// <summary>
  257. /// Raises the destroy event.
  258. /// </summary>
  259. void OnDestroy()
  260. {
  261. if (rgbMat != null)
  262. rgbMat.Dispose();
  263. if (undistortedRgbMat != null)
  264. undistortedRgbMat.Dispose();
  265. }
  266. /// <summary>
  267. /// Raises the back button click event.
  268. /// </summary>
  269. public void OnBackButtonClick()
  270. {
  271. SceneManager.LoadScene("OpenCVForUnityExample");
  272. }
  273. /// <summary>
  274. /// Raises the dictionary id dropdown value changed event.
  275. /// </summary>
  276. public void OnDictionaryIdDropdownValueChanged(int result)
  277. {
  278. if ((int)dictionaryId != result)
  279. {
  280. dictionaryId = (ArUcoDictionary)result;
  281. ResetObjectTransform();
  282. DetectMarkers();
  283. }
  284. }
  285. /// <summary>
  286. /// Raises the show rejected corners toggle value changed event.
  287. /// </summary>
  288. public void OnShowRejectedCornersToggleValueChanged()
  289. {
  290. if (showRejectedCorners != showRejectedCornersToggle.isOn)
  291. {
  292. showRejectedCorners = showRejectedCornersToggle.isOn;
  293. ResetObjectTransform();
  294. DetectMarkers();
  295. }
  296. }
  297. public enum ArUcoDictionary
  298. {
  299. DICT_4X4_50 = Objdetect.DICT_4X4_50,
  300. DICT_4X4_100 = Objdetect.DICT_4X4_100,
  301. DICT_4X4_250 = Objdetect.DICT_4X4_250,
  302. DICT_4X4_1000 = Objdetect.DICT_4X4_1000,
  303. DICT_5X5_50 = Objdetect.DICT_5X5_50,
  304. DICT_5X5_100 = Objdetect.DICT_5X5_100,
  305. DICT_5X5_250 = Objdetect.DICT_5X5_250,
  306. DICT_5X5_1000 = Objdetect.DICT_5X5_1000,
  307. DICT_6X6_50 = Objdetect.DICT_6X6_50,
  308. DICT_6X6_100 = Objdetect.DICT_6X6_100,
  309. DICT_6X6_250 = Objdetect.DICT_6X6_250,
  310. DICT_6X6_1000 = Objdetect.DICT_6X6_1000,
  311. DICT_7X7_50 = Objdetect.DICT_7X7_50,
  312. DICT_7X7_100 = Objdetect.DICT_7X7_100,
  313. DICT_7X7_250 = Objdetect.DICT_7X7_250,
  314. DICT_7X7_1000 = Objdetect.DICT_7X7_1000,
  315. DICT_ARUCO_ORIGINAL = Objdetect.DICT_ARUCO_ORIGINAL,
  316. }
  317. }
  318. }