利用Harra Cascade?分类器进行人脸检测和进一步进行笑脸检测,采用训练好的分类模型,在OpenCVSharp里变得非常简单,两三条语句就搞定了:
?CascadeClassifier face_cascade = new CascadeClassifier(facemodelfile);? //创建一个人脸分类器 ?face_cascade .DetectMultiScale(image);? ?//检测人脸
?CascadeClassifier smile_cascade = new CascadeClassifier(smilemodelfile);? //创建一个笑脸分类器
?smile_cascade.DetectMultiScale(image);? ?//检测笑脸
?
?下面是完整的代码:
using System;
using System.Drawing;
using System.Windows.Forms;
using OpenCvSharp;
namespace SmileDetect
{
public partial class Form1 : Form
{
string filename = "";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "图片文件|*.jpg;*.png;*.bmp;*.gif";
ofd.CheckFileExists = true;
if(ofd.ShowDialog()== DialogResult.OK)
{
filename = ofd.FileName;
pictureBox1.Image = DetectSmile(filename);
}
}
private Bitmap DetectSmile(string filename)
{
double scaleFactor = Convert.ToDouble(textBox1.Text);
if (scaleFactor <= 1.00)
scaleFactor = 1.01;
int miniNeighbors = Convert.ToInt16(textBox2.Text);
string facemodel = @"D:\OpenCV4.5\build\etc\haarcascades\haarcascade_frontalface_default.xml";
string smilemodel = @"D:\OpenCV4.5\build\etc\haarcascades\haarcascade_smile.xml";
CascadeClassifier face_cascade = new CascadeClassifier(facemodel);
CascadeClassifier eye_cascade = new CascadeClassifier(eyemodel);
CascadeClassifier smile_cascade = new CascadeClassifier(smilemodel);
Mat input = new Mat(filename, ImreadModes.Color);
Mat grayInput = new Mat();
Cv2.CvtColor(input, grayInput, ColorConversionCodes.BGR2GRAY);
Rect[] faces = face_cascade.DetectMultiScale(input, 1.3, 5);
for (int i = 0; i < faces.Length; i++)
{
Cv2.Rectangle(input, faces[i], Scalar.Red,2);
Mat faceMat = grayInput[faces[i]];
Mat faceMatColor = input[faces[i]];
Rect[] smiles = smile_cascade.DetectMultiScale(faceMat, scaleFactor, miniNeighbors);
for (int j = 0; j < smiles.Length; j++)
{
Cv2.Rectangle(faceMatColor, smiles[j], Scalar.Green,2);
}
}
return OpenCvSharp.Extensions.BitmapConverter.ToBitmap(input);
}
private void button2_Click(object sender, EventArgs e)
{
if(filename.Length>0)
{
if(pictureBox1.Image != null)
{
pictureBox1.Image = DetectSmile(filename);
}
}
}
}
}
模型文件可以在这里下载:https://github.com/opencv/opencv/tree/master/data/haarcascades
|