Simple camera capture in Winforms

noelicus picture noelicus · Jun 12, 2018 · Viewed 11.8k times · Source

I just want to preview then capture a snapshot from a device camera (webcam) in a WinForms C# application.

I've used this: WebEye WebCameraControl, but it seems to fail on some machines/cameras. The description implies there's loads more out there, but I can't find any on NuGet that are for WinForms.

Any recommendations? I feel like I'm missing something obvious, like a built-in windows control that will just do it!


Edit:
In trying to add OpenCVSharp this is what I get: enter image description here

Answer

PepitoSh picture PepitoSh · Jun 12, 2018

Try OpenCVSharp. A bit of a code snippet with a PictureBox and a Button:

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

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

private void CaptureCameraCallback() {

    frame = new Mat();
    capture = new VideoCapture(0);
    capture.Open(0);

    if (capture.IsOpened()) {
        while (isCameraRunning) {

            capture.Read(frame);
            image = BitmapConverter.ToBitmap(frame);
            if (pictureBox1.Image != null) {
                pictureBox1.Image.Dispose();
            }
            pictureBox1.Image = image;
        }
    }
}

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