用OpenCVSharp 4.5 跑一遍 OpenCV 官方教程。
原OpenCV 官方教程链接:OpenCV: Cascade Classifier
核心函数:
using System;
using OpenCvSharp;
namespace ConsoleApp1
{
class tutorial39 : ITutorial
{
static CascadeClassifier face_cascade = new CascadeClassifier();
static CascadeClassifier eyes_cascade = new CascadeClassifier();
public void Run()
{
string face_cascade_name = @"D:\OpenCV4.5\build\etc\haarcascades\haarcascade_frontalface_alt.xml";
string eyes_cascade_name = @"D:\OpenCV4.5\build\etc\haarcascades\haarcascade_eye_tree_eyeglasses.xml";
//-- 1. Load the cascades
if (!face_cascade.Load(face_cascade_name))
{
Console.WriteLine("--(!)Error loading face cascade");
return;
};
if (!eyes_cascade.Load(eyes_cascade_name))
{
Console.WriteLine("--(!)Error loading eyes cascade");
return;
};
VideoCapture capture = new VideoCapture();
//-- 2. Read the video stream
capture.Open(@"I:\csharp\videos\face.mp4");
if (!capture.IsOpened())
{
Console.WriteLine("--(!)Error opening video capture");
return;
}
Mat frame = new Mat();
while (capture.Read(frame))
{
if (frame.Empty())
{
Console.WriteLine("--(!) No captured frame -- Break!\n");
break;
}
//-- 3. Apply the classifier to the frame
detectAndDisplay(frame);
//Cv2.ImShow("Face Detect",frame);
if (Cv2.WaitKey(10) == 27)
{
break; // escape
}
}
return;
}
private static void detectAndDisplay(Mat frame)
{
Mat frame_gray = new Mat();
Cv2.CvtColor(frame, frame_gray, ColorConversionCodes.BGR2GRAY);
Cv2.EqualizeHist(frame_gray, frame_gray);
//-- Detect faces
Rect[] faces = face_cascade.DetectMultiScale(frame_gray);
for (int i = 0; i < faces.Length; i++)
{
Point center = new Point(faces[i].X + faces[i].Width / 2, faces[i].Y + faces[i].Height / 2);
Cv2.Ellipse(frame, center, new Size(faces[i].Width / 2, faces[i].Height / 2), 0, 0, 360, new Scalar(255, 0, 255), 4);
Mat faceROI = frame_gray[faces[i]];
//-- In each face, detect eyes
Rect[] eyes = eyes_cascade.DetectMultiScale(faceROI);
for (int j = 0; j < eyes.Length; j++)
{
Point eye_center = new Point(faces[i].X + eyes[j].X + eyes[j].Width / 2, faces[i].Y + eyes[j].Y + eyes[j].Height / 2);
int radius = (int)Math.Round((eyes[j].Width + eyes[j].Height) * 0.25);
Cv2.Circle(frame, eye_center, radius, new Scalar(255, 0, 0), 4);
}
}
//-- Show what you got
Cv2.ImShow("Capture - Face detection", frame);
}
}
}