1. 定义人脸测试类
2. 获取图片数据并灰度处理
3.使用cascade模型+Cascade分类器进行人脸检测
人脸识别测试类:
public class FRTest
{
private CascadeClassifier _cascadeClassifier;
private Capture _capture;
public FRTest()
{
_capture = new Capture();
}
public void Do(PictureBox pictureBox)
{
_cascadeClassifier = new CascadeClassifier(Application.StartupPath + "/haarcascades/haarcascade_frontalface_default.xml");
using (var imageFrame = _capture.QueryFrame().ToImage<Bgr, Byte>())
{
if (imageFrame != null)
{
var grayframe = imageFrame.Convert<Gray, byte>();
var faces = _cascadeClassifier.DetectMultiScale(grayframe, 1.1, 10,
Size.Empty); //the actual face detection happens here
foreach (var face in faces)
{
imageFrame.Draw(face, new Bgr(Color.BurlyWood),
3); //the detected face(s) is highlighted here using a box that is drawn around it/them
}
var bmp = EmguHelper.ResizeImage(imageFrame.ToBitmap(), new Size(pictureBox.Width, pictureBox.Height));
// pictureBox.CrossThreadSafeCall(() =>
//{
pictureBox.Image = bmp;
// });
}
}
}
}
4. 运行
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
var frTest = new FRTest();
BackgroundWorker bgWorker = new BackgroundWorker();
bgWorker.DoWork += (o, args) =>
{
frTest.Do(pictureBox1);
};
Timer t = new Timer();
t.Interval = 100;
t.Tick += (o, args) =>
{
if (!bgWorker.IsBusy)
{
bgWorker.RunWorkerAsync();
}
};
t.Start();
}
}
5. 辅助函数:
public static Bitmap ResizeImage(Bitmap bmp, Size size)
{
Bitmap newbmp = new Bitmap(size.Width, size.Height);
using (Graphics g = Graphics.FromImage(newbmp))
{
g.DrawImage(bmp, new Rectangle(Point.Empty, size));
}
return newbmp;
}