【Unity】OpenCV Plus Unity 获取Unity中摄像机并调用opencv使其灰度化实例

前言

OpenCV Plus Unity 有关的教程实在是少之又少,Opencv的有很多,但是在Unity上应用的相关教程很少,比如付费的OpenCV For Unity ,就已经很少了,目前经济有限,只能选择更加小众的OpenCV Plus Unity 国内甚至搜不到相关的概念,更别提学习教程了。真的就是纯靠自己一点点摸索尝试出来的。很不容易,不过成功之后也是成就感满满。其OpenCV的写法和C++版本的差不太多,也有些许不同之处,可以参考OpenCV for Unity 的语法格式写,并在写的过程看函数的参数说明。

1、导入OpenCV Plus Unity包

2、创建摄像机纹理

创建摄像机纹理并将其拖放到需要读取的摄像机上边

3、创建脚本

创建一个脚本:Get_cam_new,并将其附加到需处理的摄像机上边

4、代码分析

(1)引入包

using OpenCvSharp;

(2)所需变量

    //このScriptはMainCameraにアタッチしてください
    public RenderTexture renderTexture;             //mainCameraにつけるRendertexture(アタッチしてね)
    Texture2D kakunin, dstTexture;                  
    Camera mainCamera;
    GameObject hand;

(3)获取摄像机及所调用函数

    private void Update()
    {
        mainCamera = GetComponent<Camera>();
        kakunin = CreateTexture2D(renderTexture);
        Tex2D_to_Mat_show(kakunin);
    }

(4)将摄像机图像转 Texture2D 的函数定义

Texture2D CreateTexture2D(RenderTexture rt)
    {
        //Texture2Dを作成
        Texture2D texture2D = new Texture2D(rt.width, rt.height, TextureFormat.ARGB32, false, false);

        //subCameraにRenderTextureを入れる
        mainCamera.targetTexture = rt;

        //手動でカメラをレンダリングします
        mainCamera.Render();

        RenderTexture.active = rt;
        texture2D.ReadPixels(new UnityEngine.Rect(0, 0, rt.width, rt.height), 0, 0);
        texture2D.Apply();

        元に戻す別のカメラを用意してそれをRenderTexter用にすれば下のコードはいらないです。
        //mainCamera.targetTexture = null;
        //RenderTexture.active = null;
        return texture2D;
    }

(5)将 Texture2D 转 Mat 并经过 OpenCV 灰度处理输出到RawImage

    void Tex2D_to_Mat_show(Texture2D tex)
    {
        //Texture2D -> Mat
        Mat srcMat = OpenCvSharp.Unity.TextureToMat(tex);
        
        Mat grayMat = new Mat();
        Cv2.CvtColor(srcMat, grayMat, ColorConversionCodes.RGBA2GRAY);

        // Mat → Texture2D
        if (this.dstTexture == null)
        {
            this.dstTexture = new Texture2D(grayMat.Width, grayMat.Height, TextureFormat.RGBA32, false);
        }

        OpenCvSharp.Unity.MatToTexture(grayMat, this.dstTexture);

        // 表示
        GameObject.FindObjectOfType<RawImage>().texture = this.dstTexture;
    }

5、回到Unity,将渲染器纹理附加脚本上

6、创建一个cube,加上旋转脚本使其自转

旋转代码 Rotate:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
///
/// </summary>
public class Rotate : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }
    public float speed = 90f;
    // Update is called once per frame
    void Update()
    {
        this.transform.Rotate(Vector3.up * Time.deltaTime * speed);
    }
}

7、添加RawImage

      

 

8、运行测试

被灰度化后的图像上的Cube在不断旋转,成功

9、Get_cam_new源代码

using UnityEngine;
using UnityEngine.UI;
using OpenCvSharp;

public class Get_cam_new : MonoBehaviour
{

    //このScriptはMainCameraにアタッチしてください
    public RenderTexture renderTexture;             //mainCameraにつけるRendertexture(アタッチしてね)
    Texture2D kakunin, dstTexture;                  
    Camera mainCamera;
    GameObject hand;

    void Start()
    {
        //mainCamera = GetComponent<Camera>();
        //kakunin = CreateTexture2D(renderTexture);
        //Tex2D_to_Mat_show(kakunin);
    }
    private void Update()
    {
        mainCamera = GetComponent<Camera>();
        kakunin = CreateTexture2D(renderTexture);
        Tex2D_to_Mat_show(kakunin);
    }

    /// <summary>
    /// ここでTextur2Dに変換しているよ
    /// </summary>
    /// <param name="rt"></param>
    /// <returns></returns>
    Texture2D CreateTexture2D(RenderTexture rt)
    {
        //Texture2Dを作成
        Texture2D texture2D = new Texture2D(rt.width, rt.height, TextureFormat.ARGB32, false, false);

        //subCameraにRenderTextureを入れる
        mainCamera.targetTexture = rt;

        //手動でカメラをレンダリングします
        mainCamera.Render();

        RenderTexture.active = rt;
        texture2D.ReadPixels(new UnityEngine.Rect(0, 0, rt.width, rt.height), 0, 0);
        texture2D.Apply();

        元に戻す別のカメラを用意してそれをRenderTexter用にすれば下のコードはいらないです。
        //mainCamera.targetTexture = null;
        //RenderTexture.active = null;
        return texture2D;
    }

    void Tex2D_to_Mat_show(Texture2D tex)
    {
        //Texture2D -> Mat
        Mat srcMat = OpenCvSharp.Unity.TextureToMat(tex);
        
        Mat grayMat = new Mat();
        Cv2.CvtColor(srcMat, grayMat, ColorConversionCodes.RGBA2GRAY);

        // Mat → Texture2D
        if (this.dstTexture == null)
        {
            this.dstTexture = new Texture2D(grayMat.Width, grayMat.Height, TextureFormat.RGBA32, false);
        }

        OpenCvSharp.Unity.MatToTexture(grayMat, this.dstTexture);

        // 表示
        GameObject.FindObjectOfType<RawImage>().texture = this.dstTexture;
    }
}

以上

我的博客园:【Unity】OpenCV Plus Unity 获取Unity中摄像机并调用opencv使其灰度化实例 - HanaKoo - 博客园前言 OpenCV Plus Unity 有关的教程实在是少之又少,Opencv的有很多,但是在Unity上应用的相关教程很少,比如付费的OpenCV For Unity ,就已经很少了,目前经济有限https://www.cnblogs.com/HanaKoo/p/16206089.html

  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要在Unity使用OpenCVSharp来获取摄像头视频,你需要按照以下步骤进行操作: 1. 首先,下载并安装OpenCVSharp库。你可以从OpenCVSharp的GitHub页面(https://github.com/shimat/opencvsharp)下载最新版本的库。 2. 在Unity创建一个新的C#脚本,例如"CameraCapture.cs",并将其附加到一个GameObject上。 3. 在脚本导入OpenCVSharp库,你可以使用以下语句: ```csharp using OpenCvSharp; ``` 4. 在脚本编写代码来获取摄像头视频。下面是一个简单的示例: ```csharp using UnityEngine; using OpenCvSharp; public class CameraCapture : MonoBehaviour { private VideoCapture videoCapture; private Texture2D texture; void Start() { videoCapture = new VideoCapture(0); // 摄像头索引,0表示默认摄像头 if (!videoCapture.IsOpened()) { Debug.LogError("Failed to open camera!"); return; } texture = new Texture2D((int)videoCapture.FrameWidth, (int)videoCapture.FrameHeight, TextureFormat.RGBA32, false); } void Update() { Mat frame = new Mat(); videoCapture.Read(frame); if (!frame.Empty()) { // 将OpenCV的Mat转换为Unity的Texture2D texture.LoadRawTextureData(frame.Data, (int)(videoCapture.FrameWidth * videoCapture.FrameHeight * 4)); texture.Apply(); // 在Unity显示摄像头视频 GetComponent<Renderer>().material.mainTexture = texture; } } void OnDestroy() { videoCapture.Release(); texture.Dispose(); } } ``` 在上述示例,我们首先创建了一个VideoCapture对象来打开摄像头。然后,在Update方法,我们使用videoCapture.Read方法读取摄像头的每一帧,并将其转换为Unity的Texture2D对象。最后,我们将Texture2D对象应用到一个渲染器的材质上,从而在Unity显示摄像头视频。 请注意,这只是一个简单的示例,你可以根据自己的需求进行修改和扩展。 希望这能帮助到你!如果有任何问题,请随时提问。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值