C# 调用AForge类库操做摄像头

不少都是C#调用window API 发送SendMessage,实现操做摄像头,可是C#调用window API的时候由于驱动的问题,老是弹出视频选择对话框,让人非常无语,看到大牛们有的截获到了window消息,而后模拟点击肯定按钮,这是在是不敢恭维啊,还有的大牛根据API原型重写了,至于我是一只IT小小鸟了,而后在继续百度,找到了一个AForge强大的C#类库,最后终于搞定了,接下来将我拙劣的代码部分贴出来,以便同行或者须要的朋友学习交流,ide

首先用到AForge类库下载地址:http://www.aforgenet.com/工具

而后引用AForge,AForge.Controls(这个是控件,能够添加到工具箱中),AForge.Imaging,AForge.Video,AForge.Video.DirectShow;学习

而后直接上代码.net

private FilterInfoCollection videoDevices;
private VideoCaptureDevice videoSource;
public int selectedDeviceIndex = 0;视频

 

下面是获取设备blog

public FilterInfoCollection GetDevices()
        {
            try
            {
                //枚举全部视频输入设备
                videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
                if (videoDevices.Count != 0)
                {
                    LogClass.WriteFile("已找到视频设备.");
                    return videoDevices;
                }
                else
                    return null;
            }
            catch (Exception ex)
            {
                LogClass.WriteFile("error:没有找到视频设备!具体缘由:" + ex.Message);
                return null;
            }
        }原型

选择设备,而后链接摄像头string

<p> /// <summary>
        /// 链接视频摄像头
        /// </summary>
        /// <param name="deviceIndex"></param>
        /// <param name="resolutionIndex"></param>
        /// <returns></returns>
        public VideoCaptureDevice VideoConnect(int deviceIndex = 0, int resolutionIndex = 0)
        {
            if (videoDevices.Count <= 0)
                return null;
            selectedDeviceIndex = deviceIndex;
            videoSource = new VideoCaptureDevice(videoDevices[deviceIndex].MonikerString);</p><p>            return videoSource;
        }</p>
//抓图,拍照,单帧

public void GrabBitmap(string path)
{
if (videoSource == null)
return;
g_Path = path;
videoSource.NewFrame += new NewFrameEventHandler(videoSource_NewFrame);
}it

 

void videoSource_NewFrame(object sender, AForge.Video.NewFrameEventArgs eventArgs)
{
Bitmap bmp = (Bitmap)eventArgs.Frame.Clone();
string fullPath = path + "temp\\";
if (!Directory.Exists(fullPath))
Directory.CreateDirectory(fullPath);
string img = fullPath + DateTime.Now.ToString("yyyyMMdd hhmmss") + ".bmp";
bmp.Save(img);
//若是这里不写这个,一下子会不停的拍照,
videoSource.NewFrame -= new NewFrameEventHandler(videoSource_NewFrame);
}io

这样就完成了操做摄像头的工做

可是发现一个问题,若是要拍照获得的照片先要处理在保存,这里就有问题了,因此须要在界面前台中添加控件,医用AForge.Controls,而后添加到工具箱,而后将VideoSourcePlayer控件拖到窗体中,想要获得单张图像处理:

Bitmap bmp = videoSourcePlayer1.GetCurrentFrame();

相关文章
相关标签/搜索