ArUcoCreateMarkerExample.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. using OpenCVForUnity.CoreModule;
  2. using OpenCVForUnity.ImgcodecsModule;
  3. using OpenCVForUnity.ObjdetectModule;
  4. using OpenCVForUnity.UnityUtils;
  5. using System;
  6. using System.IO;
  7. using System.Linq;
  8. using UnityEngine;
  9. using UnityEngine.SceneManagement;
  10. using UnityEngine.UI;
  11. namespace OpenCVForUnityExample
  12. {
  13. /// <summary>
  14. /// ArUco Create Marker Example
  15. /// Referring to https://github.com/opencv/opencv_contrib/blob/4.x/modules/aruco/samples/create_marker.cpp
  16. /// https://github.com/opencv/opencv_contrib/blob/4.x/modules/aruco/samples/create_board.cpp
  17. /// https://github.com/opencv/opencv_contrib/blob/4.x/modules/aruco/samples/create_board_charuco.cpp
  18. /// https://github.com/opencv/opencv_contrib/blob/4.x/modules/aruco/samples/create_diamond.cpp
  19. /// </summary>
  20. public class ArUcoCreateMarkerExample : MonoBehaviour
  21. {
  22. /// <summary>
  23. /// The size of the output marker image (px).
  24. /// </summary>
  25. public int markerSize = 1000;
  26. /// <summary>
  27. /// The marker type.
  28. /// </summary>
  29. public MarkerType markerType = MarkerType.CanonicalMarker;
  30. /// <summary>
  31. /// The marker type dropdown.
  32. /// </summary>
  33. public Dropdown markerTypeDropdown;
  34. /// <summary>
  35. /// The dictionary identifier.
  36. /// </summary>
  37. public ArUcoDictionary dictionaryId = ArUcoDictionary.DICT_6X6_250;
  38. /// <summary>
  39. /// The dictionary id dropdown.
  40. /// </summary>
  41. public Dropdown dictionaryIdDropdown;
  42. /// <summary>
  43. /// The marker identifier.
  44. /// </summary>
  45. public MarkerID markerId = MarkerID.MarkerID_1;
  46. /// <summary>
  47. /// The marker id dropdown.
  48. /// </summary>
  49. public Dropdown markerIdDropdown;
  50. /// <summary>
  51. /// The save path input field.
  52. /// </summary>
  53. public InputField savePathInputField;
  54. /// <summary>
  55. /// The marker img mat.
  56. /// </summary>
  57. Mat markerImg;
  58. /// <summary>
  59. /// The texture.
  60. /// </summary>
  61. Texture2D texture;
  62. // width of the marker borders.
  63. const int borderBits = 1;
  64. // for GridBoard.
  65. // number of markers in X direction
  66. const int gridBoradMarkersX = 5;
  67. // number of markers in Y direction
  68. const int gridBoradMarkersY = 7;
  69. // marker side length (normally in meters)
  70. const float gridBoradMarkerLength = 0.04f;
  71. // separation between two markers (same unit as markerLength)
  72. const float gridBoradMarkerSeparation = 0.01f;
  73. // id of first marker in dictionary to use on board.
  74. const int gridBoradMarkerFirstMarker = 0;
  75. // minimum margins (in pixels) of the board in the output image
  76. const int gridBoradMarginSize = 10;
  77. // for ChArUcoBoard.
  78. // number of chessboard squares in X direction
  79. const int chArUcoBoradMarkersX = 5;
  80. // number of chessboard squares in Y direction
  81. const int chArUcoBoradMarkersY = 7;
  82. // chessboard square side length (normally in meters)
  83. const float chArUcoBoradSquareLength = 0.04f;
  84. // marker side length (same unit than squareLength)
  85. const float chArUcoBoradMarkerLength = 0.02f;
  86. // id of first marker in dictionary to use on board.
  87. const int chArUcoMarkerFirstMarker = 0;
  88. // minimum margins (in pixels) of the board in the output image
  89. const int chArUcoBoradMarginSize = 10;
  90. // set pre4.6.0 chessboard pattern behavior (even row count patterns have a white box in the upper left corner)
  91. const bool useLegacyPattern = false;
  92. // for ChArUcoDiamondMarker.
  93. // number of diamond squares in X direction
  94. const int diamondMarkersX = 3;
  95. // number of diamond squares in Y direction
  96. const int diamondMarkersY = 3;
  97. // size of the diamond squares in pixels
  98. const float diamondSquareLength = 0.1f;
  99. // size of the markers in pixels.
  100. const float diamondMarkerLength = 0.06f;
  101. // identifiers for diamonds in diamond corners.
  102. const int diamondId1 = 45;
  103. const int diamondId2 = 68;
  104. const int diamondId3 = 28;
  105. const int diamondId4 = 74;
  106. const int diamondMarginSize = 0;
  107. // Use this for initialization
  108. void Start()
  109. {
  110. //if true, The error log of the Native side OpenCV will be displayed on the Unity Editor Console.
  111. Utils.setDebugMode(true);
  112. markerImg = new Mat(markerSize, markerSize, CvType.CV_8UC3);
  113. texture = new Texture2D(markerImg.cols(), markerImg.rows(), TextureFormat.RGB24, false);
  114. gameObject.GetComponent<Renderer>().material.mainTexture = texture;
  115. markerTypeDropdown.value = (int)markerType;
  116. markerIdDropdown.value = (int)markerId;
  117. dictionaryIdDropdown.value = (int)dictionaryId;
  118. CreateMarkerImg();
  119. }
  120. // Update is called once per frame
  121. void Update()
  122. {
  123. }
  124. private void CreateMarkerImg()
  125. {
  126. if (markerImg.cols() != markerSize)
  127. {
  128. markerImg.Dispose();
  129. markerImg = new Mat(markerSize, markerSize, CvType.CV_8UC3);
  130. texture = new Texture2D(markerImg.cols(), markerImg.rows(), TextureFormat.RGB24, false);
  131. }
  132. else
  133. {
  134. markerImg.setTo(Scalar.all(255));
  135. }
  136. gameObject.transform.localScale = new Vector3(markerImg.cols(), markerImg.rows(), 1);
  137. float width = markerImg.width() / 0.7f;
  138. float height = markerImg.height() / 0.7f;
  139. float widthScale = (float)Screen.width / width;
  140. float heightScale = (float)Screen.height / height;
  141. if (widthScale < heightScale)
  142. {
  143. Camera.main.orthographicSize = (width * (float)Screen.height / (float)Screen.width) / 2;
  144. gameObject.transform.localPosition = new Vector3(0, -height * 0.1f, 0);
  145. }
  146. else
  147. {
  148. Camera.main.orthographicSize = height / 2;
  149. gameObject.transform.localPosition = new Vector3(width * 0.1f, 0, 0);
  150. }
  151. // create dictinary.
  152. Dictionary dictionary = Objdetect.getPredefinedDictionary((int)dictionaryId);
  153. // draw marker.
  154. switch (markerType)
  155. {
  156. default:
  157. case MarkerType.CanonicalMarker:
  158. Objdetect.generateImageMarker(dictionary, (int)markerId, markerSize, markerImg, borderBits);
  159. Debug.Log("draw CanonicalMarker: " + "dictionaryId " + (int)dictionaryId + " markerId " + (int)markerId + " sidePixels " + markerSize + " borderBits " + borderBits);
  160. break;
  161. case MarkerType.GridBoard:
  162. int gridBoardTotalMarkers = gridBoradMarkersX * gridBoradMarkersY;
  163. Mat gridBoardIds = new Mat(gridBoardTotalMarkers, 1, CvType.CV_32SC1);
  164. gridBoardIds.put(0, 0, Enumerable.Range(gridBoradMarkerFirstMarker, gridBoradMarkerFirstMarker + gridBoardTotalMarkers).ToArray());
  165. GridBoard gridBoard = new GridBoard(new Size(gridBoradMarkersX, gridBoradMarkersY), gridBoradMarkerLength, gridBoradMarkerSeparation, dictionary, gridBoardIds);
  166. gridBoard.generateImage(new Size(markerSize, markerSize), markerImg, gridBoradMarginSize, borderBits);
  167. gridBoard.Dispose();
  168. Debug.Log("draw GridBoard: " + "markersX " + gridBoradMarkersX + " markersY " + gridBoradMarkersY + " markerLength " + gridBoradMarkerLength +
  169. " markerSeparation " + gridBoradMarkerSeparation + " dictionaryId " + (int)dictionaryId + " firstMarkerId " + gridBoradMarkerFirstMarker +
  170. " outSize " + markerSize + " marginSize " + gridBoradMarginSize + " borderBits " + borderBits);
  171. break;
  172. case MarkerType.ChArUcoBoard:
  173. int charucoBoardTotalMarkers = (int)Math.Truncate(chArUcoBoradMarkersX * chArUcoBoradMarkersY / 2.0);
  174. Mat charucoBoardIds = new Mat(charucoBoardTotalMarkers, 1, CvType.CV_32SC1);
  175. charucoBoardIds.put(0, 0, Enumerable.Range(chArUcoMarkerFirstMarker, chArUcoMarkerFirstMarker + charucoBoardTotalMarkers).ToArray());
  176. CharucoBoard charucoBoard = new CharucoBoard(new Size(chArUcoBoradMarkersX, chArUcoBoradMarkersY), chArUcoBoradSquareLength, chArUcoBoradMarkerLength, dictionary, charucoBoardIds);
  177. charucoBoard.setLegacyPattern(useLegacyPattern);
  178. charucoBoard.generateImage(new Size(markerSize, markerSize), markerImg, chArUcoBoradMarginSize, borderBits);
  179. charucoBoard.Dispose();
  180. Debug.Log("draw ChArUcoBoard: " + "markersX " + chArUcoBoradMarkersX + " markersY " + chArUcoBoradMarkersY + " squareLength " + chArUcoBoradSquareLength +
  181. " markerLength " + chArUcoBoradMarkerLength + " dictionaryId " + (int)dictionaryId + " firstMarkerId " + chArUcoMarkerFirstMarker + " outSize " + markerSize +
  182. " marginSize " + chArUcoBoradMarginSize + " borderBits " + borderBits);
  183. break;
  184. case MarkerType.ChArUcoDiamondMarker:
  185. Mat diamondIds = new Mat(4, 1, CvType.CV_32SC1);
  186. diamondIds.put(0, 0, new int[] { diamondId1, diamondId2, diamondId3, diamondId4 });
  187. CharucoBoard charucoDiamondBoard = new CharucoBoard(new Size(diamondMarkersX, diamondMarkersY), diamondSquareLength, diamondMarkerLength, dictionary, diamondIds);
  188. charucoDiamondBoard.generateImage(new Size(markerSize, markerSize), markerImg, diamondMarginSize, borderBits);
  189. charucoDiamondBoard.Dispose();
  190. Debug.Log("draw ChArUcoDiamondMarker: " + "markersX " + diamondMarkersX + " markersY " + diamondMarkersY + " squareLength " + diamondSquareLength +
  191. " markerLength " + diamondMarkerLength +" dictionaryId " + (int)dictionaryId +
  192. " markerIds " + diamondId1 + ", " + diamondId2 + ", " + diamondId3 + ", " + diamondId4 + " outSize " + markerSize + " marginSize " + diamondMarginSize + " borderBits " + borderBits);
  193. break;
  194. }
  195. Utils.matToTexture2D(markerImg, texture, true, 0, true);
  196. }
  197. private void SaveMarkerImg()
  198. {
  199. // save the markerImg.
  200. string saveDirectoryPath = Path.Combine(Application.persistentDataPath, "ArUcoCreateMarkerExample");
  201. string savePath = "";
  202. #if UNITY_WEBGL && !UNITY_EDITOR
  203. string format = "jpg";
  204. MatOfInt compressionParams = new MatOfInt(Imgcodecs.IMWRITE_JPEG_QUALITY, 100);
  205. #else
  206. string format = "png";
  207. MatOfInt compressionParams = new MatOfInt(Imgcodecs.IMWRITE_PNG_COMPRESSION, 0);
  208. #endif
  209. switch (markerType)
  210. {
  211. default:
  212. case MarkerType.CanonicalMarker:
  213. savePath = Path.Combine(saveDirectoryPath, "CanonicalMarker-d" + (int)dictionaryId + "-i" + (int)markerId + "-sp" + markerSize + "-bb" + borderBits + "." + format);
  214. break;
  215. case MarkerType.GridBoard:
  216. savePath = Path.Combine(saveDirectoryPath, "GridBoard-mx" + gridBoradMarkersX + "-my" + gridBoradMarkersY + "-ml" + gridBoradMarkerLength + "-ms" +
  217. gridBoradMarkerSeparation + "-d" + (int)dictionaryId + "-fi" + gridBoradMarkerFirstMarker + "-os" + markerSize + "-ms" + gridBoradMarginSize + "-bb" + borderBits + "." + format);
  218. break;
  219. case MarkerType.ChArUcoBoard:
  220. savePath = Path.Combine(saveDirectoryPath, "ChArUcoBoard-mx" + chArUcoBoradMarkersX + "-my" + chArUcoBoradMarkersY + "-sl" + chArUcoBoradSquareLength +
  221. "-ml" + chArUcoBoradMarkerLength + "-d" + (int)dictionaryId + "-fi" + chArUcoMarkerFirstMarker + "-os" + markerSize + "-ms" + chArUcoBoradMarginSize +
  222. "-bb" + borderBits + "." + format);
  223. break;
  224. case MarkerType.ChArUcoDiamondMarker:
  225. savePath = Path.Combine(saveDirectoryPath, "ChArUcoDiamondMarker-mx" + diamondMarkersX + "-my" + diamondMarkersY + "-sl" + diamondSquareLength + "-ml" +
  226. diamondMarkerLength + "-d" + (int)dictionaryId + "-i" + diamondId1 + "_" + diamondId2 + "_" + diamondId3 + "_" + diamondId4 + "-os" + markerSize +
  227. "-ms" + diamondMarginSize + "-bb" + borderBits + "." + format);
  228. break;
  229. }
  230. if (!Directory.Exists(saveDirectoryPath))
  231. {
  232. Directory.CreateDirectory(saveDirectoryPath);
  233. }
  234. Imgcodecs.imwrite(savePath, markerImg, compressionParams);
  235. savePathInputField.text = savePath;
  236. Debug.Log("savePath: " + savePath);
  237. }
  238. /// <summary>
  239. /// Raises the destroy event.
  240. /// </summary>
  241. void OnDestroy()
  242. {
  243. if (markerImg != null)
  244. markerImg.Dispose();
  245. Utils.setDebugMode(false);
  246. }
  247. /// <summary>
  248. /// Raises the back button click event.
  249. /// </summary>
  250. public void OnBackButtonClick()
  251. {
  252. SceneManager.LoadScene("OpenCVForUnityExample");
  253. }
  254. /// <summary>
  255. /// Raises the marker type dropdown value changed event.
  256. /// </summary>
  257. public void OnMarkerTypeDropdownValueChanged(int result)
  258. {
  259. if ((int)markerType != result)
  260. {
  261. markerType = (MarkerType)result;
  262. markerIdDropdown.interactable = (markerType == MarkerType.CanonicalMarker);
  263. CreateMarkerImg();
  264. }
  265. }
  266. /// <summary>
  267. /// Raises the dictionary id dropdown value changed event.
  268. /// </summary>
  269. public void OnDictionaryIdDropdownValueChanged(int result)
  270. {
  271. if ((int)dictionaryId != result)
  272. {
  273. dictionaryId = (ArUcoDictionary)result;
  274. CreateMarkerImg();
  275. }
  276. }
  277. /// <summary>
  278. /// Raises the marker id dropdown value changed event.
  279. /// </summary>
  280. public void OnMarkerIdDropdownValueChanged(int result)
  281. {
  282. if ((int)markerId != result)
  283. {
  284. markerId = (MarkerID)result;
  285. CreateMarkerImg();
  286. }
  287. }
  288. /// <summary>
  289. /// Raises the save marker img button click event.
  290. /// </summary>
  291. public void OnSaveMarkerImgButtonClick()
  292. {
  293. SaveMarkerImg();
  294. }
  295. public enum MarkerType
  296. {
  297. CanonicalMarker,
  298. GridBoard,
  299. ChArUcoBoard,
  300. ChArUcoDiamondMarker
  301. }
  302. public enum ArUcoDictionary
  303. {
  304. DICT_4X4_50 = Objdetect.DICT_4X4_50,
  305. DICT_4X4_100 = Objdetect.DICT_4X4_100,
  306. DICT_4X4_250 = Objdetect.DICT_4X4_250,
  307. DICT_4X4_1000 = Objdetect.DICT_4X4_1000,
  308. DICT_5X5_50 = Objdetect.DICT_5X5_50,
  309. DICT_5X5_100 = Objdetect.DICT_5X5_100,
  310. DICT_5X5_250 = Objdetect.DICT_5X5_250,
  311. DICT_5X5_1000 = Objdetect.DICT_5X5_1000,
  312. DICT_6X6_50 = Objdetect.DICT_6X6_50,
  313. DICT_6X6_100 = Objdetect.DICT_6X6_100,
  314. DICT_6X6_250 = Objdetect.DICT_6X6_250,
  315. DICT_6X6_1000 = Objdetect.DICT_6X6_1000,
  316. DICT_7X7_50 = Objdetect.DICT_7X7_50,
  317. DICT_7X7_100 = Objdetect.DICT_7X7_100,
  318. DICT_7X7_250 = Objdetect.DICT_7X7_250,
  319. DICT_7X7_1000 = Objdetect.DICT_7X7_1000,
  320. DICT_ARUCO_ORIGINAL = Objdetect.DICT_ARUCO_ORIGINAL,
  321. }
  322. public enum MarkerID
  323. {
  324. MarkerID_0,
  325. MarkerID_1,
  326. MarkerID_2,
  327. MarkerID_3,
  328. MarkerID_4,
  329. MarkerID_5,
  330. MarkerID_6,
  331. MarkerID_7,
  332. MarkerID_8,
  333. MarkerID_9,
  334. }
  335. }
  336. }