AForge類庫呼叫攝像頭
阿新 • • 發佈:2018-11-02
首先用到AForge類庫下載地址:http://www.aforgenet.com/
然後引用AForge,AForge.Controls(這個是控制元件,可以新增到工具箱中),AForge.Imaging,AForge.Video,AForge.Video.DirectShow;
然後直接上程式碼
下面是獲取裝置
[csharp] view plain copy- public FilterInfoCollection GetDevices()
- {
- try
- {
- //列舉所有視訊輸入裝置
- videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
- if
- {
- LogClass.WriteFile("已找到視訊裝置.");
- return videoDevices;
- }
- else
- return null;
- }
- catch (Exception ex)
- {
- LogClass.WriteFile("error:沒有找到視訊裝置!具體原因:" + ex.Message);
- return null;
- }
- }
選擇裝置,然後連線攝像頭
- <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);
- }
- 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);
- }
這樣就完成了操作攝像頭的工作
但是發現一個問題,如果要拍照得到的照片先要處理在儲存,這裡就有問題了,所以需要在介面前臺中新增控制元件,醫用AForge.Controls,然後新增到工具箱,然後將VideoSourcePlayer控制元件拖到窗體中,想要得到單張影象處理:
Bitmap bmp = videoSourcePlayer1.GetCurrentFrame();
這樣就可以拿來處理了,AForge類庫是非常的強大,這裡只是冰山一角