Guest User

HandPoseEstimation

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