C# 利用AForge进行摄像头信息采集

概述

AForge.NET是一个专门为开发者和研究者基于C#框架设计的,提供了不同的类库和关于类库的资源,还有很多应用程序例子,包括计算机视觉与人工智能,图像处理,神经网络,遗传算法,机器学习,机器人等领域。本文主要讲解利用AForge进行图像采集的相关内容【包括拍照,视频录制】,仅供学习分享使用。

AForge.Net相关类库介绍

  • AForge.dll 是框架的核心基础类库,为其他类库提供服务。
  • AForge.Controls.dll 包含AForge.Net的UI控件,主要用于页面显示。
  • AForge.Imaging.dll 主要是框架中用于图像处理的类库,主要负责图像的处理
  • AForge.Video.dll 主要是框架中对视频处理的类库。
  • AForge.Video.DirectShow.dll 主要是通过DirectShow接口访问视频资源的类库。
  • AForge.Video.FFMPEG.dll 是一个还未正式发布的类库,通过FFMPEG类库对视频进行读写。

通过NuGet管理器引入AForge类库

项目名称右键-->管理NuGet程序包,打卡NuGet包管理器  如下所示:

示例效果图

本示例主要包括打开,关闭摄像头,拍照,连续拍照,开始录制视频,暂停录制视频,停止录视频,退出等功能。

如下所示:左侧为摄像头投影区域,右侧为图像控件,显示拍照所得的图片

核心代码

获取视频设备列表以及设备对应的分辨率

 1 /// <summary>
 2         /// 页面加载摄像头设备
 3         /// </summary>
 4         /// <param name="sender"></param>
 5         /// <param name="e"></param>
 6         private void FrmMain_Load(object sender, EventArgs e)
 7         {
 8             try
 9             {
10                 this.lblTime.Text = "";
11                 // 枚举所有视频输入设备
12                 videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
13                 if (videoDevices.Count == 0)
14                 {
15                     lblStatus.Text = "No local capture devices";
16                 }
17                 foreach (FilterInfo device in videoDevices)
18                 {
19                     int i = 1;
20                     cmbDevices.Items.Add(device.Name);
21                     lblStatus.Text = ("摄像头" + i + "初始化完毕..." + "
");
22                     i++;
23                 }
24                 cmbDevices.SelectedIndex = 0;
25             }
26             catch (ApplicationException)
27             {
28                 this.lblStatus.Text = "No local capture devices";
29                 videoDevices = null;
30             }
31         }
32 
33         private void cmbDevices_SelectedIndexChanged(object sender, EventArgs e)
34         {
35             this.cmbResolution.Items.Clear();
36             videoSource = new VideoCaptureDevice(videoDevices[cmbDevices.SelectedIndex].MonikerString);
37             foreach(var cap in videoSource.VideoCapabilities) {
38                 this.cmbResolution.Items.Add(string.Format("({0},{1})",cap.FrameSize.Width,cap.FrameSize.Height));
39             }
40             if (this.cmbResolution.Items.Count > 0)
41             {
42                 this.cmbResolution.SelectedIndex = 0;
43             }
44         }
View Code

打开视频设备和关闭视频设备

 1    /// <summary>
 2         /// 设备打开
 3         /// </summary>
 4         /// <param name="sender"></param>
 5         /// <param name="e"></param>
 6         private void btnOpen_Click(object sender, EventArgs e)
 7         {
 8             int index = this.cmbResolution.SelectedIndex;
 9             videoSource = new VideoCaptureDevice(videoDevices[cmbDevices.SelectedIndex].MonikerString);
10             videoSource.VideoResolution = videoSource.VideoCapabilities[index]; 
11             this.vsPlayer.VideoSource = videoSource;
12             //设置对应的事件
13             videoSource.NewFrame += new NewFrameEventHandler(videoSource_NewFrame);
14             this.vsPlayer.Start();
15         }
16 
17         /// <summary>
18         /// 产生新帧的触发事件
19         /// </summary>
20         /// <param name="sender"></param>
21         /// <param name="eventArgs"></param>
22         public void videoSource_NewFrame(object sender, NewFrameEventArgs eventArgs)
23         {
24             lock (objLock)
25             {
26                 Bitmap bmp = null;
27                 if (isMultiPhoto)
28                 {
29                     bmp = (System.Drawing.Bitmap)eventArgs.Frame.Clone();
30                     string imgFolder = Common.GetImagePath();
31                     string picName = string.Format("{0}\{1}.jpg", imgFolder, DateTime.Now.ToString("yyyyMMddHHmmss"));
32                     Common.SaveImage(picName, bmp);
33                 }
34                 //Write Videos
35                 if (isRecordVideo)
36                 {
37                     bmp = (System.Drawing.Bitmap)eventArgs.Frame.Clone();
38                     videoWriter.WriteVideoFrame(bmp);
39                 }
40             }
41         }
42 
43         /// <summary>
44         /// 设备关闭
45         /// </summary>
46         /// <param name="sender"></param>
47         /// <param name="e"></param>
48         private void btnClose_Click(object sender, EventArgs e)
49         {
50             this.vsPlayer.SignalToStop();
51             this.vsPlayer.WaitForStop();
52         }
View Code

拍照

 1 /// <summary>
 2         /// 拍照
 3         /// </summary>
 4         /// <param name="sender"></param>
 5         /// <param name="e"></param>
 6         private void btnCapture_Click(object sender, EventArgs e)
 7         {
 8             try
 9             {
10                 if (this.vsPlayer.IsRunning)
11                 {
12                     Bitmap bitMap = this.vsPlayer.GetCurrentVideoFrame();
13                     this.pbImage.Image = bitMap;
14                     //设置图片相对控件的大小
15                     this.pbImage.SizeMode = PictureBoxSizeMode.StretchImage;
16                 }
17             }
18             catch (Exception ex)
19             {
20                 MessageBox.Show("摄像头异常:" + ex.Message);
21             }
22         }
View Code

连拍功能

连拍主要是同时视频控件的一个帧触发事件,在事件中对图像进行保存,达到连拍的效果,如下所示:

1  //设置对应的事件
2 videoSource.NewFrame += new NewFrameEventHandler(videoSource_NewFrame);

视频录制

视频录制,是采用VideoFileWriter对获取到的每一帧进行写入到视频文件中,如下所示:

 1  /// <summary>
 2         /// 开始录视频
 3         /// </summary>
 4         /// <param name="sender"></param>
 5         /// <param name="e"></param>
 6         private void btnStartVideo_Click(object sender, EventArgs e)
 7         {
 8             try
 9             {
10                 //创建一个视频文件
11                 string vdoPath = Common.GetVideoPath();
12                 string vdoName = string.Format("{0}\{1}.avi", vdoPath, DateTime.Now.ToString("yyyyMMdd HH-mm-ss"));
13                 
14                 this.timer1.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件;
15                 this.lblStatus.Text="录制中...
";
16                 tickNum = 0;
17                 videoWriter = new VideoFileWriter();
18                 if (this.vsPlayer.IsRunning)
19                 {
20                     videoWriter.Open(vdoName, vdoWidth, vdoHeight, frameRate, VideoCodec.MPEG4);
21                     isRecordVideo = true;
22                 }
23                 else
24                 {
25                     MessageBox.Show("没有视频源输入,无法录制视频。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
26                 }
27             }
28             catch (Exception ex)
29             {
30                 MessageBox.Show("摄像头异常:" + ex.Message);
31             }
32         }
33 
34         /// <summary>
35         /// 停止录视频
36         /// </summary>
37         /// <param name="sender"></param>
38         /// <param name="e"></param>
39         private void btnStopVideo_Click(object sender, EventArgs e)
40         {
41             this.isRecordVideo = false;
42             this.videoWriter.Close();
43             this.timer1.Enabled = false;
44             tickNum = 0;
45             this.lblStatus.Text="录制停止!
";
46         }
47 
48         /// <summary>
49         /// 定时器
50         /// </summary>
51         /// <param name="sender"></param>
52         /// <param name="e"></param>
53         private void timer1_Tick(object sender, EventArgs e)
54         {
55             tickNum++;
56             int temp = tickNum;
57             string tick = Common.GetTimeSpan(temp);
58             this.lblTime.Text = tick;
59         }
60 
61         /// <summary>
62         /// 暂停录制
63         /// </summary>
64         /// <param name="sender"></param>
65         /// <param name="e"></param>
66         private void btnPauseVideo_Click(object sender, EventArgs e)
67         {
68             if (this.btnPauseVideo.Text.Trim() == "暂停录像")
69             {
70                 isRecordVideo = false;
71                 this.btnPauseVideo.Text = "恢复录像";
72                 this.timer1.Enabled = false;    //暂停计时
73                 return;
74             }
75             if (this.btnPauseVideo.Text.Trim() == "恢复录像")
76             {
77                 isRecordVideo = true;
78                 this.btnPauseVideo.Text = "暂停录像";
79                 this.timer1.Enabled = true;     //恢复计时
80             }
81         }
View Code

注意事项

1. 由于视频录制是采用FFMPEG类库进行处理,所以除了需要AForge.Video.FFMPEG.dll以外,还需要FFMPEG类库(C++),位于【AForge.NET Framework-2.2.5Externalsffmpegin】目录下,copy到应用程序目下即可,如下图所示:

2. 由于AForge.Video.FFMPEG.dll类库只支持.NetFrameWork2.0,所以需要采用混合模式,App.config配置如下:

1 <?xml version="1.0" encoding="utf-8"?>
2 <configuration>
3     <startup  useLegacyV2RuntimeActivationPolicy="true"> 
4     <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/></startup>
5     <supportedRuntime version="v2.0.50727"/>
6 </configuration>

3. 由于FFMPEG只支持x86模式,不支持混合模式,所以需要在配置管理器进行配置x86平台,如下所示:

4. 由于视频帧频率过快,所以需要进行加锁控制,否则会造成【读写受保护的内存】错误。

经过以上4步,才可以进行视频录制。如果是进行拍照,则不需要。

备注

心有猛虎,细嗅蔷薇。

原文地址:https://www.cnblogs.com/hsiang/p/11762412.html