AForge调用摄像头 - (第四十七讲)
本章节给大家讲讲如何使用AForge调用摄像头进行拍照,按照百度百科的说法:AForge.NET是一个专门为开发者和研究者基于C#框架设计的,这个框架提供了不同的类库和关于类库的资源,还有很多应用程序例子,包括计算机视觉与人工智能,图像处理,神经网络,遗传算法,机器学习,机器人等领域。
感觉好像和OpenCv的功能差不多,但是OpenCv更适合跨平台使用,AForge需要安装的库如下:
1、AForge
2、AForge.Controls
3、AForge.Imaging
4、AForge.Math
5、AForge.Video
6、AForge.Video.DirectShow

废话不多说,我们先来看下演示效果:

首先我们来看下对AForge的封装VideoDevice.cs文件代码:
using AForge.Controls;
using AForge.Video.DirectShow;
using System.Collections.Generic;
namespace WindowsFormsApp
{
public class VideoDevice
{
public VideoSourcePlayer vispShoot; // 图像数据
private VideoCaptureDevice videoDevice; // 启动的摄像头
private FilterInfoCollection videoDevices; // 摄像头列表
/// <summary>
/// 获取当前摄像头列表
/// </summary>
/// <returns></returns>
public List<string> GetVideos()
{
List<string> dev = new List<string>();
videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
if (videoDevices.Count != 0)
{
foreach (FilterInfo device in videoDevices)
{
dev.Add(device.Name);
}
}
return dev;
}
/// <summary>
/// 启动摄像头
/// </summary>
/// <param name="Index"></param>
public void StartPlay(int Index)
{
videoDevice = new VideoCaptureDevice(videoDevices[Index].MonikerString);
videoDevice.VideoResolution = videoDevice.VideoCapabilities[videoDevice.VideoCapabilities.Length - 1];
vispShoot.VideoSource = videoDevice;
vispShoot.Start();
}
/// <summary>
/// 关闭摄像头
/// </summary>
/// <param name="Index"></param>
public void StopPlay()
{
vispShoot.WaitForStop();
vispShoot.Stop();
}
}
}
Form1.cs的代码如下:
using AForge.Controls;
using System;
using System.Windows.Forms;
namespace WindowsFormsApp
{
public partial class Form1 : Form
{
private VideoDevice video = new VideoDevice();
public Form1()
{
InitializeComponent();
// 初始化,将图像添加到pictureBox1控件上
video.vispShoot = new VideoSourcePlayer();
pictureBox1.Controls.Add(video.vispShoot);
video.vispShoot.Dock = DockStyle.Fill;
}
private void button_查找摄像头_Click(object sender, EventArgs e)
{
comboBox1.Items.Clear();
comboBox1.Items.AddRange(video.GetVideos().ToArray());
comboBox1.SelectedIndex = 0;
}
private void button_打开摄像头_Click(object sender, EventArgs e)
{
video.StartPlay(comboBox1.SelectedIndex);
}
private void button_关闭摄像头_Click(object sender, EventArgs e)
{
video.StopPlay();
}
private void button_拍照_Click(object sender, EventArgs e)
{
pictureBox2.Image = video.vispShoot.GetCurrentVideoFrame();
}
}
}