Introduction
Face detection has evolved from a cool sci-fi concept to a practical tool in everything from photo tagging to biometric authentication. In this blog post, we’ll explore how to build a real-time face detection system using the latest .NET 9 and OpenCV via Emgu.CV, a popular .NET wrapper around the OpenCV library.
Prerequisites
To follow along, you'll need:
- ✅ .NET 9 SDK
- ✅ Visual Studio 2022+ or VS Code
- ✅ Basic knowledge of C#
- ✅ Emgu.CV NuGet packages
- ✅ A working webcam (for real-time detection)
Step 1. Create a New .NET Console App
Open a terminal and run:
dotnet new console -n FaceDetectionApp
cd FaceDetectionApp
Step 2. Install Required Packages
Add the Emgu.CV packages:
dotnet add package Emgu.CV
dotnet add package Emgu.CV.runtime.windows
Step 3. Add the Haar Cascade File
OpenCV uses trained XML classifiers for detecting objects. Download the Haar cascade for frontal face detection:
🔗 Download XML
Place this file in your project root and configure it to copy to the output directory:
FaceDetectionApp.csproj
<ItemGroup>
<None Update="haarcascade_frontalface_default.xml">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
Step 4. Write the Real-Time Detection Code
Replace Program.cs with:
using Emgu.CV;
using Emgu.CV.Structure;
using System.Drawing;
var capture = new VideoCapture(0);
var faceCascade = new CascadeClassifier("haarcascade_frontalface_default.xml");
if (!capture.IsOpened)
{
Console.WriteLine("Could not open the webcam.");
return;
}
Console.WriteLine("Press ESC to exit...");
while (true)
{
using var frame = capture.QueryFrame()?.ToImage<Bgr, byte>();
if (frame == null)
break;
var gray = frame.Convert<Gray, byte>();
var faces = faceCascade.DetectMultiScale(gray, 1.1, 10, Size.Empty);
foreach (var face in faces)
{
frame.Draw(face, new Bgr(Color.Green), 2);
}
CvInvoke.Imshow("Real-Time Face Detection", frame);
if (CvInvoke.WaitKey(1) == 27) // ESC key
break;
}
CvInvoke.DestroyAllWindows();
Output
Once you run the app using dotnet run, your webcam will open, and it will start detecting faces in real time by drawing rectangles around them.
Conclusion
With the power of .NET 9 and the flexibility of OpenCV, building a real-time face detection system has never been easier. Whether you're developing a hobby project or prototyping a serious application, this foundation sets you on the path to mastering computer vision in the .NET ecosystem.