機械学習基礎理論独習

誤りがあればご指摘いただけると幸いです。数式が整うまで少し時間かかります。リンクフリーです。

勉強ログです。リンクフリーです
目次へ戻る

【Form/C#】OpenCvSharpを使って、bitmapから動画を作成する

概要

C#で作成したbitmapから動画を作成します。
簡単なので、ソースのみです。

プログラム

using OpenCvSharp;
using OpenCvSharp.Extensions;

namespace SampleFormOpenCvSharp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // create video with opencv

            int width = 1280;
            int height = 720;
            double fps = 60;
            int radius = height / 2;

            // video writer initialize
            VideoWriter vw = new(@"C:\temp\aa.mp4", FourCC.H264, fps, new OpenCvSharp.Size(width, height));
            bool check = vw.IsOpened();
            if (!check)
            {
                MessageBox.Show("video writer is not opened.");
                return;
            }

            Bitmap bm = new(width, height);
            Graphics g = Graphics.FromImage(bm);

            // create movie
            while (true)
            {              
                g.Clear(Color.White);
                g.FillEllipse(Brushes.LightBlue, 0, 0, radius * 2, radius * 2);
                
                // create frame
                Mat mat = bm.ToMat();
                vw.Write(mat);
                mat.Dispose();
                
                if (--radius < 0)
                {
                    break;
                }
            }; 
            vw.Release();
            vw.Dispose();
            bm.Dispose();
            g.Dispose();

            MessageBox.Show("video created.");
        }
    }
}
目次へ戻る