用c++实现多人的人脸检测和自动取景功能的代码
时间: 2024-02-24 16:59:52 浏览: 27
以下是一个基于 OpenCV 库的 C++ 代码,实现了多人的人脸检测和自动取景功能:
```c++
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main()
{
// 加载人脸检测器
CascadeClassifier face_cascade;
face_cascade.load("haarcascade_frontalface_alt.xml");
// 打开摄像头
VideoCapture cap(0);
if (!cap.isOpened()) {
cerr << "Failed to open camera!" << endl;
return -1;
}
while (true) {
// 读取图像
Mat frame;
cap >> frame;
if (frame.empty()) {
cerr << "Failed to read frame!" << endl;
break;
}
// 转换为灰度图像
Mat gray;
cvtColor(frame, gray, COLOR_BGR2GRAY);
// 检测人脸
vector<Rect> faces;
face_cascade.detectMultiScale(gray, faces);
// 调整取景框
if (!faces.empty()) {
int x = INT_MAX, y = INT_MAX, w = INT_MIN, h = INT_MIN;
for (const auto& face : faces) {
x = min(x, face.x);
y = min(y, face.y);
w = max(w, face.x + face.width);
h = max(h, face.y + face.height);
}
int margin_x = w - x;
int margin_y = h - y;
int margin = max(margin_x, margin_y);
int cx = x + margin_x / 2;
int cy = y + margin_y / 2;
int size = max(margin, max(frame.cols, frame.rows));
int x0 = cx - size / 2;
int y0 = cy - size / 2;
int x1 = cx + size / 2;
int y1 = cy + size / 2;
Rect roi(x0, y0, x1 - x0, y1 - y0);
Mat roi_frame = frame(roi);
// 显示图像
imshow("Face detection", roi_frame);
} else {
// 显示图像
imshow("Face detection", frame);
}
// 退出循环
if (waitKey(1) == 'q') {
break;
}
}
// 释放资源
cap.release();
destroyAllWindows();
return 0;
}
```
这段代码使用 CascadeClassifier 类加载已经训练好的人脸检测器,并使用 detectMultiScale 函数检测图像中的人脸。然后,根据检测到的人脸位置和数量,使用图像处理函数调整图像的取景框,并在窗口中显示调整后的图像。需要注意的是,这段代码只演示了如何对单张图像进行人脸检测和自动取景,如果要对视频流进行处理,需要在循环中不断读取图像帧,并针对每帧进行处理。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)