c# Opencvsharp 3 摄像机捕获 windows 形式

c# Opencvsharp 3 camcorder capture on windows form

大家好,我是 opencvsharp 编程的新手。我正在尝试制作一个程序,通过图片框流式传输我的相机视图。 while 循环使我的程序崩溃。没有循环它工作正常,虽然它只显示一张图片。我正在使用 opencvsharp3。

    VideoCapture capture;
    Mat frame;
    Bitmap image;


public Form1()
{
    InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
    if (button1.Text.Equals("Start"))
    {
        frame = new Mat();
        capture = new VideoCapture();
        capture.Open(2);
        capture.Read(frame);
        Bitmap image = BitmapConverter.ToBitmap(frame);
        while (true)
        {
            pictureBox1.Image = image;
        }
        button1.Text = "Stop";
    }
    else
    {
        capture.Release();
        button1.Text = "Start";
    }
}

更新:感谢 GuidoG 的评论,我已经弄明白了。

    VideoCapture capture;
    Mat frame;
    Bitmap image;
    private Thread camera;
    int isCameraRunning = 0;

    private void CaptureCamera()
    {
      camera = new Thread(new ThreadStart(CaptureCameraCallback));
      camera.Start();
    }

    private void CaptureCameraCallback()
    {
        frame = new Mat();
        capture = new VideoCapture();
        capture.Open(2);
        while (isCameraRunning == 1)
        {
            capture.Read(frame);
            image = BitmapConverter.ToBitmap(frame);
            pictureBox1.Image = image;
            image = null;
        }

    }
    public Form1()
    {
        InitializeComponent();

    }

   private void button1_Click(object sender, EventArgs e)
    {
         if (button1.Text.Equals("Start"))
            {
            CaptureCamera();
            button1.Text = "Stop";
            isCameraRunning = 1;
            }
            else
            {
            capture.Release();
            button1.Text = "Start";
            isCameraRunning = 0;
            }
    }

}
}
private void CaptureCameraCallback()
{
    frame = new Mat();
    capture = new VideoCapture();
    capture.Open(2);
    while (isCameraRunning == 1)
    {
        capture.Read(frame);
        image = BitmapConverter.ToBitmap(frame);
        pictureBox1.Image = image;
        image = null;
    }

}

该部分应放在 beginBeginInvoke() 中。 您需要创建一个委托函数