ARUtils.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System;
  5. namespace OpenCVForUnity.UnityUtils
  6. {
  7. public struct PoseData
  8. {
  9. public Vector3 pos;
  10. public Quaternion rot;
  11. }
  12. /// <summary>
  13. /// AR utils.
  14. /// </summary>
  15. public class ARUtils
  16. {
  17. /// <summary>
  18. /// Convertes rvec value to rotation transform.
  19. /// </summary>
  20. /// <param name="tvec">Rvec.</param>
  21. /// <returns>Rotation.</returns>
  22. public static Quaternion ConvertRvecToRot (double[] rvec)
  23. {
  24. if (rvec.Length < 3)
  25. return new Quaternion ();
  26. Vector3 _rvec = new Vector3 ((float)rvec[0], (float)rvec[1], (float)rvec[2]);
  27. float theta = _rvec.magnitude;
  28. _rvec.Normalize ();
  29. // http://stackoverflow.com/questions/12933284/rodrigues-into-eulerangles-and-vice-versa
  30. return Quaternion.AngleAxis (theta * Mathf.Rad2Deg, _rvec);
  31. }
  32. /// <summary>
  33. /// Convertes tvec value to position transform.
  34. /// </summary>
  35. /// <param name="tvec">Tvec.</param>
  36. /// <returns>Position.</returns>
  37. public static Vector3 ConvertTvecToPos (double[] tvec)
  38. {
  39. if (tvec.Length < 3)
  40. return new Vector3 ();
  41. return new Vector3 ((float)tvec[0], (float)tvec[1], (float)tvec[2]);
  42. }
  43. /// <summary>
  44. /// Convertes rvec and tvec value to PoseData.
  45. /// </summary>
  46. /// <param name="tvec">Rvec.</param>
  47. /// <param name="tvec">Tvec.</param>
  48. /// <returns>PoseData.</returns>
  49. public static PoseData ConvertRvecTvecToPoseData (double[] rvec, double[] tvec)
  50. {
  51. PoseData data = new PoseData ();
  52. data.pos = ConvertTvecToPos (tvec);
  53. data.rot = ConvertRvecToRot (rvec);
  54. return data;
  55. }
  56. private static Vector3 vector_one = Vector3.one;
  57. private static Matrix4x4 invertYMatrix = Matrix4x4.TRS (Vector3.zero, Quaternion.identity, new Vector3 (1, -1, 1));
  58. private static Matrix4x4 invertZMatrix = Matrix4x4.TRS (Vector3.zero, Quaternion.identity, new Vector3 (1, 1, -1));
  59. /// <summary>
  60. /// Convertes PoseData to transform matrix.
  61. /// </summary>
  62. /// <param name="posedata">PoseData.</param>
  63. /// <param name="toLeftHandCoordinateSystem">Determines if convert the transformation matrix to the left-hand coordinate system.</param>
  64. /// <param name="invertZAxis">Determines if invert Z axis of the transform matrix.</param>
  65. /// <returns>Transform matrix.</returns>
  66. public static Matrix4x4 ConvertPoseDataToMatrix (ref PoseData poseData, bool toLeftHandCoordinateSystem = false, bool invertZAxis = false)
  67. {
  68. Matrix4x4 matrix = Matrix4x4.TRS (poseData.pos, poseData.rot, vector_one);
  69. // right-handed coordinates system (OpenCV) to left-handed one (Unity)
  70. if (toLeftHandCoordinateSystem)
  71. matrix = invertYMatrix * matrix;
  72. // Apply Z axis inverted matrix.
  73. if (invertZAxis)
  74. matrix = matrix * invertZMatrix;
  75. return matrix;
  76. }
  77. /// <summary>
  78. /// Convertes transform matrix to PoseData.
  79. /// </summary>
  80. /// <param name="matrix">Transform matrix.</param>
  81. /// <returns>PoseData.</returns>
  82. public static PoseData ConvertMatrixToPoseData (ref Matrix4x4 matrix)
  83. {
  84. PoseData data = new PoseData ();
  85. data.pos = ExtractTranslationFromMatrix (ref matrix);
  86. data.rot = ExtractRotationFromMatrix (ref matrix);
  87. return data;
  88. }
  89. /// <summary>
  90. /// Creates pose data dictionary.
  91. /// </summary>
  92. /// <param name="markerCount">Marker count.</param>
  93. /// <param name="ids">ids.</param>
  94. /// <param name="rvecs">Rvecs.</param>
  95. /// <param name="tvecs">Tvecs.</param>
  96. /// <returns>PoseData dictionary.</returns>
  97. public static Dictionary<int, PoseData> CreatePoseDataDict (int markerCount, int[] ids, double[] rvecs, double[] tvecs)
  98. {
  99. Dictionary<int, PoseData> dict = new Dictionary<int, PoseData> ();
  100. if (markerCount == 0) return dict;
  101. Vector3 rvec = new Vector3 ();
  102. for (int i = 0; i < markerCount; i++)
  103. {
  104. PoseData data = new PoseData ();
  105. data.pos.Set ((float)tvecs[i * 3], (float)tvecs[i * 3 + 1], (float)tvecs[i * 3 + 2]);
  106. rvec.Set ((float)rvecs[i * 3], (float)rvecs[i * 3 + 1], (float)rvecs[i * 3 + 2]);
  107. float theta = rvec.magnitude;
  108. rvec.Normalize ();
  109. data.rot = Quaternion.AngleAxis (theta * Mathf.Rad2Deg, rvec);
  110. dict[ids[i]] = data;
  111. }
  112. return dict;
  113. }
  114. /// <summary>
  115. /// Performs a lowpass check on the position and rotation in newPose, comparing them to oldPose.
  116. /// </summary>
  117. /// <param name="oldPose">Old PoseData.</param>
  118. /// <param name="newPose">New PoseData.</param>
  119. /// <param name="posThreshold">Positon threshold.</param>
  120. /// <param name="rotThreshold">Rotation threshold.</param>
  121. public static void LowpassPoseData (ref PoseData oldPose, ref PoseData newPose, float posThreshold, float rotThreshold)
  122. {
  123. posThreshold *= posThreshold;
  124. float posDiff = (newPose.pos - oldPose.pos).sqrMagnitude;
  125. float rotDiff = Quaternion.Angle (newPose.rot, oldPose.rot);
  126. if (posDiff < posThreshold)
  127. {
  128. newPose.pos = oldPose.pos;
  129. }
  130. if (rotDiff < rotThreshold)
  131. {
  132. newPose.rot = oldPose.rot;
  133. }
  134. }
  135. /// <summary>
  136. /// Performs a lowpass check on the position and rotation of each marker in newDict, comparing them to those in oldDict.
  137. /// </summary>
  138. /// <param name="oldDict">Old dictionary.</param>
  139. /// <param name="newDict">New dictionary.</param>
  140. /// <param name="posThreshold">Positon threshold.</param>
  141. /// <param name="rotThreshold">Rotation threshold.</param>
  142. public static void LowpassPoseDataDict (Dictionary<int, PoseData> oldDict, Dictionary<int, PoseData> newDict, float posThreshold, float rotThreshold)
  143. {
  144. posThreshold *= posThreshold;
  145. List<int> keys = new List<int> (newDict.Keys);
  146. foreach (int key in keys)
  147. {
  148. if (!oldDict.ContainsKey (key)) continue;
  149. PoseData oldPose = oldDict[key];
  150. PoseData newPose = newDict[key];
  151. float posDiff = (newPose.pos - oldPose.pos).sqrMagnitude;
  152. float rotDiff = Quaternion.Angle (newPose.rot, oldPose.rot);
  153. if (posDiff < posThreshold)
  154. {
  155. newPose.pos = oldPose.pos;
  156. }
  157. if (rotDiff < rotThreshold)
  158. {
  159. newPose.rot = oldPose.rot;
  160. }
  161. newDict[key] = newPose;
  162. }
  163. }
  164. /// <summary>
  165. /// Extract translation from transform matrix.
  166. /// </summary>
  167. /// <param name="matrix">Transform matrix. This parameter is passed by reference
  168. /// to improve performance; no changes will be made to it.</param>
  169. /// <returns>
  170. /// Translation offset.
  171. /// </returns>
  172. public static Vector3 ExtractTranslationFromMatrix (ref Matrix4x4 matrix)
  173. {
  174. Vector3 translate;
  175. translate.x = matrix.m03;
  176. translate.y = matrix.m13;
  177. translate.z = matrix.m23;
  178. return translate;
  179. }
  180. /// <summary>
  181. /// Extract rotation quaternion from transform matrix.
  182. /// </summary>
  183. /// <param name="matrix">Transform matrix. This parameter is passed by reference
  184. /// to improve performance; no changes will be made to it.</param>
  185. /// <returns>
  186. /// Quaternion representation of rotation transform.
  187. /// </returns>
  188. public static Quaternion ExtractRotationFromMatrix (ref Matrix4x4 matrix)
  189. {
  190. Vector3 forward;
  191. forward.x = matrix.m02;
  192. forward.y = matrix.m12;
  193. forward.z = matrix.m22;
  194. Vector3 upwards;
  195. upwards.x = matrix.m01;
  196. upwards.y = matrix.m11;
  197. upwards.z = matrix.m21;
  198. return Quaternion.LookRotation (forward, upwards);
  199. }
  200. /// <summary>
  201. /// Extract scale from transform matrix.
  202. /// </summary>
  203. /// <param name="matrix">Transform matrix. This parameter is passed by reference
  204. /// to improve performance; no changes will be made to it.</param>
  205. /// <returns>
  206. /// Scale vector.
  207. /// </returns>
  208. public static Vector3 ExtractScaleFromMatrix (ref Matrix4x4 matrix)
  209. {
  210. Vector3 scale;
  211. scale.x = new Vector4 (matrix.m00, matrix.m10, matrix.m20, matrix.m30).magnitude;
  212. scale.y = new Vector4 (matrix.m01, matrix.m11, matrix.m21, matrix.m31).magnitude;
  213. scale.z = new Vector4 (matrix.m02, matrix.m12, matrix.m22, matrix.m32).magnitude;
  214. return scale;
  215. }
  216. /// <summary>
  217. /// Extract position, rotation and scale from TRS matrix.
  218. /// </summary>
  219. /// <param name="matrix">Transform matrix. This parameter is passed by reference
  220. /// to improve performance; no changes will be made to it.</param>
  221. /// <param name="localPosition">Output position.</param>
  222. /// <param name="localRotation">Output rotation.</param>
  223. /// <param name="localScale">Output scale.</param>
  224. public static void DecomposeMatrix (ref Matrix4x4 matrix, out Vector3 localPosition, out Quaternion localRotation, out Vector3 localScale)
  225. {
  226. localPosition = ExtractTranslationFromMatrix (ref matrix);
  227. localRotation = ExtractRotationFromMatrix (ref matrix);
  228. localScale = ExtractScaleFromMatrix (ref matrix);
  229. }
  230. /// <summary>
  231. /// Set transform component from TRS matrix.
  232. /// </summary>
  233. /// <param name="transform">Transform component.</param>
  234. /// <param name="matrix">Transform matrix. This parameter is passed by reference
  235. /// to improve performance; no changes will be made to it.</param>
  236. public static void SetTransformFromMatrix (Transform transform, ref Matrix4x4 matrix)
  237. {
  238. transform.localPosition = ExtractTranslationFromMatrix (ref matrix);
  239. transform.localRotation = ExtractRotationFromMatrix (ref matrix);
  240. transform.localScale = ExtractScaleFromMatrix (ref matrix);
  241. }
  242. /// <summary>
  243. /// Calculate projection matrix from camera matrix values.
  244. /// </summary>
  245. /// <param name="fx">Focal length x.</param>
  246. /// <param name="fy">Focal length y.</param>
  247. /// <param name="cx">Image center point x.(principal point x)</param>
  248. /// <param name="cy">Image center point y.(principal point y)</param>
  249. /// <param name="width">Image width.</param>
  250. /// <param name="height">Image height.</param>
  251. /// <param name="near">The near clipping plane distance.</param>
  252. /// <param name="far">The far clipping plane distance.</param>
  253. /// <returns>
  254. /// Projection matrix.
  255. /// </returns>
  256. public static Matrix4x4 CalculateProjectionMatrixFromCameraMatrixValues (float fx, float fy, float cx, float cy, float width, float height, float near, float far)
  257. {
  258. Matrix4x4 projectionMatrix = new Matrix4x4 ();
  259. projectionMatrix.m00 = 2.0f * fx / width;
  260. projectionMatrix.m02 = 1.0f - 2.0f * cx / width;
  261. projectionMatrix.m11 = 2.0f * fy / height;
  262. projectionMatrix.m12 = -1.0f + 2.0f * cy / height;
  263. projectionMatrix.m22 = -(far + near) / (far - near);
  264. projectionMatrix.m23 = -2.0f * far * near / (far - near);
  265. projectionMatrix.m32 = -1.0f;
  266. return projectionMatrix;
  267. }
  268. /// <summary>
  269. /// Calculate camera matrix values from projection matrix.
  270. /// </summary>
  271. /// <param name="projectionMatrix">Projection matrix.</param>
  272. /// <param name="width">Image width.</param>
  273. /// <param name="height">Image height.</param>
  274. /// <param name="fovV">Vertical field of view.</param>
  275. /// <returns>
  276. /// Camera matrix values. (fx = matrx.m00, fy = matrx.m11, cx = matrx.m02, cy = matrx.m12)
  277. /// </returns>
  278. public static Matrix4x4 CameraMatrixValuesFromCalculateProjectionMatrix (Matrix4x4 projectionMatrix, float width, float height, float fovV)
  279. {
  280. float fovH = 2.0f * Mathf.Atan (width / height * Mathf.Tan (fovV * Mathf.Deg2Rad / 2.0f)) * Mathf.Rad2Deg;
  281. Matrix4x4 cameraMatrix = new Matrix4x4 ();
  282. cameraMatrix.m00 = CalculateDistance (width, fovH);
  283. cameraMatrix.m02 = -((projectionMatrix.m02 * width - width) / 2);
  284. cameraMatrix.m11 = CalculateDistance (height, fovV);
  285. cameraMatrix.m12 = (projectionMatrix.m12 * height + height) / 2;
  286. cameraMatrix.m22 = 1.0f;
  287. return cameraMatrix;
  288. }
  289. /// <summary>
  290. /// Calculate frustum size.
  291. /// https://docs.unity3d.com/Manual/FrustumSizeAtDistance.html
  292. /// </summary>
  293. /// <param name="distance">Distance.</param>
  294. /// <param name="fov">Field of view. (horizontal or vertical direction)</param>
  295. /// <returns>
  296. /// Frustum height.
  297. /// </returns>
  298. public static float CalculateFrustumSize (float distance, float fov)
  299. {
  300. return 2.0f * distance * Mathf.Tan (fov * 0.5f * Mathf.Deg2Rad);
  301. }
  302. /// <summary>
  303. /// Calculate distance.
  304. /// https://docs.unity3d.com/Manual/FrustumSizeAtDistance.html
  305. /// </summary>
  306. /// <param name="frustumHeight">One side size of a frustum.</param>
  307. /// <param name="fov">Field of view. (horizontal or vertical direction)</param>
  308. /// <returns>
  309. /// Distance.
  310. /// </returns>
  311. public static float CalculateDistance (float frustumSize, float fov)
  312. {
  313. return frustumSize * 0.5f / Mathf.Tan (fov * 0.5f * Mathf.Deg2Rad);
  314. }
  315. /// <summary>
  316. /// Calculate FOV angle.
  317. /// https://docs.unity3d.com/Manual/FrustumSizeAtDistance.html
  318. /// </summary>
  319. /// <param name="frustumHeight">One side size of a frustum.</param>
  320. /// <param name="distance">Distance.</param>
  321. /// <returns>
  322. /// FOV angle.
  323. /// </returns>
  324. public static float CalculateFOVAngle (float frustumSize, float distance)
  325. {
  326. return 2.0f * Mathf.Atan (frustumSize * 0.5f / distance) * Mathf.Rad2Deg;
  327. }
  328. }
  329. }