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 Emgu.CV;
using Emgu.CV.Structure;
using Emgu.CV.Util;
using System.Runtime.InteropServices;
namespace FaceDetection
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = Image.FromFile(openFileDialog1.FileName);
}
}
private void button2_Click(object sender, EventArgs e)
{
//Load the image
Image<Bgr, Byte> image = new Image<Bgr, Byte>(openFileDialog1.FileName);
//Use List to store faces and eyes
List<Rectangle> faces = new List<Rectangle>();
List<Rectangle> eyes = new List<Rectangle>();
//Pre-trained cascade
CascadeClassifier face = new CascadeClassifier("haarcascade_frontalface_default.xml");
CascadeClassifier eye = new CascadeClassifier("haarcascade_eye.xml");
//The input image of Cascadeclassifier must be grayscale
Image<Gray, Byte> gray = image.Convert<Gray, Byte>();
//Face detection
Rectangle[] facesDetected = face.DetectMultiScale(
gray, //image
1.1, //scaleFactor
10, //minNeighbors
new Size(20, 20), //minSize
Size.Empty); //maxSize
faces.AddRange(facesDetected);
//Eyes detection
foreach (Rectangle f in facesDetected)
{
gray.ROI = f;
//scaleFactor参数可以决定每两个不同大小的窗口之间有多大的跳跃;这个参数设置的大,则意味着计算会变快
//但如果窗口错过了某个大小的人脸,则可能丢失物体。
//minNeighbors控制误检测,现实图像中脸会被多次检测到,因为周围的像素和不同大小的窗口也会检测到人脸。
//在人脸检测代码中,设置这个参数的默认值3表明至少有3次重叠检测,我们才认为人脸确实存在。
//minSize指示人脸的最小区域。设置参数过大,会丢失小物体为代价减少计算量。
Rectangle[] eyesDetected = eye.DetectMultiScale(
gray,
1.1,
10,
new Size(20, 20),
Size.Empty);
gray.ROI = Rectangle.Empty;
foreach (Rectangle ey in eyesDetected)
{
Rectangle eyeRect = ey;
eyeRect.Offset(f.X, f.Y);
eyes.Add(eyeRect);
}
}
//Draw detected area
foreach (Rectangle face1 in faces)
image.Draw(face1, new Bgr(Color.Red), 2);
foreach (Rectangle eye1 in eyes)
image.Draw(eye1, new Bgr(Color.Blue), 2);
//Show image
pictureBox1.Image = image.Bitmap;
}
}
}
Emgu人脸检测
最新推荐文章于 2021-03-04 09:53:10 发布