c# Opencvsharp 3摄像机捕捉窗体

本文关键字:窗体 摄像机 Opencvsharp | 更新日期: 2023-09-27 18:06:35

我是opencvsharp编程的新手。我正在尝试制作一个程序,它可以通过picturebox传输我的相机视图。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;
            }
    }
}
}

c# Opencvsharp 3摄像机捕捉窗体

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;
    }
}

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