OpenCV人脸检测(正脸、左右侧脸)----GPU版使用

#include 
#include 
#include 
#include
#include


using namespace std;
using namespace cv;

string front_face_cascade_name = "../haarcascades_GPU/haarcascade_frontalface_alt2.xml";//正脸
string left_face_cascade_name = "../haarcascades_GPU/haarcascade_profileface.xml";//左脸

gpu::CascadeClassifier_GPU front_face_cascade;
gpu::CascadeClassifier_GPU left_face_cascade;



int main()
{


	Mat img;
	
	if (!front_face_cascade.load(front_face_cascade_name)){
		cout << "cascade load error" << endl;
		return -1;
	}
	if (!left_face_cascade.load(left_face_cascade_name)){
		cout << "cascade load error" << endl;
		return -1;
	}
	gpu::GpuMat GpuGray, GpuObj;
	VideoCapture cap(1);
		while (cap.isOpened()){
			cap >> img;

			gpu::GpuMat GpuImg;
			GpuImg.upload(img);
			clock_t start = clock();
			gpu::cvtColor(GpuImg, GpuGray, CV_BGR2GRAY);
			gpu::equalizeHist(GpuGray, GpuGray);

			gpu::GpuMat GpuGrayRight;//右脸
			gpu::flip(GpuGray, GpuGrayRight, 1);

			Mat obj_host;// 把存储在GpuMat中的Rect存到Cpu Mat中  

			 //区别于CPU版,返回的人脸检测区域Rect存储在GpuMat中
			//正脸
			int detections_number_front = front_face_cascade.detectMultiScale(GpuGray, GpuObj);		
			// download only detected number of rectangles
			GpuObj.colRange(0, detections_number_front).download(obj_host);	
			Rect* faces = obj_host.ptr();
			//这里就比较清楚了,利用ptr,每次读一个Rect,共detections_number个检测区域
			for (int i = 0; i < detections_number_front; ++i)
				cv::rectangle(img, faces[i], Scalar(255),3);
			//左脸
			int detections_number_feft = left_face_cascade.detectMultiScale(GpuGray, GpuObj);
			// download only detected number of rectangles
			GpuObj.colRange(0, detections_number_feft).download(obj_host);
			faces = obj_host.ptr();
			for (int i = 0; i < detections_number_feft; ++i)
				cv::rectangle(img, faces[i], Scalar(0,0,255), 3);

			//右脸
			int detections_number_right = left_face_cascade.detectMultiScale(GpuGrayRight, GpuObj);
			// download only detected number of rectangles
			GpuObj.colRange(0, detections_number_right).download(obj_host);
			faces = obj_host.ptr();
			for (int i = 0; i < detections_number_right; ++i)
				cv::rectangle(img, Rect(img.cols - faces[i].x - faces[i].width, faces[i].y, faces[i].width, faces[i].height), Scalar(0, 255, 0), 3);


			clock_t end = clock();
			double duration = (end - start) / CLOCKS_PER_SEC;
			cout << "一帧耗时:" << duration << endl;
			imshow("Faces", img);
			char ch = waitKey(33);
			if (ch == 'q')
				break;
		}	
}

效果如下,完全的侧脸还是检测不到。

OpenCV人脸检测(正脸、左右侧脸)----GPU版使用_第1张图片

你可能感兴趣的:(Opencv)