Advertisement
Guest User

Untitled

a guest
Jul 10th, 2018
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 5.91 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using OpenCVForUnity;
  5. using System;
  6. using OpenCVForUnity.RectangleTrack;
  7. using HoloLensWithOpenCVForUnityExample;
  8. #if WINDOWS_UWP
  9. using System.Threading.Tasks;
  10. #else
  11. using System.Threading;
  12. #endif
  13.  
  14. public class Test : MonoBehaviour {
  15.  
  16.     HoloLensWithOpenCVForUnityExample.HololensCameraStreamToMatHelper camToStreamHelper;
  17.  
  18.     DetectThread dt, dt2;
  19.     /// <summary>
  20.     /// The min detection size ratio.
  21.     /// </summary>
  22.     public float m_minDetectionSizeRatio = 0.07f;
  23.  
  24.     public string m_cascadeFileName = "cascade.xml";
  25.  
  26.     public string m_cascadeFileName2 = "cascade.xml";
  27.  
  28.     public GameObject m_TestCube, m_TestCube2;
  29.  
  30.     //Mat grayMat;
  31.  
  32.     // Use this for initialization
  33.     void Start ()
  34.     {
  35.         camToStreamHelper = gameObject.GetComponent<HoloLensWithOpenCVForUnityExample.HololensCameraStreamToMatHelper>();
  36.         camToStreamHelper.frameMatAcquired += OnFrameMatAcquired;
  37.         camToStreamHelper.Initialize();
  38.  
  39.  
  40.     }
  41.  
  42.     // Update is called once per frame
  43.     void Update()
  44.     {
  45.         if (camToStreamHelper.IsPlaying() && camToStreamHelper.DidUpdateThisFrame())
  46.         {
  47.  
  48.             Mat rgbaMat = camToStreamHelper.GetMat();
  49.            
  50.             dt2.setupDetect(rgbaMat, Imgproc.COLOR_RGBA2GRAY);
  51.  
  52.             //Imgproc.cvtColor(rgbaMat, grayMat, );
  53.             //Imgproc.equalizeHist(grayMat, grayMat);
  54.         }
  55.     }
  56.     // Callback
  57.     public void OnFrameMatAcquired(Mat bgraMat, Matrix4x4 projectionMatrix, Matrix4x4 cameraToWorldMatrix)
  58.     {
  59.         // Checks if it's detecting already and starts a new Thread if not.
  60.         dt. setupDetect(bgraMat, Imgproc.COLOR_BGRA2GRAY);
  61.  
  62.         //dt2.setupDetect(bgraMat);
  63.     }
  64.  
  65.     public void OnWebCamTextureToMatHelperInitialized()
  66.     {
  67.         Mat webCamTextureMat = camToStreamHelper.GetMat();
  68.         Mat grayMat = new Mat(webCamTextureMat.rows(), webCamTextureMat.cols(), CvType.CV_8UC1);
  69.  
  70.         Matrix4x4 projectionMatrix = camToStreamHelper.GetProjectionMatrix ();
  71.         dt  = new DetectThread(grayMat, projectionMatrix, m_cascadeFileName,  m_minDetectionSizeRatio, gameObject.GetComponent<RectOverlay>(), m_TestCube);
  72.  
  73.         dt2 = new DetectThread(grayMat, projectionMatrix, m_cascadeFileName2, m_minDetectionSizeRatio, gameObject.GetComponent<RectOverlay>(), m_TestCube2);
  74.  
  75.     }
  76.  
  77.  
  78.     public void OnWebCamTextureToMatHelperDisposed()
  79.     {
  80.         dt.Dispose();
  81.     }
  82.  
  83.     /// <summary>
  84.     /// Raises the web cam texture to mat helper error occurred event.
  85.     /// </summary>
  86.     /// <param name="errorCode">Error code.</param>
  87.     public void OnWebCamTextureToMatHelperErrorOccurred(HoloLensWithOpenCVForUnityExample.WebCamTextureToMatHelper.ErrorCode errorCode)
  88.     {
  89.         Debug.Log("OnWebCamTextureToMatHelperErrorOccurred " + errorCode);
  90.     }
  91.  
  92.  
  93.     /// <summary>
  94.     /// Raises the destroy event.
  95.     /// </summary>
  96.     void OnDestroy()
  97.     {
  98.         camToStreamHelper.frameMatAcquired -= OnFrameMatAcquired;
  99.         camToStreamHelper.Dispose();
  100.     }
  101.  
  102.     public class DetectThread
  103.     {
  104.  
  105.         System.Object sync = new System.Object();
  106.         private bool _IsDetecting = false;
  107.         bool IsDetecting
  108.         {
  109.             get
  110.             {
  111.                 lock (sync)
  112.                     return _IsDetecting;
  113.             }
  114.             set
  115.             {
  116.                 lock (sync)
  117.                     _IsDetecting = value;
  118.             }
  119.         }
  120.  
  121.         private CascadeClassifier   m_cascade;
  122.         private Mat                 m_grayMat;
  123.         private Matrix4x4           m_projectionMatrix;
  124.         private float               m_minDetectionSizeRatio;
  125.         private RectOverlay         m_rectOverlay;
  126.         private Mat                 m_bgraMat;
  127.         private GameObject          m_TestCube;
  128.  
  129.         RectangleTracker                m_rectangleTracker;
  130.         List<OpenCVForUnity.Rect>       m_resultObjects = new List<OpenCVForUnity.Rect>();
  131.  
  132.         public void setupDetect(Mat bgraMat, int imgproc)
  133.         {
  134.             if (!IsDetecting)
  135.             {
  136.                 IsDetecting = true;
  137.                 Imgproc.cvtColor(bgraMat, m_grayMat, imgproc);
  138.                 Imgproc.equalizeHist(m_grayMat, m_grayMat);
  139.                 m_bgraMat = bgraMat;
  140.                 #if WINDOWS_UWP
  141.                 Task t;
  142.                 t = new Task(
  143.                     async () =>
  144.                     {
  145.                         this.DetectObject();
  146.                     }
  147.                 );
  148.                 #else
  149.                 Thread t;
  150.                 t = new Thread(new ThreadStart(this.DetectObject));
  151.                 #endif
  152.                 t.Start();
  153.             }
  154.         }
  155.  
  156.  
  157.         public DetectThread(Mat grayMat, Matrix4x4 projectionMatrix, string cascadeFileName, float minDetectionSizeRatio, RectOverlay rectOverlay, GameObject testCube)
  158.         {
  159.             m_grayMat               =   grayMat;
  160.             m_projectionMatrix      =   projectionMatrix;
  161.             m_minDetectionSizeRatio =   minDetectionSizeRatio;
  162.             m_rectOverlay           =   rectOverlay;
  163.             m_TestCube              =   testCube;
  164.             m_rectangleTracker      =   new RectangleTracker();
  165.             m_cascade               =   new CascadeClassifier();
  166.  
  167.             m_cascade.load(Utils.getFilePath(cascadeFileName));
  168.         }
  169.  
  170.         private void DetectObject()
  171.         {
  172.             MatOfRect objects = new MatOfRect();
  173.             if (m_cascade != null)
  174.                 m_cascade.detectMultiScale(m_grayMat, objects, 1.1, 2, Objdetect.CASCADE_SCALE_IMAGE, // TODO: objdetect.CV_HAAR_SCALE_IMAGE
  175.                     new Size(m_grayMat.cols() * m_minDetectionSizeRatio, m_grayMat.rows() * m_minDetectionSizeRatio), new Size());
  176.  
  177.             if (!objects.empty()) {
  178.                 OpenCVForUnity.Rect[] rects;
  179.  
  180.                 m_rectangleTracker.UpdateTrackedObjects(objects.toList());
  181.                 m_rectangleTracker.GetObjects(m_resultObjects, true);
  182.                 rects = m_resultObjects.ToArray();
  183.                 DrawRects(rects, m_bgraMat.width(), m_bgraMat.height());
  184.                
  185.                 Vector3 position = new Vector3(rects[0].x, rects[0].y, 1);
  186.                 m_TestCube.transform.position = Camera.main.ScreenToWorldPoint(position);
  187.  
  188.                 m_bgraMat.Dispose();
  189.  
  190.             }
  191.  
  192.             IsDetecting = false;
  193.         }
  194.  
  195.         private void DrawRects(OpenCVForUnity.Rect[] rects, float imageWidth, float imageHeight)
  196.         {
  197.             UnityEngine.Rect[] overlayRects = new UnityEngine.Rect[rects.Length];
  198.  
  199.             for (int i = 0; i < rects.Length; i++)
  200.             {
  201.                 overlayRects[i] = new UnityEngine.Rect(rects[i].x / imageWidth
  202.                     , rects[i].y / imageHeight
  203.                     , rects[i].width / imageWidth
  204.                     , rects[i].height / imageHeight);
  205.             }
  206.             m_rectOverlay.DrawRects(overlayRects);
  207.         }
  208.  
  209.         public void Dispose()
  210.         {
  211.             if (m_grayMat != null)
  212.                 m_grayMat.Dispose();
  213.  
  214.             if (m_cascade != null)
  215.                 m_cascade.Dispose();
  216.  
  217.             m_rectangleTracker.Reset();
  218.         }
  219.  
  220.     }
  221. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement