Windows Forms: Webcam Face Detection for .NET using EMGU.CV in C#

This post shows you How to implement face detection from webcam or camera using EMGU.CV in C# .NET Windows Forms Application.

Creating a new Windows Forms Application project, then open your form designer.

Dragging Label, Combobox, PictureBox and Button controls from your Visual Studio Toolbox to your form designer.

c# face detection using webcam

After you finish your form design, you need to right-click on your project, then select Manage Nuget Packages.

Face detection and recognition using emgu, opencv and c#

Next, Search and Install 'AForge'. 'Emgu' to your project.

emgu aforge c#

Declare two variables as shown below.

FilterInfoCollection filter;
VideoCaptureDevice device;

Adding a Form_Load event handler that allows you to detect your webcam name, then add the device name to the Combobox control.

private void Form1_Load(object sender, EventArgs e)
{
    filter = new FilterInfoCollection(FilterCategory.VideoInputDevice);
    foreach (FilterInfo device in filter)
        cboDevice.Items.Add(device.Name);
    cboDevice.SelectedIndex = 0;
    device = new VideoCaptureDevice();
}

You need to download haarcascade_frontalface_alt_tree.xml from github website, then create a cascadeClassifier variable.

This is a training data file helps you detect faces in image.

static readonly CascadeClassifier cascadeClassifier = new CascadeClassifier("haarcascade_frontalface_alt_tree.xml");

Adding a click event handler to the Detect button allows you to capture image from the webcam.

private void btnDetect_Click(object sender, EventArgs e)
{
    device = new VideoCaptureDevice(filter[cboDevice.SelectedIndex].MonikerString);
    device.NewFrame += Device_NewFrame;
    device.Start();
}

You should implement NewFrame event handler allows you to detect face from webcam.

private void Device_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
    Bitmap bitmap = (Bitmap)eventArgs.Frame.Clone();
    Image<Bgr, byte> grayImage = new Image<Bgr, byte>(bitmap);
    Rectangle[] rectangles = cascadeClassifier.DetectMultiScale(grayImage, 1.2, 1);
    foreach (Rectangle rectangle in rectangles)
    {
        using (Graphics graphics = Graphics.FromImage(bitmap))
        {
            using (Pen pen = new Pen(Color.Red, 1))
            {
                graphics.DrawRectangle(pen, rectangle);
            }
        }
    }
    pic.Image = bitmap;
}

You can also draw squares on faces that you detect.

And don't forget to close your webcam when closing your form.

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if (device.IsRunning)
        device.Stop();
}

VIDEO TUTORIAL