C# 人脸识别第一步,OpenCvSharp打开摄像头

首先下载安装OpenCvSharp。

C# 人脸识别第一步,OpenCvSharp打开摄像头_第1张图片

添加引用后就可以开始写代码了。打开关闭摄像头:

private void btn_play_Click(object sender, EventArgs e)
        {
            if (!bPlayflag)
            {
                m_vCapture = new VideoCapture(CaptureDevice.Any);
                if (!m_vCapture.IsOpened())
                {
                    MessageBox.Show("摄像头打不开", "摄像头故障", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                m_vCapture.Set(CaptureProperty.FrameWidth, 640);//宽度
                m_vCapture.Set(CaptureProperty.FrameHeight, 480);//高度

                bPlayflag = true;
                ThreadCam = new Thread(Play_Camera);
                ThreadCam.Start();

                pic_cam.Image = null;
                btn_play.Text = "关闭摄像头";
            }
            else
            {
                bPlayflag = false;
                ThreadCam.Abort();
                m_vCapture.Release();
                btn_play.Text = "打开摄像头";
            }
        }

播放摄像头线程:

 private void Play_Camera()
        {
            while (bPlayflag)
            {
                //Thread.Sleep(40);
                Mat cFrame = new Mat();
                m_vCapture.Read(cFrame);
                int sleepTime = (int)Math.Round(1000 / m_vCapture.Fps);
                Cv2.WaitKey(sleepTime);

                if (cFrame.Empty())
                {
                    continue;
                }
                Cv2.Flip(cFrame, cFrame, OpenCvSharp.FlipMode.Y);
                Rect cMaxrect = new Rect(170, 90, 300, 300);
                if (bTakePicture)//拍照,截取指定区域
                {                    
                    Mat cHead = new Mat(cFrame, cMaxrect);
                    Cv2.ImWrite(PicSavePath, cHead);
                    SetPictureBoxImage(pic_head, cHead.ToBitmap());
                    cHead.Release();
                    bTakePicture = false;
                }
                //绘制指定区域(人脸框)
                Scalar color = new Scalar(0, 100, 0);
                Cv2.Rectangle(cFrame, cMaxrect, color, 2);
                
                SetPictureBoxImage(pic_cam, cFrame.ToBitmap());

                cFrame.Release();//释放      
            }
        }

 C# 人脸识别第一步,OpenCvSharp打开摄像头_第2张图片

C# 人脸识别第一步,OpenCvSharp打开摄像头_第3张图片

 

代码传送门 

 

你可能感兴趣的:(C#)