怎么在C#中调用AForge实现摄像头?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
1:首先下载库文件
输出为MP4需要用到ffmpeg相关的文件,我打包的库已经带了,去官网找的库可以在这个目录找到:

2:添加这些引用:

3:两个全局变量:
//用来操作摄像头
private VideoCaptureDevice Camera = null;
//用来把每一帧图像编码到视频文件
private VideoFileWriter VideoOutPut = new VideoFileWriter();
开始代码:
//获取摄像头列表
var devs = new FilterInfoCollection(FilterCategory.VideoInputDevice);
//实例化设备控制类(我选了第1个)
Camera = new VideoCaptureDevice(devs[0].MonikerString);
//配置录像参数(宽,高,帧率,比特率等参数)VideoCapabilities这个属性会返回摄像头支持哪些配置,从这里面选一个赋值接即可,我选了第1个
Camera.VideoResolution = Camera.VideoCapabilities[0];
//设置回调,aforge会不断从这个回调推出图像数据
Camera.NewFrame += Camera_NewFrame;
//打开摄像头
Camera.Start();
//打开录像文件(如果没有则创建,如果有也会清空),这里还有关于
VideoOutPut.Open("E:/VIDEO.MP4",
Camera.VideoResolution.FrameSize.Width,
Camera.VideoResolution.FrameSize.Height,
Camera.VideoResolution.AverageFrameRate,
VideoCodec.MPEG4,
Camera.VideoResolution.BitCount);
给AForge输出图像数据的回调方法:
//图像缓存
private Bitmap bmp = new Bitmap(1, 1);
//摄像头输出回调
private void Camera_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
//写到文件
VideoOutPut.WriteVideoFrame(eventArgs.Frame);
lock (bmp)
{
//释放上一个缓存
bmp.Dispose();
//保存一份缓存
bmp = eventArgs.Frame.Clone() as Bitmap;
}
}结束代码:
//停摄像头
Camera.Stop();
//关闭录像文件,如果忘了不关闭,将会得到一个损坏的文件,无法播放
VideoOutPut.Close();4:修改App.config,兼容net2.0的一些东西:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
</startup>
<supportedRuntime version="v2.0.50727"/>
</configuration>不然会这样:

。
关于怎么在C#中调用AForge实现摄像头问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。
郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。