HandPoseEstimationExample.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. using UnityEngine;
  2. using UnityEngine.EventSystems;
  3. using UnityEngine.SceneManagement;
  4. using UnityEngine.UI;
  5. using System.Collections;
  6. using System.Collections.Generic;
  7. using OpenCVForUnity.CoreModule;
  8. using OpenCVForUnity.ImgprocModule;
  9. using OpenCVForUnity.UnityUtils.Helper;
  10. using OpenCVForUnity.UnityUtils;
  11. namespace OpenCVForUnityExample
  12. {
  13. /// <summary>
  14. /// Hand Pose Estimation Example
  15. /// Referring to https://www.youtube.com/watch?v=KuGpOxOcpds.
  16. /// </summary>
  17. [RequireComponent (typeof(WebCamTextureToMatHelper))]
  18. public class HandPoseEstimationExample : MonoBehaviour
  19. {
  20. /// <summary>
  21. /// The number of fingers text.
  22. /// </summary>
  23. public UnityEngine.UI.Text numberOfFingersText;
  24. /// <summary>
  25. /// The threashold slider.
  26. /// </summary>
  27. public Slider threasholdSlider;
  28. /// <summary>
  29. /// The texture.
  30. /// </summary>
  31. Texture2D texture;
  32. /// <summary>
  33. /// The BLOB color hsv.
  34. /// </summary>
  35. Scalar blobColorHsv;
  36. ///// <summary>
  37. ///// The BLOB color rgba.
  38. ///// </summary>
  39. //Scalar blobColorRgba;
  40. /// <summary>
  41. /// The detector.
  42. /// </summary>
  43. ColorBlobDetector detector;
  44. /// <summary>
  45. /// The spectrum mat.
  46. /// </summary>
  47. Mat spectrumMat;
  48. /// <summary>
  49. /// Indicates whether is color selected.
  50. /// </summary>
  51. bool isColorSelected = false;
  52. /// <summary>
  53. /// The spectrum size.
  54. /// </summary>
  55. Size SPECTRUM_SIZE;
  56. /// <summary>
  57. /// The contour color.
  58. /// </summary>
  59. Scalar CONTOUR_COLOR;
  60. /// <summary>
  61. /// The contour color white.
  62. /// </summary>
  63. Scalar CONTOUR_COLOR_WHITE;
  64. /// <summary>
  65. /// The number of fingers.
  66. /// </summary>
  67. int numberOfFingers = 0;
  68. /// <summary>
  69. /// The webcam texture to mat helper.
  70. /// </summary>
  71. WebCamTextureToMatHelper webCamTextureToMatHelper;
  72. /// <summary>
  73. /// The stored touch point.
  74. /// </summary>
  75. Point storedTouchPoint;
  76. /// <summary>
  77. /// The FPS monitor.
  78. /// </summary>
  79. FpsMonitor fpsMonitor;
  80. // Use this for initialization
  81. void Start ()
  82. {
  83. fpsMonitor = GetComponent<FpsMonitor> ();
  84. webCamTextureToMatHelper = gameObject.GetComponent<WebCamTextureToMatHelper> ();
  85. #if UNITY_ANDROID && !UNITY_EDITOR
  86. // Avoids the front camera low light issue that occurs in only some Android devices (e.g. Google Pixel, Pixel2).
  87. webCamTextureToMatHelper.avoidAndroidFrontCameraLowLightIssue = true;
  88. #endif
  89. webCamTextureToMatHelper.Initialize ();
  90. }
  91. /// <summary>
  92. /// Raises the web cam texture to mat helper initialized event.
  93. /// </summary>
  94. public void OnWebCamTextureToMatHelperInitialized ()
  95. {
  96. Debug.Log ("OnWebCamTextureToMatHelperInitialized");
  97. Mat webCamTextureMat = webCamTextureToMatHelper.GetMat ();
  98. texture = new Texture2D (webCamTextureMat.cols (), webCamTextureMat.rows (), TextureFormat.RGBA32, false);
  99. gameObject.GetComponent<Renderer> ().material.mainTexture = texture;
  100. gameObject.transform.localScale = new Vector3 (webCamTextureMat.cols (), webCamTextureMat.rows (), 1);
  101. Debug.Log ("Screen.width " + Screen.width + " Screen.height " + Screen.height + " Screen.orientation " + Screen.orientation);
  102. if (fpsMonitor != null) {
  103. fpsMonitor.Add ("width", webCamTextureMat.width ().ToString ());
  104. fpsMonitor.Add ("height", webCamTextureMat.height ().ToString ());
  105. fpsMonitor.Add ("orientation", Screen.orientation.ToString ());
  106. fpsMonitor.consoleText = "Please touch the area of the open hand.";
  107. }
  108. float width = webCamTextureMat.width ();
  109. float height = webCamTextureMat.height ();
  110. float widthScale = (float)Screen.width / width;
  111. float heightScale = (float)Screen.height / height;
  112. if (widthScale < heightScale) {
  113. Camera.main.orthographicSize = (width * (float)Screen.height / (float)Screen.width) / 2;
  114. } else {
  115. Camera.main.orthographicSize = height / 2;
  116. }
  117. detector = new ColorBlobDetector ();
  118. spectrumMat = new Mat ();
  119. //blobColorRgba = new Scalar (255);
  120. blobColorHsv = new Scalar (255);
  121. SPECTRUM_SIZE = new Size (200, 64);
  122. CONTOUR_COLOR = new Scalar (255, 0, 0, 255);
  123. CONTOUR_COLOR_WHITE = new Scalar (255, 255, 255, 255);
  124. }
  125. /// <summary>
  126. /// Raises the web cam texture to mat helper disposed event.
  127. /// </summary>
  128. public void OnWebCamTextureToMatHelperDisposed ()
  129. {
  130. Debug.Log ("OnWebCamTextureToMatHelperDisposed");
  131. if (spectrumMat != null) {
  132. spectrumMat.Dispose ();
  133. spectrumMat = null;
  134. }
  135. if (texture != null) {
  136. Texture2D.Destroy (texture);
  137. texture = null;
  138. }
  139. }
  140. /// <summary>
  141. /// Raises the web cam texture to mat helper error occurred event.
  142. /// </summary>
  143. /// <param name="errorCode">Error code.</param>
  144. public void OnWebCamTextureToMatHelperErrorOccurred (WebCamTextureToMatHelper.ErrorCode errorCode)
  145. {
  146. Debug.Log ("OnWebCamTextureToMatHelperErrorOccurred " + errorCode);
  147. }
  148. // Update is called once per frame
  149. void Update ()
  150. {
  151. #if ((UNITY_ANDROID || UNITY_IOS) && !UNITY_EDITOR)
  152. //Touch
  153. int touchCount = Input.touchCount;
  154. if (touchCount == 1)
  155. {
  156. Touch t = Input.GetTouch (0);
  157. if(t.phase == TouchPhase.Ended && !EventSystem.current.IsPointerOverGameObject (t.fingerId)) {
  158. storedTouchPoint = new Point (t.position.x, t.position.y);
  159. //Debug.Log ("touch X " + t.position.x);
  160. //Debug.Log ("touch Y " + t.position.y);
  161. }
  162. }
  163. #else
  164. //Mouse
  165. if (Input.GetMouseButtonUp (0) && !EventSystem.current.IsPointerOverGameObject ()) {
  166. storedTouchPoint = new Point (Input.mousePosition.x, Input.mousePosition.y);
  167. //Debug.Log ("mouse X " + Input.mousePosition.x);
  168. //Debug.Log ("mouse Y " + Input.mousePosition.y);
  169. }
  170. #endif
  171. if (webCamTextureToMatHelper.IsPlaying () && webCamTextureToMatHelper.DidUpdateThisFrame ()) {
  172. Mat rgbaMat = webCamTextureToMatHelper.GetMat ();
  173. if (storedTouchPoint != null) {
  174. ConvertScreenPointToTexturePoint (storedTouchPoint, storedTouchPoint, gameObject, rgbaMat.cols (), rgbaMat.rows ());
  175. OnTouch (rgbaMat, storedTouchPoint);
  176. storedTouchPoint = null;
  177. }
  178. HandPoseEstimationProcess (rgbaMat);
  179. // Imgproc.putText (rgbaMat, "Please touch the area of the open hand.", new Point (5, rgbaMat.rows () - 10), Imgproc.FONT_HERSHEY_SIMPLEX, 1.0, new Scalar (255, 255, 255, 255), 2, Imgproc.LINE_AA, false);
  180. Utils.fastMatToTexture2D (rgbaMat, texture);
  181. }
  182. }
  183. private void HandPoseEstimationProcess (Mat rgbaMat)
  184. {
  185. //Imgproc.blur(mRgba, mRgba, new Size(5,5));
  186. Imgproc.GaussianBlur (rgbaMat, rgbaMat, new Size (3, 3), 1, 1);
  187. //Imgproc.medianBlur(mRgba, mRgba, 3);
  188. if (!isColorSelected)
  189. return;
  190. List<MatOfPoint> contours = detector.GetContours ();
  191. detector.Process (rgbaMat);
  192. // Debug.Log ("Contours count: " + contours.Count);
  193. if (contours.Count <= 0) {
  194. return;
  195. }
  196. RotatedRect rect = Imgproc.minAreaRect (new MatOfPoint2f (contours [0].toArray ()));
  197. double boundWidth = rect.size.width;
  198. double boundHeight = rect.size.height;
  199. int boundPos = 0;
  200. for (int i = 1; i < contours.Count; i++) {
  201. rect = Imgproc.minAreaRect (new MatOfPoint2f (contours [i].toArray ()));
  202. if (rect.size.width * rect.size.height > boundWidth * boundHeight) {
  203. boundWidth = rect.size.width;
  204. boundHeight = rect.size.height;
  205. boundPos = i;
  206. }
  207. }
  208. MatOfPoint contour = contours [boundPos];
  209. OpenCVForUnity.CoreModule.Rect boundRect = Imgproc.boundingRect (new MatOfPoint (contour.toArray ()));
  210. Imgproc.rectangle (rgbaMat, boundRect.tl (), boundRect.br (), CONTOUR_COLOR_WHITE, 2, 8, 0);
  211. // Debug.Log (
  212. // " Row start [" +
  213. // (int)boundRect.tl ().y + "] row end [" +
  214. // (int)boundRect.br ().y + "] Col start [" +
  215. // (int)boundRect.tl ().x + "] Col end [" +
  216. // (int)boundRect.br ().x + "]");
  217. double a = boundRect.br ().y - boundRect.tl ().y;
  218. a = a * 0.7;
  219. a = boundRect.tl ().y + a;
  220. // Debug.Log (" A [" + a + "] br y - tl y = [" + (boundRect.br ().y - boundRect.tl ().y) + "]");
  221. Imgproc.rectangle (rgbaMat, boundRect.tl (), new Point (boundRect.br ().x, a), CONTOUR_COLOR, 2, 8, 0);
  222. MatOfPoint2f pointMat = new MatOfPoint2f ();
  223. Imgproc.approxPolyDP (new MatOfPoint2f (contour.toArray ()), pointMat, 3, true);
  224. contour = new MatOfPoint (pointMat.toArray ());
  225. MatOfInt hull = new MatOfInt ();
  226. MatOfInt4 convexDefect = new MatOfInt4 ();
  227. Imgproc.convexHull (new MatOfPoint (contour.toArray ()), hull);
  228. if (hull.toArray ().Length < 3)
  229. return;
  230. Imgproc.convexityDefects (new MatOfPoint (contour.toArray ()), hull, convexDefect);
  231. List<MatOfPoint> hullPoints = new List<MatOfPoint> ();
  232. List<Point> listPo = new List<Point> ();
  233. for (int j = 0; j < hull.toList ().Count; j++) {
  234. listPo.Add (contour.toList () [hull.toList () [j]]);
  235. }
  236. MatOfPoint e = new MatOfPoint ();
  237. e.fromList (listPo);
  238. hullPoints.Add (e);
  239. List<Point> listPoDefect = new List<Point> ();
  240. if (convexDefect.rows () > 0) {
  241. List<int> convexDefectList = convexDefect.toList ();
  242. List<Point> contourList = contour.toList ();
  243. for (int j = 0; j < convexDefectList.Count; j = j + 4) {
  244. Point farPoint = contourList [convexDefectList [j + 2]];
  245. int depth = convexDefectList [j + 3];
  246. if (depth > threasholdSlider.value && farPoint.y < a) {
  247. listPoDefect.Add (contourList [convexDefectList [j + 2]]);
  248. }
  249. // Debug.Log ("convexDefectList [" + j + "] " + convexDefectList [j + 3]);
  250. }
  251. }
  252. // Debug.Log ("hull: " + hull.toList ());
  253. // if (convexDefect.rows () > 0) {
  254. // Debug.Log ("defects: " + convexDefect.toList ());
  255. // }
  256. Imgproc.drawContours (rgbaMat, hullPoints, -1, CONTOUR_COLOR, 3);
  257. // int defectsTotal = (int)convexDefect.total();
  258. // Debug.Log ("Defect total " + defectsTotal);
  259. this.numberOfFingers = listPoDefect.Count;
  260. if (this.numberOfFingers > 5)
  261. this.numberOfFingers = 5;
  262. // Debug.Log ("numberOfFingers " + numberOfFingers);
  263. // Imgproc.putText (rgbaMat, "" + numberOfFingers, new Point (rgbaMat.cols () / 2, rgbaMat.rows () / 2), Imgproc.FONT_HERSHEY_PLAIN, 4.0, new Scalar (255, 255, 255, 255), 6, Imgproc.LINE_AA, false);
  264. numberOfFingersText.text = numberOfFingers.ToString ();
  265. foreach (Point p in listPoDefect) {
  266. Imgproc.circle (rgbaMat, p, 6, new Scalar (255, 0, 255, 255), -1);
  267. }
  268. }
  269. private void OnTouch (Mat img, Point touchPoint)
  270. {
  271. int cols = img.cols ();
  272. int rows = img.rows ();
  273. int x = (int)touchPoint.x;
  274. int y = (int)touchPoint.y;
  275. //Debug.Log ("Touch image coordinates: (" + x + ", " + y + ")");
  276. if ((x < 0) || (y < 0) || (x > cols) || (y > rows))
  277. return;
  278. OpenCVForUnity.CoreModule.Rect touchedRect = new OpenCVForUnity.CoreModule.Rect ();
  279. touchedRect.x = (x > 5) ? x - 5 : 0;
  280. touchedRect.y = (y > 5) ? y - 5 : 0;
  281. touchedRect.width = (x + 5 < cols) ? x + 5 - touchedRect.x : cols - touchedRect.x;
  282. touchedRect.height = (y + 5 < rows) ? y + 5 - touchedRect.y : rows - touchedRect.y;
  283. using (Mat touchedRegionRgba = img.submat (touchedRect))
  284. using (Mat touchedRegionHsv = new Mat ()) {
  285. Imgproc.cvtColor (touchedRegionRgba, touchedRegionHsv, Imgproc.COLOR_RGB2HSV_FULL);
  286. // Calculate average color of touched region
  287. blobColorHsv = Core.sumElems (touchedRegionHsv);
  288. int pointCount = touchedRect.width * touchedRect.height;
  289. for (int i = 0; i < blobColorHsv.val.Length; i++)
  290. blobColorHsv.val [i] /= pointCount;
  291. //blobColorRgba = ConverScalarHsv2Rgba (blobColorHsv);
  292. //Debug.Log ("Touched rgba color: (" + mBlobColorRgba.val [0] + ", " + mBlobColorRgba.val [1] +
  293. // ", " + mBlobColorRgba.val [2] + ", " + mBlobColorRgba.val [3] + ")");
  294. detector.SetHsvColor (blobColorHsv);
  295. Imgproc.resize (detector.GetSpectrum (), spectrumMat, SPECTRUM_SIZE);
  296. isColorSelected = true;
  297. }
  298. }
  299. private Scalar ConverScalarHsv2Rgba (Scalar hsvColor)
  300. {
  301. Scalar rgbaColor;
  302. using (Mat pointMatRgba = new Mat ())
  303. using (Mat pointMatHsv = new Mat (1, 1, CvType.CV_8UC3, hsvColor)) {
  304. Imgproc.cvtColor (pointMatHsv, pointMatRgba, Imgproc.COLOR_HSV2RGB_FULL, 4);
  305. rgbaColor = new Scalar (pointMatRgba.get (0, 0));
  306. }
  307. return rgbaColor;
  308. }
  309. /// <summary>
  310. /// Converts the screen point to texture point.
  311. /// </summary>
  312. /// <param name="screenPoint">Screen point.</param>
  313. /// <param name="dstPoint">Dst point.</param>
  314. /// <param name="texturQuad">Texture quad.</param>
  315. /// <param name="textureWidth">Texture width.</param>
  316. /// <param name="textureHeight">Texture height.</param>
  317. /// <param name="camera">Camera.</param>
  318. private void ConvertScreenPointToTexturePoint (Point screenPoint, Point dstPoint, GameObject textureQuad, int textureWidth = -1, int textureHeight = -1, Camera camera = null)
  319. {
  320. if (textureWidth < 0 || textureHeight < 0) {
  321. Renderer r = textureQuad.GetComponent<Renderer> ();
  322. if (r != null && r.material != null && r.material.mainTexture != null) {
  323. textureWidth = r.material.mainTexture.width;
  324. textureHeight = r.material.mainTexture.height;
  325. } else {
  326. textureWidth = (int)textureQuad.transform.localScale.x;
  327. textureHeight = (int)textureQuad.transform.localScale.y;
  328. }
  329. }
  330. if (camera == null)
  331. camera = Camera.main;
  332. Vector3 quadPosition = textureQuad.transform.localPosition;
  333. Vector3 quadScale = textureQuad.transform.localScale;
  334. Vector2 tl = camera.WorldToScreenPoint (new Vector3 (quadPosition.x - quadScale.x / 2, quadPosition.y + quadScale.y / 2, quadPosition.z));
  335. Vector2 tr = camera.WorldToScreenPoint (new Vector3 (quadPosition.x + quadScale.x / 2, quadPosition.y + quadScale.y / 2, quadPosition.z));
  336. Vector2 br = camera.WorldToScreenPoint (new Vector3 (quadPosition.x + quadScale.x / 2, quadPosition.y - quadScale.y / 2, quadPosition.z));
  337. Vector2 bl = camera.WorldToScreenPoint (new Vector3 (quadPosition.x - quadScale.x / 2, quadPosition.y - quadScale.y / 2, quadPosition.z));
  338. using (Mat srcRectMat = new Mat (4, 1, CvType.CV_32FC2))
  339. using (Mat dstRectMat = new Mat (4, 1, CvType.CV_32FC2)) {
  340. srcRectMat.put (0, 0, tl.x, tl.y, tr.x, tr.y, br.x, br.y, bl.x, bl.y);
  341. dstRectMat.put (0, 0, 0, 0, quadScale.x, 0, quadScale.x, quadScale.y, 0, quadScale.y);
  342. using (Mat perspectiveTransform = Imgproc.getPerspectiveTransform (srcRectMat, dstRectMat))
  343. using (MatOfPoint2f srcPointMat = new MatOfPoint2f (screenPoint))
  344. using (MatOfPoint2f dstPointMat = new MatOfPoint2f ()) {
  345. Core.perspectiveTransform (srcPointMat, dstPointMat, perspectiveTransform);
  346. dstPoint.x = dstPointMat.get (0, 0) [0] * textureWidth / quadScale.x;
  347. dstPoint.y = dstPointMat.get (0, 0) [1] * textureHeight / quadScale.y;
  348. }
  349. }
  350. }
  351. /// <summary>
  352. /// Raises the destroy event.
  353. /// </summary>
  354. void OnDestroy ()
  355. {
  356. webCamTextureToMatHelper.Dispose ();
  357. if (detector != null)
  358. detector.Dispose ();
  359. }
  360. /// <summary>
  361. /// Raises the back button click event.
  362. /// </summary>
  363. public void OnBackButtonClick ()
  364. {
  365. SceneManager.LoadScene ("OpenCVForUnityExample");
  366. }
  367. /// <summary>
  368. /// Raises the play button click event.
  369. /// </summary>
  370. public void OnPlayButtonClick ()
  371. {
  372. webCamTextureToMatHelper.Play ();
  373. }
  374. /// <summary>
  375. /// Raises the pause button click event.
  376. /// </summary>
  377. public void OnPauseButtonClick ()
  378. {
  379. webCamTextureToMatHelper.Pause ();
  380. }
  381. /// <summary>
  382. /// Raises the stop button click event.
  383. /// </summary>
  384. public void OnStopButtonClick ()
  385. {
  386. webCamTextureToMatHelper.Stop ();
  387. }
  388. /// <summary>
  389. /// Raises the change camera button click event.
  390. /// </summary>
  391. public void OnChangeCameraButtonClick ()
  392. {
  393. webCamTextureToMatHelper.requestedIsFrontFacing = !webCamTextureToMatHelper.IsFrontFacing ();
  394. }
  395. }
  396. }