opecv人脸检测 c++
时间: 2023-11-24 21:51:33 浏览: 55
以下是使用OpenCV和dlib库进行人脸检测的C++代码示例:
```cpp
#include <opencv2/opencv.hpp>
#include <dlib/opencv.h>
#include <dlib/image_processing/frontal_face_detector.h>
#include <dlib/image_processing.h>
using namespace cv;
using namespace dlib;
int main()
{
// 加载图像
Mat img1 = imread("1.jpg");
Mat img2 = imread("2.jpg");
// 初始化人脸检测器
frontal_face_detector detector = get_frontal_face_detector();
shape_predictor predictor;
deserialize("shape_predictor_68_face_landmarks.dat") >> predictor;
// 将OpenCV图像转换为dlib图像
cv_image<bgr_pixel> dlib_img1(img1);
cv_image<bgr_pixel> dlib_img2(img2);
// 检测人脸并标记关键点
std::vector<rectangle> dets1 = detector(dlib_img1);
std::vector<rectangle> dets2 = detector(dlib_img2);
std::vector<full_object_detection> shapes1, shapes2;
for (unsigned long i = 0; i < dets1.size(); ++i)
shapes1.push_back(predictor(dlib_img1, dets1[i]));
for (unsigned long i = 0; i < dets2.size(); ++i)
shapes2.push_back(predictor(dlib_img2, dets2[i]));
// 将dlib图像转换回OpenCV图像
Mat img1_landmarks = img1.clone();
Mat img2_landmarks = img2.clone();
for (unsigned long i = 0; i < shapes1.size(); ++i)
for (unsigned long j = 0; j < 68; ++j)
circle(img1_landmarks, Point(shapes1[i].part(j).x(), shapes1[i].part(j).y()), 2, Scalar(0, 255, 0), -1);
for (unsigned long i = 0; i < shapes2.size(); ++i)
for (unsigned long j = 0; j < 68; ++j)
circle(img2_landmarks, Point(shapes2[i].part(j).x(), shapes2[i].part(j).y()), 2, Scalar(0, 255, 0), -1);
// 显示结果
imshow("img1 with landmarks", img1_landmarks);
imshow("img2 with landmarks", img2_landmarks);
waitKey(0);
return 0;
}
```
上述代码使用了dlib库中的人脸检测器和关键点检测器,将OpenCV图像转换为dlib图像进行处理,最后再将dlib图像转换回OpenCV图像进行显示。你可以根据自己的需求对代码进行修改。