Unity3d利用opencv保存游戏视频

脚本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是一个机器视觉库,为了精简起见,没有提供音频有关的操作。

上一篇:【JS】heatmap.js v1.0 到 v2.0,详细总结一下:)


下一篇:[译]在 64bit 环境中执行32 bit的SSIS包