Facedectection in C# with less than 50 LoC
I’ve been mucking around with face detection a bit lately. Here’s a short guide to getting face detection running in C# in a short amount of time.
UPDATE: Recommend EmguCV for C# wrapping OpenCV, read the updated guide.
I’ve identified two free computer vision libraries that do face detection: Torch3vision and OpenCV(I’m sure there are plenty more, but these seem to be comprehensive, recently updated and freely available). Torch3vision claims to be better than OpenCV but on the other hand more people are building libraries and wrappers around OpenCV and there’s even a wrapper for .Net. While it doesn’t yet wrap the face detection components of OpenCV, it seems to be the most promising solution.
To get face detection in OpenCV to work with C#, do the following:
- Install OpenCV and OpenCVDotNet as per the instructions
- Get CVHaar.h from this discussion and place it in
C:\Program Files\OpenCVDotNet\src\OpenCVDotNet
UPDATE: Dud link, read the updated guide - Open
OpenCVDotNet.sln
, addCVHaar.h
to the solution and include it inOpenCVDotNet.cpp
- Rebuild the solution
- Create a Windows forms application as described in the tutorial, but do something like the code below
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using OpenCVDotNet; namespace opencvtut { public partial class Form1 : Form { private CVCapture cap; private CVHaar haar; public Form1() { InitializeComponent(); } private void timer1_Tick(object sender, EventArgs e) { using (CVImage nextFrame = cap.QueryFrame()) { Rectangle[] faces = haar.detectPatterns(1.3, nextFrame, 20, 20, 1.1, 2, 1); for (int i = 0; i < faces.Length; i++) { nextFrame.DrawRectangle(faces[i], Color.Yellow, 3); } pictureBox1.Image = nextFrame.ToBitmap(); } } private void Form1_Load(object sender, EventArgs e) { // passing 0 gets zeroth webcam cap = new CVCapture(0); haar = new CVHaar( "C:Program FilesOpenCVdatahaarcascadeshaarcascade_frontalface_alt2.xml"); } } }
Happy detecting 🙂
Leave a Reply