LoginSignup
2
1

[開発] 動画再生 (WPF+OpenCV)

Last updated at Posted at 2024-03-23

動画生成

最近、手を出し始めたOpenCV。今回は動画再生してみました。
・Waitをスライダで変えて再生速度を自由に操作したり、
 表示フレームを指定すれば特定の間をループ再生も簡単に行える。
・動画再生はVLC等使えば良いが自分で作ったアプリ内に動画を入れる時には必要となる。
・このサンプルでは大量のjpgが作成されます。動画をフレーム毎にjpg保存してます。

B.jpg

using OpenCvSharp;
using OpenCvSharp.WpfExtensions;
using System.IO;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media.Imaging;

namespace openCV4 {
    public partial class MainWindow : System.Windows.Window {
        public MainWindow() {
            InitializeComponent();
        }

        private async void Window_Loaded(object sender, RoutedEventArgs e) {
            VideoCapture capture  = new VideoCapture("C:\\1.AVI");
            var img = new Mat();

            // 101番目のフレームから再生 MAXFRAME が100の場合は99が最大
            //capture.PosFrames=101;
            
            // フレームカウンタ
            int cnt=1;
            while (capture.Read(img)){

                Title=capture.Fps.ToString()+"Fps,MAXFrame"+capture.FrameCount.ToString()+"/Frame"+cnt.ToString();
                cnt++;

                var x=BitmapSourceConverter.ToBitmapSource(img);

                // 開始5秒後を表示
                // capture.PosMsec=5000;
                             
                // 保存 
                using (Stream stream = new FileStream("c:\\test"+cnt+".jpg", FileMode.Create)){
                    PngBitmapEncoder encoder = new PngBitmapEncoder();
                    encoder.Frames.Add(BitmapFrame.Create(x));
                    encoder.Save(stream);
                }
                image.Source=x;
                await Task.Delay(10);
            }
            image.Source=null;
        }
    }
}
<Window x:Class="openCV4.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:openCV4"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800" Loaded="Window_Loaded">
    <Grid>
        <Image x:Name="image"/>
    </Grid>
</Window>
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1