Unity3d利用opencv保存游戏视频

时间:2023-01-07 09:14:40

脚本MyVideoWriter.cs

using UnityEngine;
using System.Collections;
using OpenCvSharp;
using OpenCvSharp.CPlusPlus;
using System.IO;
/*author:bluebeandate:2016.8.8all rights reserved*/
public class MyVideoWriter : MonoBehaviour {
    VideoWriter writer;
    ;
    ;

    //VideoWriter参数
    string fileName ;
    FourCC fourcc = FourCC.XVID;
    ;
    Size size;
    bool isWriting = false;

    Texture2D img;
    // Use this for initialization
    void Start () {
        w = Screen.width;
        h = Screen.height;
        Size size = new Size(w, h);
        fileName = Application.streamingAssetsPath + "/output.avi";

        img = new Texture2D(w, h,TextureFormat.RGB24,false,false);

        writer = new VideoWriter();
        writer.Open(fileName, fourcc, fps, size, true);
    }

    // Update is called once per frame
    void Update () {
        if (Input.GetKey(KeyCode.S))
        {
            isWriting = !isWriting;
        }
        if (isWriting)
        {
            StartCoroutine(startWriteVideo());
        }

    }

    IEnumerator  startWriteVideo()
    {
        Debug.Log("start write");

        while (isWriting)
        {
            yield return new WaitForEndOfFrame();

            img.ReadPixels(, , w, h), , , true);//read pixels from screen to texture
            img.Apply();

            Mat tmp = new Mat(h, w, MatType.CV_8UC3, img.GetRawTextureData());
            Cv2.CvtColor(tmp, tmp, ColorConversion.BgrToRgb);
            Cv2.Flip(tmp, tmp, FlipMode.X);

            writer.Write(tmp);
        }

        Debug.Log("end write");
        yield return null;
    }

    void OnDestroy()
    {
        writer.Release();
    }
}

将脚本拖给摄像机或任何物体,按S键开始录制,再按一次结束录制,关闭程序后,可以查看保存下来的游戏视频。

注意:保存下来的只有视频而没有音频,opencv是一个机器视觉库,为了精简起见,没有提供音频有关的操作。