本博文IDE为vs2013

OpenCV2.49

话不多说,先看视频演示(20S演示):

例如以下:

https://v.youku.com/v_show/id_XMjYzMzkxMTYyMA==.html?spm=a2h0w.8278793.2736843.4#paction

程序截图例如以下:

OpenCV人脸检測(完整源代码+思路)-LMLPHP

怎样来用OpenCV来实现能。

以下给出OpenCV实现人脸检測的一般步骤:

1.载入人脸检測器

2.开启摄像头

3.对图片进行灰度处理(事实上能够不处理,上图中原图的标题栏就是未进行灰度处理进行的检測,这里的灰度是为下节人脸识别打基础)

4.对图片进行直方图均衡化(事实上能够不处理。上图中原图的标题栏就是未进行灰度处理进行的检測和灰度图是为进行均衡化识别,这里的均衡化是为下节人脸识别打基础)

5.人脸检測

总结下,假设单单仅仅要人脸检測,能够的步骤是1,2,5

本博客把1。2。5,

1。2,3,5

1,2,3,4,5

都演示了出来。

以下是完整的代码。本代码还有大量凝视,在此不再详细说明哪个函数有什么用。

以下上源代码:

#include <opencv.hpp>
#include <opencv2/core/core.hpp>
#include <iostream> using namespace cv; void Pic2Gray(Mat camerFrame,Mat &gray)
{
//普通台式机3通道BGR,移动设备为4通道
if (camerFrame.channels() == 3)
{
cvtColor(camerFrame, gray, CV_BGR2GRAY);
}
else if (camerFrame.channels() == 4)
{
cvtColor(camerFrame, gray, CV_BGRA2GRAY);
}
else
gray = camerFrame;
} int main()
{
//载入Haar或LBP对象或人脸检測器
CascadeClassifier faceDetector;
std::string faceCascadeFilename = "haarcascade_frontalface_default.xml"; //友好错误信息提示
try{
faceDetector.load(faceCascadeFilename);
}
catch (cv::Exception e){}
if (faceDetector.empty())
{
std::cerr << "脸部检測器不能载入 (";
std::cerr << faceCascadeFilename << ")!" << std::endl;
exit(1);
} //打开摄像头
VideoCapture camera(0);
while (true)
{
Mat camerFrame;
camera >> camerFrame;
if (camerFrame.empty())
{
std::cerr << "无法获取摄像头图像" << std::endl;
getchar();
exit(1);
}
Mat displayedFrame(camerFrame.size(),CV_8UC3); //人脸检測仅仅试用于灰度图像
Mat gray;
Pic2Gray(camerFrame, gray); //直方图均匀化(改善图像的对照度和亮度)
Mat equalizedImg;
equalizeHist(gray, equalizedImg); //人脸检測用Cascade Classifier::detectMultiScale来进行人脸检測 int flags = CASCADE_FIND_BIGGEST_OBJECT|CASCADE_DO_ROUGH_SEARCH; //仅仅检測脸最大的人
//int flags = CASCADE_SCALE_IMAGE; //检測多个人
Size minFeatureSize(30, 30);
float searchScaleFactor = 1.1f;
int minNeighbors = 4;
std::vector<Rect> faces;
faceDetector.detectMultiScale(equalizedImg, faces, searchScaleFactor, minNeighbors, flags, minFeatureSize); //画矩形框
cv::Mat face;
cv::Point text_lb;
for (size_t i = 0; i < faces.size(); i++)
{
if (faces[i].height > 0 && faces[i].width > 0)
{
face = gray(faces[i]);
text_lb = cv::Point(faces[i].x, faces[i].y);
cv::rectangle(equalizedImg, faces[i], cv::Scalar(255, 0, 0), 1, 8, 0);
cv::rectangle(gray, faces[i], cv::Scalar(255, 0, 0), 1, 8, 0);
cv::rectangle(camerFrame, faces[i], cv::Scalar(255, 0, 0), 1, 8, 0);
}
} imshow("直方图均匀化", equalizedImg);
imshow("灰度化", gray);
imshow("原图", camerFrame); waitKey(20);
} getchar();
return 0;
}
04-16 07:56