树莓派简单摄像头录像并保存视频文件

Posted songxingzhu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了树莓派简单摄像头录像并保存视频文件相关的知识,希望对你有一定的参考价值。

一、简介

  本文讲使用OpenCV,不使用FFMPEG的方法进行保存视频。

二、代码

  1、引用

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="OpenCvSharp3-AnyCPU" version="3.4.1.20180830" targetFramework="net47" />
</packages>

 

  2、代码

using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace OpenCVDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var cameraIndex = 0;
            if (args != null && args.Length > 0)
            {
                int.TryParse(args[0], out cameraIndex);
            }
            Console.WriteLine("Begin At Cam Index " + cameraIndex + " ...");
            var path = Path.Combine(AppContext.BaseDirectory, "imgs");
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);
            int count = 0;
            var videoSize = new Size(640, 480);
            var timePoint = new Point(0, 15);
            VideoWriter videoWriter = new VideoWriter(Path.Combine(path, "Video.mp4"), FourCC.XVID, 30,
                   videoSize, true);
            using (var camera = VideoCapture.FromCamera(CaptureDevice.Any))
            {
                //VideoWriter videoWriter = new VideoWriter(Path.Combine(path, "Video.mp4"), FourCC.Prompt, 30,
                //new Size(camera.Get(CaptureProperty.FrameWidth), camera.Get(CaptureProperty.FrameHeight)));
                while (true)
                {
                    var mat = camera.RetrieveMat();
                    if (mat.Empty()) { Thread.Sleep(100); continue; }
                    if (++count > 30 * 30) break;
                    Console.WriteLine("save .. " + count);
                    //mat.PutText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), new Point(10, 10), HersheyFonts.HersheyPlain, 20, Scalar.Yellow, 2);
                    Cv2.PutText(mat, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " GTM+8", timePoint, HersheyFonts.HersheyPlain, 1, Scalar.Red, 1);
                    //OpenCvSharp.Cv2.ImShow("myWin", mat);
                    //if (Cv2.WaitKey(40) == 13)
                    //{
                    //    break;
                    //}
                    Thread.Sleep(50);
                    var newmat = mat.Resize(videoSize);
                    videoWriter.Write(newmat);
                    mat.Dispose();
                    newmat.Dispose();
                }
                videoWriter.Dispose();
                //GC.Collect();
            }
            Console.WriteLine("Finish.");
        }
    }
}

 

以上是关于树莓派简单摄像头录像并保存视频文件的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 树莓派连接摄像头拍照

使用opencv去操作树莓派摄像头保存图片和视频

智能家居代码构建编写简单工厂模式树莓派摄像头视频监控功能实现

树莓派 摄像头

OpenCV操作不了树莓派原装摄像头(picam)解决方法

树莓派使用Python使用PiCamera录制视频