FaceDetectionWebCamTextureExample.cs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. using UnityEngine;
  2. using UnityEngine.SceneManagement;
  3. using System;
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using OpenCVForUnity.CoreModule;
  7. using OpenCVForUnity.ObjdetectModule;
  8. using OpenCVForUnity.ImgprocModule;
  9. using OpenCVForUnity.UnityUtils;
  10. using OpenCVForUnity.UnityUtils.Helper;
  11. namespace OpenCVForUnityExample
  12. {
  13. /// <summary>
  14. /// Face Detection WebCamTexture Example
  15. /// An example of detecting human face in a image of WebCamTexture using the CascadeClassifier class.
  16. /// http://docs.opencv.org/3.2.0/db/d28/tutorial_cascade_classifier.html
  17. /// </summary>
  18. [RequireComponent (typeof(WebCamTextureToMatHelper))]
  19. public class FaceDetectionWebCamTextureExample : MonoBehaviour
  20. {
  21. /// <summary>
  22. /// The gray mat.
  23. /// </summary>
  24. Mat grayMat;
  25. /// <summary>
  26. /// The texture.
  27. /// </summary>
  28. Texture2D texture;
  29. /// <summary>
  30. /// The cascade.
  31. /// </summary>
  32. CascadeClassifier cascade;
  33. /// <summary>
  34. /// The faces.
  35. /// </summary>
  36. MatOfRect faces;
  37. /// <summary>
  38. /// The webcam texture to mat helper.
  39. /// </summary>
  40. WebCamTextureToMatHelper webCamTextureToMatHelper;
  41. /// <summary>
  42. /// The FPS monitor.
  43. /// </summary>
  44. FpsMonitor fpsMonitor;
  45. #if UNITY_WEBGL && !UNITY_EDITOR
  46. IEnumerator getFilePath_Coroutine;
  47. #endif
  48. // Use this for initialization
  49. void Start ()
  50. {
  51. fpsMonitor = GetComponent<FpsMonitor> ();
  52. webCamTextureToMatHelper = gameObject.GetComponent<WebCamTextureToMatHelper> ();
  53. #if UNITY_WEBGL && !UNITY_EDITOR
  54. getFilePath_Coroutine = Utils.getFilePathAsync ("lbpcascade_frontalface.xml", (result) => {
  55. getFilePath_Coroutine = null;
  56. cascade = new CascadeClassifier ();
  57. cascade.load (result);
  58. if (cascade.empty ()) {
  59. Debug.LogError ("cascade file is not loaded. Please copy from “OpenCVForUnity/StreamingAssets/” to “Assets/StreamingAssets/” folder. ");
  60. }
  61. webCamTextureToMatHelper.Initialize ();
  62. });
  63. StartCoroutine (getFilePath_Coroutine);
  64. #else
  65. cascade = new CascadeClassifier ();
  66. cascade.load (Utils.getFilePath ("lbpcascade_frontalface.xml"));
  67. // cascade.load (Utils.getFilePath ("haarcascade_frontalface_alt.xml"));
  68. #if !UNITY_WSA_10_0
  69. if (cascade.empty ()) {
  70. Debug.LogError ("cascade file is not loaded. Please copy from “OpenCVForUnity/StreamingAssets/” to “Assets/StreamingAssets/” folder. ");
  71. }
  72. #endif
  73. #if UNITY_ANDROID && !UNITY_EDITOR
  74. // Avoids the front camera low light issue that occurs in only some Android devices (e.g. Google Pixel, Pixel2).
  75. webCamTextureToMatHelper.avoidAndroidFrontCameraLowLightIssue = true;
  76. #endif
  77. webCamTextureToMatHelper.Initialize ();
  78. #endif
  79. }
  80. /// <summary>
  81. /// Raises the web cam texture to mat helper initialized event.
  82. /// </summary>
  83. public void OnWebCamTextureToMatHelperInitialized ()
  84. {
  85. Debug.Log ("OnWebCamTextureToMatHelperInitialized");
  86. Mat webCamTextureMat = webCamTextureToMatHelper.GetMat ();
  87. texture = new Texture2D (webCamTextureMat.cols (), webCamTextureMat.rows (), TextureFormat.RGBA32, false);
  88. gameObject.GetComponent<Renderer> ().material.mainTexture = texture;
  89. gameObject.transform.localScale = new Vector3 (webCamTextureMat.cols (), webCamTextureMat.rows (), 1);
  90. Debug.Log ("Screen.width " + Screen.width + " Screen.height " + Screen.height + " Screen.orientation " + Screen.orientation);
  91. if (fpsMonitor != null) {
  92. fpsMonitor.Add ("width", webCamTextureMat.width ().ToString ());
  93. fpsMonitor.Add ("height", webCamTextureMat.height ().ToString ());
  94. fpsMonitor.Add ("orientation", Screen.orientation.ToString ());
  95. }
  96. float width = webCamTextureMat.width ();
  97. float height = webCamTextureMat.height ();
  98. float widthScale = (float)Screen.width / width;
  99. float heightScale = (float)Screen.height / height;
  100. if (widthScale < heightScale) {
  101. Camera.main.orthographicSize = (width * (float)Screen.height / (float)Screen.width) / 2;
  102. } else {
  103. Camera.main.orthographicSize = height / 2;
  104. }
  105. grayMat = new Mat (webCamTextureMat.rows (), webCamTextureMat.cols (), CvType.CV_8UC1);
  106. faces = new MatOfRect ();
  107. }
  108. /// <summary>
  109. /// Raises the web cam texture to mat helper disposed event.
  110. /// </summary>
  111. public void OnWebCamTextureToMatHelperDisposed ()
  112. {
  113. Debug.Log ("OnWebCamTextureToMatHelperDisposed");
  114. if (grayMat != null)
  115. grayMat.Dispose ();
  116. if (texture != null) {
  117. Texture2D.Destroy (texture);
  118. texture = null;
  119. }
  120. if (faces != null)
  121. faces.Dispose ();
  122. }
  123. /// <summary>
  124. /// Raises the web cam texture to mat helper error occurred event.
  125. /// </summary>
  126. /// <param name="errorCode">Error code.</param>
  127. public void OnWebCamTextureToMatHelperErrorOccurred (WebCamTextureToMatHelper.ErrorCode errorCode)
  128. {
  129. Debug.Log ("OnWebCamTextureToMatHelperErrorOccurred " + errorCode);
  130. }
  131. // Update is called once per frame
  132. void Update ()
  133. {
  134. if (webCamTextureToMatHelper.IsPlaying () && webCamTextureToMatHelper.DidUpdateThisFrame ()) {
  135. Mat rgbaMat = webCamTextureToMatHelper.GetMat ();
  136. Imgproc.cvtColor (rgbaMat, grayMat, Imgproc.COLOR_RGBA2GRAY);
  137. Imgproc.equalizeHist (grayMat, grayMat);
  138. if (cascade != null)
  139. cascade.detectMultiScale (grayMat, faces, 1.1, 2, 2, // TODO: objdetect.CV_HAAR_SCALE_IMAGE
  140. new Size (grayMat.cols () * 0.2, grayMat.rows () * 0.2), new Size ());
  141. OpenCVForUnity.CoreModule.Rect[] rects = faces.toArray ();
  142. for (int i = 0; i < rects.Length; i++) {
  143. // Debug.Log ("detect faces " + rects [i]);
  144. Imgproc.rectangle (rgbaMat, new Point (rects [i].x, rects [i].y), new Point (rects [i].x + rects [i].width, rects [i].y + rects [i].height), new Scalar (255, 0, 0, 255), 2);
  145. }
  146. // Imgproc.putText (rgbaMat, "W:" + rgbaMat.width () + " H:" + rgbaMat.height () + " SO:" + Screen.orientation, new Point (5, rgbaMat.rows () - 10), Imgproc.FONT_HERSHEY_SIMPLEX, 1.0, new Scalar (255, 255, 255, 255), 2, Imgproc.LINE_AA, false);
  147. Utils.fastMatToTexture2D (rgbaMat, texture);
  148. }
  149. }
  150. /// <summary>
  151. /// Raises the destroy event.
  152. /// </summary>
  153. void OnDestroy ()
  154. {
  155. webCamTextureToMatHelper.Dispose ();
  156. if (cascade != null)
  157. cascade.Dispose ();
  158. #if UNITY_WEBGL && !UNITY_EDITOR
  159. if (getFilePath_Coroutine != null) {
  160. StopCoroutine (getFilePath_Coroutine);
  161. ((IDisposable)getFilePath_Coroutine).Dispose ();
  162. }
  163. #endif
  164. }
  165. /// <summary>
  166. /// Raises the back button click event.
  167. /// </summary>
  168. public void OnBackButtonClick ()
  169. {
  170. SceneManager.LoadScene ("OpenCVForUnityExample");
  171. }
  172. /// <summary>
  173. /// Raises the play button click event.
  174. /// </summary>
  175. public void OnPlayButtonClick ()
  176. {
  177. webCamTextureToMatHelper.Play ();
  178. }
  179. /// <summary>
  180. /// Raises the pause button click event.
  181. /// </summary>
  182. public void OnPauseButtonClick ()
  183. {
  184. webCamTextureToMatHelper.Pause ();
  185. }
  186. /// <summary>
  187. /// Raises the stop button click event.
  188. /// </summary>
  189. public void OnStopButtonClick ()
  190. {
  191. webCamTextureToMatHelper.Stop ();
  192. }
  193. /// <summary>
  194. /// Raises the change camera button click event.
  195. /// </summary>
  196. public void OnChangeCameraButtonClick ()
  197. {
  198. webCamTextureToMatHelper.requestedIsFrontFacing = !webCamTextureToMatHelper.IsFrontFacing ();
  199. }
  200. }
  201. }