当前位置:   article > 正文

C#winform中使用OpenCvSharp录制视频,学不会不要钱_c# opencv录像

c# opencv录像

有这样一个需求,要连接电脑的摄像头录制视频,用Aforge来做发现有的电脑不适配,于是打算用OpenCvSharp来实现

第一步:引用OpenCvSharp所需要的包(注意包的版本最好保持一致)

  1. OpenCvSharp4
  2. OpenCvSharp4.runtime.win
  3. AForge.Video.DirectShow   (这个是用来获取电脑摄像头数量)

第二步:话不多说直接上代码

 

  1. public partial class Form1 : Form
  2. {
  3. public Form1()
  4. {
  5. InitializeComponent();
  6. Control.CheckForIllegalCrossThreadCalls = false; //加载时 取消跨线程检查
  7. }
  8. private VideoCapture capture;
  9. private VideoWriter writer=new VideoWriter();
  10. private Mat frame;
  11. private bool _IsPlay = false;
  12. private void Form1_Load(object sender, EventArgs e)
  13. {
  14. FilterInfoCollection filterInfoCollection = new FilterInfoCollection(FilterCategory.VideoInputDevice);
  15. if(filterInfoCollection.Count==0)
  16. {
  17. MessageBox.Show("没有摄像头");
  18. return;
  19. }
  20. foreach (FilterInfo item in filterInfoCollection)
  21. {
  22. comboBox1.Items.Add(item.Name);
  23. }
  24. }
  25. private void button1_Click(object sender, EventArgs e)
  26. {
  27. Thread t = new Thread(_PlayFun);
  28. t.IsBackground = true;
  29. t.Name = "Camera Play Thread";
  30. t.Start();
  31. _IsPlay = true;
  32. }
  33. private void _PlayFun()
  34. {
  35. int index = this.comboBox1.SelectedIndex;
  36. capture = new VideoCapture(index);
  37. double width = capture.Get(VideoCaptureProperties.FrameWidth);
  38. double height = capture.Get(VideoCaptureProperties.FrameHeight);
  39. OpenCvSharp.Size size = new OpenCvSharp.Size(width, height);
  40. writer.Open("test.avi", VideoWriter.FourCC(@"XVID"), 30.0, size, true);
  41. if (capture.IsOpened())
  42. {
  43. while (_IsPlay)
  44. {
  45. Mat mat = new Mat();
  46. capture.Read(mat);
  47. if (mat.Empty())
  48. {
  49. break;
  50. }
  51. writer.Write(mat);
  52. this.pictureBox1.Invoke(new Action(() =>
  53. {
  54. pictureBox1.Image = BitmapConverter.ToBitmap(mat);
  55. }));
  56. }
  57. }
  58. else
  59. {
  60. MessageBox.Show("摄像头打开失败!");
  61. return;
  62. }
  63. }
  64. private void button2_Click(object sender, EventArgs e)
  65. {
  66. _IsPlay = false;
  67. if (capture.IsOpened())
  68. {
  69. capture.Dispose();
  70. }
  71. if (writer.IsOpened())
  72. {
  73. writer.Release();
  74. }
  75. }
  76. }

当然,还需要用到2个Button(开始录制,结束录制)和一个pictureBox(展示图片)和一个combox(显示摄像头列表)

全网最详细代码,喜欢的话给博主点点关注!!!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/148431?site
推荐阅读
相关标签
  

闽ICP备14008679号