opencv人脸识别C++代码
时间: 2023-05-26 17:06:19 浏览: 107
基于C++ opencv实现人脸识别【100012285】
1. 导入库
```
#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
```
2. 定义命名空间
```
using namespace cv;
using namespace std;
```
3. 读取待检测的图片
```
Mat img = imread("image.jpg");
```
4. 创建 Haar 级联分类器
```
CascadeClassifier face_cascade;
face_cascade.load("haarcascade_frontalface_alt.xml");
```
5. 使用分类器检测人脸
```
vector<Rect> faces;
face_cascade.detectMultiScale(img, faces, 1.1, 2, 0|CV_HAAR_SCALE_IMAGE, Size(30, 30));
```
6. 绘制检测出的人脸
```
for (size_t i = 0; i < faces.size(); i++) {
rectangle(img, faces[i], Scalar(0, 0, 255), 2, 8, 0);
}
```
完整代码:
```
#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
using namespace cv;
using namespace std;
int main() {
Mat img = imread("image.jpg");
CascadeClassifier face_cascade;
face_cascade.load("haarcascade_frontalface_alt.xml");
vector<Rect> faces;
face_cascade.detectMultiScale(img, faces, 1.1, 2, 0|CV_HAAR_SCALE_IMAGE, Size(30, 30));
for (size_t i = 0; i < faces.size(); i++) {
rectangle(img, faces[i], Scalar(0, 0, 255), 2, 8, 0);
}
imshow("Detected Face", img);
waitKey(0);
return 0;
}
```
阅读全文