您的位置:首页 > 移动开发 > Unity3D

Unity3d利用opencv保存游戏视频

2016-08-08 10:57 330 查看
脚本MyVideoWriter.cs

using UnityEngine;
using System.Collections;
using OpenCvSharp;
using OpenCvSharp.CPlusPlus;
using System.IO;
/*
author:bluebean
date:2016.8.8
all rights reserved
*/
public class MyVideoWriter : MonoBehaviour {
VideoWriter writer;
int w = 0;
int h = 0;

//VideoWriter参数
string fileName ;
FourCC fourcc = FourCC.XVID;
double fps = 50;
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(new UnityEngine.Rect(0, 0, w, h), 0, 0, 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是一个机器视觉库,为了精简起见,没有提供音频有关的操作。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: