1. 程式人生 > >基於opencv3的人臉檢測

基於opencv3的人臉檢測

目前opencv3中已經有人臉檢測的類了,只要呼叫函式庫的類就行

該程式需要兩個xml檔案,分別是haarcascade_frontalface_alt.xml和haarcascade_eye_tree_eyeglasses.xml,它們分別是已經通過了大量訓練且能檢測出人臉和眼睛了,只要呼叫即可。

#include"opencv2/objdetect/objdetect.hpp"
#include"opencv2/highgui/highgui.hpp"
#include"opencv2/imgproc/imgproc.hpp"
#include"opencv2/core/core.hpp"
#include"iostream"
using namespace std; using namespace cv; void detection(Mat frame); String face_cascade_name = "haarcascade_frontalface_alt.xml"; String eyes_cascade_name = "haarcascade_eye_tree_eyeglasses.xml"; CascadeClassifier face_cascade; CascadeClassifier eyes_cascade; int main() { if (!face_cascade.load(face_cascade_name)) cerr
<< "Loading haarcascade_frontalface_alt.xml error"<<endl; if (!eyes_cascade.load(eyes_cascade_name)) cerr << "Loading haarcascade_eye_tree_eyeglasses.xml error" << endl; VideoCapture capture(0); Mat frame; while (1) { capture >> frame; if
(!frame.data) cerr << "Opening capture error!" << endl; detection(frame); waitKey(15); } return 0; } void detection(Mat frame) { vector<Rect> faces; Mat frame_gray; cvtColor(frame, frame_gray, COLOR_BGR2GRAY); equalizeHist(frame_gray, frame_gray);//直方圖均勻化 face_cascade.detectMultiScale(frame_gray, faces, 1.1, 2, 0 | 0 | CV_HAAR_SCALE_IMAGE, Size(30, 30));//人臉檢測 for (int i = 0; i < faces.size(); i++) { //用橢圓圈出臉 Point center(faces[i].x + faces[i].width / 2, faces[i].y + faces[i].height / 2); ellipse(frame, center, Size(faces[i].width / 2, faces[i].height / 2), 0, 0, 360, Scalar(255, 0, 255), 2, 8, 0); //用圓圈出眼睛 Mat face_roi = frame_gray(faces[i]); vector<Rect> eyes; eyes_cascade.detectMultiScale(face_roi, eyes, 1.1, 2, 0 | CV_HAAR_SCALE_IMAGE, Size(30, 30));//在臉中檢測眼睛 for (int j = 0; j < eyes.size(); j++) { Point eye_center(faces[i].x + eyes[j].x + eyes[j].width / 2, faces[i].y + eyes[j].y + eyes[j].height / 2); int radius = cvRound((eyes[j].width + eyes[j].height)*0.25); circle(frame, eye_center, radius, Scalar(255, 0, 0), 3, 8, 0); } } //-- 顯示最終效果圖 imshow("picture", frame); }