1
0

FacialRecognitionHandler.cs 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. // using OpenCVSharp;
  6. using OpenCVForUnity;
  7. using OpenCVForUnity.CoreModule;
  8. using OpenCVForUnity.ImgprocModule;
  9. using OpenCVForUnity.UnityUtils;
  10. using OpenCVForUnity.ObjdetectModule;
  11. /// <summary>
  12. /// 面部识别
  13. /// </summary>
  14. public class FacialRecognitionHandler : MonoBehaviour
  15. {
  16. private Mat gray; // 灰度图,方便识别
  17. private Mat rotatedNewMat;
  18. private MatOfRect faceRect; // 识别到的人脸的区域
  19. private CascadeClassifier classifier; // 人脸识别分类器
  20. private string cascadePath = Application.streamingAssetsPath + "/haarcascade_frontalface_alt2.xml";
  21. [SerializeField] private float timer = 0;
  22. // ==================================================
  23. private void Start() => Init();
  24. private void OnDestroy() => Dispose();
  25. // ==================================================
  26. private void Init()
  27. {
  28. // LogAllWebCam();
  29. gray = new Mat(); // 初始化Mat
  30. faceRect = new MatOfRect(); // 初始化识别到的人脸的区域
  31. classifier = new CascadeClassifier(cascadePath); // 初始化人脸识别分类器
  32. previewMat = new Mat();
  33. resultPreviewTexture2D = new Texture2D(440, 440, TextureFormat.RGBA32, false);
  34. return;
  35. }
  36. // ==================================================
  37. #region 资源释放
  38. private void Dispose()
  39. {
  40. if (rotatedNewMat != null)
  41. {
  42. rotatedNewMat.Dispose();
  43. rotatedNewMat = null;
  44. }
  45. if (previewMat != null)
  46. {
  47. previewMat.Dispose();
  48. previewMat = null;
  49. }
  50. if (resultPreviewTexture2D != null)
  51. {
  52. Destroy(resultPreviewTexture2D);
  53. resultPreviewTexture2D = null;
  54. }
  55. return;
  56. }
  57. #endregion
  58. // ==================================================
  59. #region 面部识别
  60. public void DetectFace(Mat rgbaMat)
  61. {
  62. // rotatedNewMat = MatRotate(rgbaMat.clone()); // 旋转原数据
  63. rotatedNewMat = rgbaMat.clone(); // 原数据
  64. Imgproc.cvtColor(rotatedNewMat, gray, Imgproc.COLOR_RGBA2GRAY); // 将获取到的摄像头画面转化为灰度图并赋值给gray
  65. // mat/面部矩形向量组/识别精度越高越快越不准/面部识别次数2次以上算识别/?性能优化/最小检测尺寸/最大检测尺寸
  66. // classifier.detectMultiScale(gray, faceRect, 1.1d, 2, 2, new Size(20, 20), new Size()); // 检测gray中的人脸
  67. classifier.detectMultiScale(gray, faceRect, 1.1d, 3, 2, new Size(20, 20), new Size());
  68. OpenCVForUnity.CoreModule.Rect[] rects = faceRect.toArray();
  69. if (rects.Length > 0)
  70. {
  71. for (int i = 0; i < rects.Length; i++)
  72. {
  73. Imgproc.rectangle(rotatedNewMat, new Point(rects[i].x, rects[i].y), new Point(rects[i].x + rects[i].width, rects[i].y + rects[i].height), new Scalar(0, 255, 0, 255), 2); //在原本的画面中画框,框出人脸额位置,其中rects[i].x和rects[i].y为框的左上角的顶点,rects[i].width、rects[i].height即为框的宽和高
  74. }
  75. timer += Time.deltaTime;
  76. if (timer > .2f)
  77. {
  78. Debug.Log("检测到面部");
  79. }
  80. }
  81. else
  82. {
  83. // if (timer > 0) // 缓慢减少检测值
  84. // {
  85. // timer -= Time.deltaTime / 2;
  86. // if (timer < 0)
  87. // {
  88. // timer = 0;
  89. // }
  90. // }
  91. timer = 0;
  92. }
  93. // 深复制识别、画框数据并显示
  94. UpdateResultPreview(rotatedNewMat);
  95. return;
  96. }
  97. #endregion
  98. // ==================================================
  99. #region 预览画面
  100. [SerializeField] private Image resultPreviewImage;
  101. private Mat previewMat;
  102. private Texture2D resultPreviewTexture2D;
  103. private void UpdateResultPreview(Mat value)
  104. {
  105. if (resultPreviewImage == null)
  106. {
  107. return;
  108. }
  109. previewMat = value.clone();
  110. Utils.matToTexture2D(previewMat, resultPreviewTexture2D);
  111. resultPreviewImage.sprite = Sprite.Create(resultPreviewTexture2D, new UnityEngine.Rect(0, 0, 440, 440), Vector2.zero);
  112. return;
  113. }
  114. #endregion
  115. // ==================================================
  116. /// <summary>
  117. /// Mat旋转方法
  118. /// </summary>
  119. /// <param name="orginalMat"></param>
  120. /// <returns></returns>
  121. private Mat MatRotate(Mat orginalMat)
  122. {
  123. Mat rotatedMat = new Mat(orginalMat.height(), orginalMat.width(), CvType.CV_8UC4, new Scalar(0, 0, 0, 255)); // DEBUG:宽高可能相反
  124. // mat旋转
  125. Point center = new Point(orginalMat.cols() / 2f, orginalMat.rows() / 2f);
  126. Mat mat = Imgproc.getRotationMatrix2D(center, 90, 1);
  127. Imgproc.warpAffine(orginalMat, rotatedMat, mat, orginalMat.size());
  128. return rotatedMat;
  129. }
  130. /// <summary>
  131. /// 预览有多少相机
  132. /// </summary>
  133. private void LogAllWebCam()
  134. {
  135. Debug.Log($"Found {WebCamTexture.devices.Length} device...<color=green>[OK]</color>");
  136. foreach (WebCamDevice webcamDevice in WebCamTexture.devices)
  137. {
  138. Debug.Log($"{webcamDevice.name}...<color=green>[OK]</color>");
  139. }
  140. return;
  141. }
  142. }