以下是使用 lbpcascade_frontalface.xml 和 dlib 库从摄像头中取出最大的一张人脸进行人眼检测的 C++ 程序示例:
```c++ #include <dlib/image_processing/frontal_face_detector.h> #include <dlib/image_processing/render_face_detections.h> #include <dlib/image_processing.h> #include <dlib/gui_widgets.h> #include <dlib/image_io.h> #include <dlib/opencv.h> #include <opencv2/opencv.hpp>
using namespace dlib; using namespace std;
int main() { try { // 初始化人脸检测器 frontal_face_detector detector = get_frontal_face_detector();
// 初始化人眼检测器
shape_predictor sp;
deserialize("shape_predictor_68_face_landmarks.dat") >> sp;
// 打开摄像头
cv::VideoCapture cap(0);
if (!cap.isOpened())
{
cerr << "Unable to connect to camera" << endl;
return 1;
}
// 循环读取摄像头中的每一帧
while (1)
{
cv::Mat temp;
cap >> temp;
cv_image<bgr_pixel> cimg(temp);
// 检测人脸
std::vector<rectangle> faces = detector(cimg);
if(faces.size()==0) continue;
int max_x = 0, max_y = 0, max_area = 0;
for (int i = 0; i < faces.size(); i++)
{
if(faces[i].area()>max_area)
{
max_x = faces[i].left();
max_y = faces[i].top();
max_area = faces[i].area();
}
}
rect max_face = rect(max_x, max_y, max_x + faces[0].width(), max_y + faces[0].height());
// 检测人眼
full_object_detection shape = sp(cimg, max_face);
// 在图像中画出人眼
for (int i = 36; i <= 41; i++)
{
cv::circle(temp, cv::Point(shape.part(i).x(), shape.part(i).y()), 2, cv::Scalar(0, 255, 0), -1);
}
cv::imshow("Face", temp);
if (cv::waitKey