opencv,C++实现图像中检测人脸

参考博客:https://blog.csdn.net/u012679707/article/details/80376969

1.搭建VS2015+opencv3.4.1环境

2.如果opencv3.4.1下搜索不到训练好的人脸检测模型,就是haarcascade_frontalface_alt.xml文件,手动下载xml文件

下载链接:

链接:https://pan.baidu.com/s/1VZwhNO8beb-PYtxITgPOug

提取码:rxv2

3.在项目目录下新建一个xml文件夹,将下载的xml文件放入到文件夹下

 

4.测试图片

 

5.实现代码,注意测试图片的路径

#include <opencv2/opencv.hpp>
#include <opencv.hpp>
#include <iostream>
#include <opencv2\face.hpp>

using namespace std;
using namespace cv;

int main(int argc, char *argv[])
{
	Mat img = imread("C:\\Users\\JSM-SQ\\Desktop\\face\\001.jpg");
	namedWindow("display");
	imshow("display", img);

	/*********************************** 1.加载人脸检测器  ******************************/
	// 建立级联分类器
	CascadeClassifier cascade;
	// 加载训练好的 人脸检测器(.xml)
	//注意路径问题,当前目录的上一个目录中的xml文件夹下
	const string path = "../xml/haarcascade_frontalface_alt2.xml";
	if (!cascade.load(path))
	{
		cout << "cascade load failed!\n";
	}

	//计时
	double t = 0;
	t = (double)getTickCount();
	/*********************************** 2.人脸检测 ******************************/
	vector<Rect> faces(0);
	cascade.detectMultiScale(img, faces, 1.1, 2, 0, Size(30, 30));

	cout << "detect face number is :" << faces.size() << endl;
	/********************************  3.显示人脸矩形框 ******************************/

	if (faces.size() > 0)
	{
		for (size_t i = 0; i < faces.size(); i++)
		{
			rectangle(img, faces[i], Scalar(150, 0, 0), 3, 8, 0);

		}
	}
	else cout << "未检测到人脸" << endl;

	t = (double)getTickCount() - t;  //getTickCount():  Returns the number of ticks per second.
	cout << "检测人脸用时:" << t * 1000 / getTickFrequency() << "ms (不计算加载模型的时间)" << endl;

	namedWindow("face_detect");
	imshow("face_detect", img);
	waitKey(0);
	
	destroyWindow("display");
	destroyWindow("face_detect");
	return 0;
}

6.结果

 

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值