Unity/유니티 개발
[유니티] OpenCV+ Face Detection
도이(doi)
2021. 9. 24. 22:49
728x90
https://assetstore.unity.com/packages/tools/integration/opencv-plus-unity-85928
OpenCV plus Unity | 기능 통합 | Unity Asset Store
Use the OpenCV plus Unity from Paper Plane Tools on your next project. Find this integration tool & more on the Unity Asset Store.
assetstore.unity.com
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using OpenCvSharp;
public class faceDetector : MonoBehaviour
{
WebCamTexture _webCamTexture;
CascadeClassifier cascade;
OpenCvSharp.Rect MyFace;
OpenCvSharp.Rect[] faces;
void Start()
{
WebCamDevice[] devices = WebCamTexture.devices;
_webCamTexture = new WebCamTexture(devices[0].name);
_webCamTexture.Play();
cascade = new CascadeClassifier(Application.dataPath + "/OpenCV+Unity/Demo/Face_Detector/" + "haarcascade_frontalface_default.xml");
}
void Update()
{
//GetComponent<Renderer>().material.mainTexture = _webCamTexture;
Mat frame = OpenCvSharp.Unity.TextureToMat(_webCamTexture);
findNewFace(frame);
display(frame);
}
void findNewFace(Mat frame)
{
faces = cascade.DetectMultiScale(frame, 1.1, 2, HaarDetectionType.ScaleImage);
if(faces.Length >= 1)
{
Debug.Log(faces[0].Location);
Debug.Log("detected face num : "+ faces.Length);
MyFace = faces[0];
}
else
{
Debug.Log("could not reconginze the face");
}
}
void display(Mat frame)
{
if(MyFace != null && faces.Length >= 1)
{
frame.Rectangle(MyFace, new Scalar(0, 255, 0), 2);
}
Texture newtexture = OpenCvSharp.Unity.MatToTexture(frame);
GetComponent<Renderer>().material.mainTexture = newtexture;
}
}
plane 3D 게임 오브젝트를 만들고 위 스크립트를 add Component해준다.
728x90
반응형