opencv实现摄像头实时人脸检测

昨天晚上在大神的带领下领略了opencv的风采,搞得我都想换行搞机器视觉了,这个库真的太好用了,用很简单的代码就能写出自己的人脸检测程序。

我把程序直接贴出来,大家一次讨论学习,平台是opencv2.4.10 + win10 + VS2013

#include<iostream>
#include<stdio.h>

#include<opencv2/opencv.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
#include "opencv2/core/core.hpp"
using namespace cv;
using namespace std;

#define W 1920
#define H 1080

string face_cascade_name = "E:/code/Myprojects/ConsoleApplication1/ConsoleApplication1/haarcascade_frontalface_alt2.xml";
CascadeClassifier face_cascade;
int facesnum = 0;
void DectectorAndDis(Mat frame)
{
	Mat face_gray = Mat::zeros(H, W, CV_8UC3);
	vector<Rect> faces;
	cvtColor(frame, face_gray, CV_BGR2GRAY);//RGB转化为灰度
	equalizeHist(face_gray, face_gray);//直方图均衡化
	face_cascade.detectMultiScale(face_gray, faces, 1.75, 2, 0 | CV_HAAR_SCALE_IMAGE, Size(30, 30));
	for (int i = 0; i < faces.size(); i++){
		Point CvBox2D(int(faces[i].x + faces[i].width*0.5), int(faces[i].y + faces[i].height*0.5));
		ellipse(frame, CvBox2D, Size(int(faces[i].width*0.5), int(faces[i].height*0.5)), 0, 0, 360, Scalar(255, 0, 0), 4, 8, 0);	
	}
	if( facesnum != faces.size())
	{
		cout << "人脸数:" << faces.size() << endl;
		facesnum = faces.size();
	}
	
	imshow("读取视频", frame);
}
int main(int argc, char* argv[])
{
	//cv::Mat test  = cv::imread("E:/code/Myprojects/ConsoleApplication1/test.jpg",0);
	//cv::Mat test1;
	//resize(test, test, Size(W, H));
	//imshow("test", test);
	//cv::Canny(test, test1, 1, 3, 3);
	//imshow("test1", test1);
	//test.convertTo(test, CV_32SC1);
	
	VideoCapture capture;	
	capture.open(0);

	Mat frame = Mat::zeros(H, W, CV_8UC3);
	Mat frameaftcanny = Mat::zeros(H, W, CV_8UC3);
	face_cascade.load(face_cascade_name);
	while (1)
	{
		capture >> frame;

		//cv::Canny(frame, frameaftcanny, 100, 300, 3);
		//imshow("边缘检测", frameaftcanny);
		DectectorAndDis(frame);
		cv::waitKey(50);
	}

	return 0;
}

猜你喜欢

转载自blog.csdn.net/u010993820/article/details/71310496
今日推荐