//静态变量提高访问速度
//Read the HaarCascade objects
static HaarCascade face = new HaarCascade(".\\haarcascades\\haarcascade_frontalface_alt_tree.xml");
static HaarCascade eye = new HaarCascade(".\\haarcascades\\haarcascade_frontaleye.xml");
private static void FaceDetector(Bitmap frame)
{
//调用OpenCV进行人脸分析与检测
//转换为8为灰度图像处理
//首先将图OpenCV的Image格式,允许使用矩阵操作图像
using (Emgu.CV.Image<Bgr, Byte> image = new Emgu.CV.Image<Bgr, Byte>((Bitmap)frame.Clone()))
{
//Emgu.CV.Image<Bgr, Byte> image = new Emgu.CV.Image<Bgr, byte>("lena.jpg"); //Read the files as an 8-bit Bgr image
Emgu.CV.Image<Gray, Byte> gray = image.Convert<Gray, Byte>(); //Convert it to Grayscale
//normalizes brightness and increases contrast of the image
gray._EqualizeHist();
gray.SmoothMedian(5);//中值滤波
////Read the HaarCascade objects
//HaarCascade face = new HaarCascade(".\\haarcascades\\haarcascade_frontalface_alt_tree.xml");
//HaarCascade eye = new HaarCascade(".\\haarcascades\\haarcascade_frontaleye.xml");
//HaarCascade upperBody = new HaarCascade(".\\haarcascades\\haarcascade_upperbody.xml");
//Detect the faces from the gray scale image and store the locations as rectangle
//The first dimensional is the channel
//The second dimension is the index of the rectangle in the specific channel
////检测人体上半部分
//MCvAvgComp[][] bodysDetected = gray.DetectHaarCascade(upperBody, 1.1, 1, Emgu.CV.CvEnum.HAAR_DETECTION_TYPE.DO_CANNY_PRUNING, new Size(20, 20));
Graphics g = Graphics.FromImage(frame);
//foreach (var cBody in bodysDetected[0])//只考虑一个人的情况
//{
// g.DrawRectangle(penBlue, cBody.rect);
// g.DrawString("body detected", font, brush, cBody.rect);
//检测人脸
//gray.ROI = gray.rect;
MCvAvgComp[][] facesDetected = gray.DetectHaarCascade(face, 1.1, 1, Emgu.CV.CvEnum.HAAR_DETECTION_TYPE.DO_CANNY_PRUNING, new Size(20, 20));
gray.ROI = Rectangle.Empty;
foreach (MCvAvgComp f in facesDetected[0]) //只有一个人脸
{
//Set the region of interest on the faces
gray.ROI = f.rect;
MCvAvgComp[][] eyesDetected = gray.DetectHaarCascade(eye, 1.1, 1,Emgu.CV.CvEnum.HAAR_DETECTION_TYPE.DO_CANNY_PRUNING,new Size(20, 20));
gray.ROI = Rectangle.Empty;
//if there is no eye in the specific region, the region shouldn't contains a face
//note that we might not be able to recoginize a person who ware glass in this case
if (eyesDetected[0].Length == 0) continue;
//draw the face detected in the 0th (gray) channel with blue color
//image.Draw(f.rect, new Bgr(Color.Blue), 2);
//foreach (MCvAvgComp e in eyesDetected[0])
//{
// Rectangle eyeRect = e.rect;
// eyeRect.Offset(f.rect.X, f.rect.Y);
// image.Draw(eyeRect, new Bgr(Color.Red), 2);
//}
g.DrawRectangle(penBlue, f.rect);
g.DrawString("face detected", font, brush, f.rect);
foreach (MCvAvgComp e in eyesDetected[0])
{
Rectangle eyeRect = e.rect;
eyeRect.Offset(f.rect.X, f.rect.Y);
//image.Draw(eyeRect, new Bgr(Color.Red), 2);
g.DrawRectangle(penBlue, eyeRect);
}
}
//}
}
}