赞
踩
有这样一个需求,要连接电脑的摄像头录制视频,用Aforge来做发现有的电脑不适配,于是打算用OpenCvSharp来实现
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- Control.CheckForIllegalCrossThreadCalls = false; //加载时 取消跨线程检查
- }
- private VideoCapture capture;
- private VideoWriter writer=new VideoWriter();
- private Mat frame;
- private bool _IsPlay = false;
- private void Form1_Load(object sender, EventArgs e)
- {
- FilterInfoCollection filterInfoCollection = new FilterInfoCollection(FilterCategory.VideoInputDevice);
- if(filterInfoCollection.Count==0)
- {
- MessageBox.Show("没有摄像头");
- return;
- }
- foreach (FilterInfo item in filterInfoCollection)
- {
- comboBox1.Items.Add(item.Name);
- }
- }
-
- private void button1_Click(object sender, EventArgs e)
- {
- Thread t = new Thread(_PlayFun);
- t.IsBackground = true;
- t.Name = "Camera Play Thread";
- t.Start();
- _IsPlay = true;
- }
- private void _PlayFun()
- {
- int index = this.comboBox1.SelectedIndex;
- capture = new VideoCapture(index);
- double width = capture.Get(VideoCaptureProperties.FrameWidth);
- double height = capture.Get(VideoCaptureProperties.FrameHeight);
- OpenCvSharp.Size size = new OpenCvSharp.Size(width, height);
- writer.Open("test.avi", VideoWriter.FourCC(@"XVID"), 30.0, size, true);
- if (capture.IsOpened())
- {
- while (_IsPlay)
- {
- Mat mat = new Mat();
- capture.Read(mat);
- if (mat.Empty())
- {
- break;
- }
- writer.Write(mat);
- this.pictureBox1.Invoke(new Action(() =>
- {
- pictureBox1.Image = BitmapConverter.ToBitmap(mat);
- }));
- }
- }
- else
- {
- MessageBox.Show("摄像头打开失败!");
- return;
- }
- }
- private void button2_Click(object sender, EventArgs e)
- {
- _IsPlay = false;
- if (capture.IsOpened())
- {
- capture.Dispose();
-
- }
- if (writer.IsOpened())
- {
- writer.Release();
- }
- }
-
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。