前面几篇文章中介绍了OpenCVforUnity的使用方法,在导入了这个包之后,我们就可以在C#代码当中利用opencv的库了。
以下是在unity中编写OpenCV图像处理代码所用的一般格式:
using UnityEngine;
using UnityEngine.EventSystems;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
#if UNITY_5_3 || UNITY_5_3_OR_NEWER
using UnityEngine.SceneManagement;
#endif
using OpenCVForUnity;
namespace OpenCVForUnityExample
{
[RequireComponent(typeof(WebCamTextureToMatHelper))]
public class HandPoseEstimationExample : MonoBehaviour
{
//详细内容
}
}
首先阐述一下我们利用opencv库对手指进行识别的主要思路。利用摄像头对手部进行识别,有一个非常重要的工具:WebCamTexture,这是在unity中实现摄像头拍照和录像的必备工具。
一、启用摄像头:
该工具在unity当中的初始化过程:
//初始化WebCamTextureToMat
public void OnWebCamTextureToMatHelperInitialized ()
{
Debug.Log ("OnWebCamTextureToMatHelperInitialized");
Mat webCamTextureMat = webCamTextureToMatHelper.GetMat ();
texture = new Texture2D (webCamTextureMat.cols (), webCamTextureMat.rows (), TextureFormat.RGBA32, false);
gameObject.GetComponent<Renderer> ().material.mainTexture = texture;
gameObject.transform.localScale = new Vector3 (webCamTextureMat.cols (), webCamTextureMat.rows (), 1);
Debug.Log ("Screen.width " + Screen.width + " Screen.height " + Screen.height + " Screen.orientation " + Screen.orientation);
if (fpsMonitor != null){
fpsMonitor.Add ("width", webCamTextureMat.width ().ToString());
fpsMonitor.Add ("height", webCamTextureMat.height ().ToString());
fpsMonitor.Add ("orientation", Screen.orientation.ToString());
fpsMonitor.consoleText = "Please touch the area of the open hand.";
}
float wi