在WPF中使用AForge.net控制攝像頭拍照


利用AForge.net控制攝像頭拍照最方便的方法就是利用PictureBox顯示攝像頭畫面,但在WPF中不能直接使用PictureBox。必須通過<WindowsFormsHost></WindowsFormsHost>來提供交換功能。其解決方法如下:

1、按照常規方法新建一個WPF應用程序;

2、添加引用

WindowsFormsIntegration  (與WinForm交互的支持)

System.Windows.Forms (WinForm控件支持)

AForge.Video和AForge.Video.DirectShow(拷貝AForge.Video.dll,AForge.Video.DirectShow.dll,攝像頭操作的庫)

3、在XAML中添加  xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"(用wf代替System.Windows.Forms,即可使用<wf:PictureBox/>添加PictureBox控件

4、在界面相應位置添加

<WindowsFormsHost Name="winForm">

  <wf:PictureBox Name="myPicture"/>

</WindowsFormsHost>(至此,界面層的設置完成)

5、代碼部分

首先在窗口加載時初始化攝像頭

 myPhoto = pictureHost.Child as System.Windows.Forms.PictureBox;
            FilterInfoCollection videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
            if (videoDevices.Count <= 0)
            {
                System.Windows.MessageBox.Show("請連接攝像頭");
                return;
            }
            else
            {
                CloseCaptureDevice();
                myCaptureDevice = new VideoCaptureDevice(videoDevices[0].MonikerString);//myCaptureDevice的類型為VideoCaptureDevice,
                myCaptureDevice.NewFrame += new NewFrameEventHandler(myCaptureDevice_NewFrame);
                myCaptureDevice.DesiredFrameSize = new System.Drawing.Size(436, 360);//436, 360
                myCaptureDevice.DesiredFrameRate = 10;
                myCaptureDevice.Start();                
            }

PictureBox myPhoto = pictureHost.Child as System.Windows.Forms.PictureBox;//獲取界面中的myPicture控件

void myCaptureDevice_NewFrame(object sender, NewFrameEventArgs eventArgs)//幀處理程序
        {
            Bitmap bitmap = (Bitmap)eventArgs.Frame.Clone();
            myPhoto.Image = bitmap.Clone(
                new RectangleF((bitmap.Size.Width - 295) / 2, (bitmap.Size.Height - 413) / 2, 295, 413), //顯示圖像的寬度為295像素,高度為413像素
                System.Drawing.Imaging.PixelFormat.Format32bppRgb);
        }

關閉攝像頭,釋放系統資源(在窗口推出時必須調用)

 private void CloseCaptureDevice()
        {
            if (myCaptureDevice != null)
            {
                if (myCaptureDevice.IsRunning)
                {
                    myCaptureDevice.SignalToStop();                   
                }

       myCaptureDevice = null;
            }

    }

至此,使用AForge.net操作攝像頭基本完成。攝像頭捕獲的畫面能在PictureBox中顯示出來,如果要實現拍照只需使用myCaptureDevice.Stop()停止攝像頭,保存PictureBox中的Image屬性即可。

原來想直接使用WPF中的Image控件顯示攝像頭,但在幀處理程序中始終提示無法操作幀圖像,提示:沒有權限操作,另一進程擁有該對象(大概是這個意思)。在這個問題上我糾結了大概有10天,一直都沒有找到解決的辦法,還請高人指點,謝謝!!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM