【C#】借助OpenCvSharp读取摄像头并显示

1,首先要安装OpenCvSharp,使用cv2的函数获取设备,并将图像转换到Bitmap

更多内容关注微信公众号:ML_Study

  using OpenCvSharp;
  using OpenCvSharp.Extensions;    



     void run_cap()
        {
            Mat src = new Mat();
            FrameSource frame = Cv2.CreateFrameSource_Camera(0);
            while (f1)
            {

                frame.NextFrame(src);
                
                Bitmap bitmap = BitmapConverter.ToBitmap(src);
                

                Invalidate();
                pictureBox1.Invalidate();


                imgshow = bitmap;
                
            }

        }

2,在调用时开启线程,可以在主函数内调用,也可在按钮内调用

      private void button1_Click(object sender, EventArgs e)
        {

           // Image imgshow0 = Image.FromFile("src.jpg");
          //  pictureBox1.Image = imgshow0;
            Thread threadA = new Thread(run_cap);
            threadA.Start();

        }

3,在form框架调用重绘函数将每一帧重绘到pictureBox1

this.pictureBox1.Paint += PictureBox1_Paint;

4,函数如下:

       private void PictureBox1_Paint(object sender, PaintEventArgs e)
        {
           if (f)
            {

                           
                Invalidate();pictureBox1.Invalidate();    
                e.Graphics.DrawImage(imgshow,0,0);

            }

        }

5,运行如下:

【C#】借助OpenCvSharp读取摄像头并显示_第1张图片

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