c# Opencvsharp 3 camcorder capture on windows form

TadasK picture TadasK · Sep 12, 2016 · Viewed 8.2k times · Source

Hi am new on opencvsharp programming. I am trying to make a program which would stream my camera view via picturebox. The while loop crashes my program. Without the loop it works fine, although it shows only a picture. I am using 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";
    }
}

Update: thanks to GuidoG comment, i have managed to figure it out.

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

}
}

Answer

jesson picture jesson · Feb 5, 2018
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;
    }

}

The part should be put in the begin BeginInvoke(). You need to create a delegate function