AForge类库调用摄像头

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

然后引用AForge,AForge.Controls(这个是控件,可以添加到工具箱中),AForge.Imaging,AForge.Video,AForge.Video.DirectShow;

然后直接上代码




下面是获取设备

[csharp]  view plain copy
  1. public FilterInfoCollection GetDevices()  
  2.         {  
  3.             try  
  4.             {  
  5.                 //枚举所有视频输入设备  
  6.                 videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);  
  7.                 if (videoDevices.Count != 0)  
  8.                 {  
  9.                     LogClass.WriteFile("已找到视频设备.");  
  10.                     return videoDevices;  
  11.                 }  
  12.                 else  
  13.                     return null;  
  14.             }  
  15.             catch (Exception ex)  
  16.             {  
  17.                 LogClass.WriteFile("error:没有找到视频设备!具体原因:" + ex.Message);  
  18.                 return null;  
  19.             }  
  20.         }  


选择设备,然后连接摄像头

[csharp]  view plain copy
  1. <p> /// <summary>  
  2.         /// 连接视频摄像头  
  3.         /// </summary>  
  4.         /// <param name="deviceIndex"></param>  
  5.         /// <param name="resolutionIndex"></param>  
  6.         /// <returns></returns>  
  7.         public VideoCaptureDevice VideoConnect(int deviceIndex = 0, int resolutionIndex = 0)  
  8.         {  
  9.             if (videoDevices.Count <= 0)  
  10.                 return null;  
  11.             selectedDeviceIndex = deviceIndex;  
  12.             videoSource = new VideoCaptureDevice(videoDevices[deviceIndex].MonikerString);</p><p>            return videoSource;  
  13.         }</p>  
[csharp]  view plain copy
  1. //抓图,拍照,单帧  
  2.   
  3. public void GrabBitmap(string path)  
  4.         {  
  5.             if (videoSource == null)  
  6.                 return;  
  7.             g_Path = path;  
  8.             videoSource.NewFrame += new NewFrameEventHandler(videoSource_NewFrame);  
  9.         }  


 

[csharp]  view plain copy
  1. void videoSource_NewFrame(object sender, AForge.Video.NewFrameEventArgs eventArgs)  
  2.         {  
  3.             Bitmap bmp = (Bitmap)eventArgs.Frame.Clone();  
  4.             string fullPath = path + "temp\\";  
  5.             if (!Directory.Exists(fullPath))  
  6.                 Directory.CreateDirectory(fullPath);  
  7.             string img = fullPath + DateTime.Now.ToString("yyyyMMdd hhmmss") + ".bmp";  
  8.             bmp.Save(img);  
[csharp]  view plain copy
  1. //如果这里不写这个,一会儿会不停的拍照,  
  2.             videoSource.NewFrame -= new NewFrameEventHandler(videoSource_NewFrame);  
  3.         }  


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

但是发现一个问题,如果要拍照得到的照片先要处理在保存,这里就有问题了,所以需要在界面前台中添加控件,医用AForge.Controls,然后添加到工具箱,然后将VideoSourcePlayer控件拖到窗体中,想要得到单张图像处理:

Bitmap bmp = videoSourcePlayer1.GetCurrentFrame();

这样就可以拿来处理了,AForge类库是非常的强大,这里只是冰山一角

猜你喜欢

转载自blog.csdn.net/u010613052/article/details/47333991
今日推荐