很久没更新Opencv for Unity的系列了,最近刚好项目要用到,所以碰巧就抽时间来写一篇关于opencv for unity的,今天来简单介绍一下Opencv for unity这个插件中的一个非常有用的帮助类WebCamTextureToMatHelper。
你通过他的名字就能知道他是帮助你来获取Webcam的画面,并转换成我们Opencv中所用的Mat类,有了Mat类那不就可以通过Opencv的方法库来进行各种处理啦。
废话不多说,下面我们进入正题:
- 添加脚本
第一步就是把这个帮助类,添加进场景中,因为他继承自Mono,所以直接可以选择场景中的任意物体进行添加,可以看到他公有很多变量可以进行设置,建议就保持默认咯。

- 编写脚本
下面写自己的脚本,随便建立一个脚本,比如叫WebCamTest之类的,那么下面如何打开摄像头呢,当然我们需要我们的脚本中,首先获取到这个帮助类WebCamTextureToMatHelper。

要声明这个类,也别忘记Opencv的命名空间:

然后你只要调用这个实例的初始化方法,这个类其实已经在帮你初始化获取摄像头的画面了。

然而你看到这里会问,我怎么知道这个帮助类有没有成功的获取到摄像头呢?别人既然是一个完善的帮助类肯定也想到啦,你其实看这个帮助类的面板,他提供了三个回调事件 OnInitialized(初始化成功时), OnDisposed(释放时),OnErrorOcurred(错误发生时)。

你可以拖对应的方法到上面,也可以通过自己手写:
我通过webcamTextureHelper在初始化时注册了一个回调方法

而这个回调方法就是为获取画面做准备:
首先声明一个RawImage 和 Texture2D的变量;

然后通过帮助类GetMat()方法,这个方法是返回画面的当前帧,他的类型是Mat,这个Opencv的容器相信大家都很熟悉了。

我们获得了Mat变量,就说明我们可以决定了Texture2D类型的webTex的摄像头贴图的大小,把这个贴图给初始化好,并把RawImage的Texture指定为这张贴图。(别忘记在你的Unity场景里建立一个RawImage并把他赋值给脚本里的RawImage,不然会报空)

最后就是事实把获取到的Mat更新给Texture就能事实获取到了摄像头的画面了,这个方法呢,我们放到Update()函数中执行。
为了减少消耗,所以我们做了通过WebCamTextureHelper做了两个判断,如果是在运行以及这帧有画面更新的时候,才去通过帮助类GetMat(),并把Mat转换为Texture;

然后你在编辑里点运行,看到摄像头的画面,大功告成,当然你通过获取到了摄像头的Mat,你可以进行各种处理后再转成Texture,赋值给摄像头,这就是我们所说的各种特效啦,你可以举一反三。

最后贴上我的完整脚本
using OpenCVForUnity.CoreModule;
using OpenCVForUnity.UnityUtils.Helper;
using UnityEngine;
using UnityEngine.UI;
public class WebCamTest : MonoBehaviour
{
public WebCamTextureToMatHelper webCamTextureHelper;
private RawImage webImg;
private Texture2D webTex;
// Start is called before the first frame update
void Start()
{
webImg = this.GetComponent<RawImage>();
webCamTextureHelper = this.GetComponent<WebCamTextureToMatHelper>();
webCamTextureHelper.onInitialized.AddListener(OnWebCamInitialize);
webCamTextureHelper.Initialize();
}
private void OnWebCamInitialize()
{
Debug.Log("初始化成功了了");
Mat mat = webCamTextureHelper.GetMat();
webTex = new Texture2D(mat.cols(), mat.rows(), TextureFormat.RGBA32, false);
webImg.texture = webTex;
}
// Update is called once per frame
void Update()
{
if (webCamTextureHelper.IsPlaying() && webCamTextureHelper.DidUpdateThisFrame())
{
Mat rgbaMat = webCamTextureHelper.GetMat();
OpenCVForUnity.UnityUtils.Utils.fastMatToTexture2D(rgbaMat, webTex);
}
}
}
网友评论