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

#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/gpu/gpu.hpp>
#include<iostream>
#include<time.h>


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<Rect>();
			//这里就比较清楚了,利用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<Rect>();
			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<Rect>();
			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;
		}	
}

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

  • 1
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值