天天看點

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. public void GrabBitmap(string path)  
  3.         {  
  4.             if (videoSource == null)  
  5.                 return;  
  6.             g_Path = path;  
  7.             videoSource.NewFrame += new NewFrameEventHandler(videoSource_NewFrame);  
  8.         }  

[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類庫是非常的強大,這裡隻是冰山一角