#include <iostream>
#include <opencv2/objdetect/objdetect.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include "time.h"
#define MY_SIZE Size(90, 90)
using namespace cv;
using namespace std;
string getTime() //获取系统时间 字符串
{
time_t timep; //time_t类型
time(&timep);
char tmp[64]; //字符个数
strftime(tmp, sizeof(tmp), "%Y-%m-%d %H:%M:%S", localtime(&timep)); //时间格式可调
return tmp;
}
CascadeClassifier faceCascade; //人脸检测的类
CascadeClassifier eyeClassifier;
int main() {
if (!faceCascade.load("./haarcascade_frontalface_alt.xml")) //加载分类器,注意文件路径
{
cout << "导入haarcascade_frontalface_alt.xml时出错 !" << endl;
return 0;
}
if (!eyeClassifier.load("./haarcascade_eye.xml")) //把xml文档复制到现在用的文件夹下
{
cout << "导入haarcascade_eye.xml时出错 !" << endl;
return 0;
}
VideoCapture cap;
//cap.open(0); //打开摄像头
cap.open("33.mp4"); //打开视频
Mat img, imgGray;
vector < Rect > faces;
vector < Rect > eyes;
int c = 0;
if (!cap.isOpened()) {
return 1;
}
while (c != 27) //按键ESC的ASC码值.按下则退出
{
cap >> img; //读取帧
if (img.channels() == 3) //三通道红绿蓝,彩色图像
{
cvtColor(img, imgGray, CV_RGB2GRAY); //变成灰色图像
} else {
imgGray = img;
}
//Mat equalizedImg;
//equalizeHist(imgGray, imgGray);//直方图均衡化
eyeClassifier.detectMultiScale(imgGray, eyes, 1.4, 8,
0 | CV_HAAR_SCALE_IMAGE, Size(10, 10));
//1.4搜索窗口的比例系数,每次搜索依次扩大的百分比.
//8 如果组成检测目标的小矩形的个数和小于8都会被排除.
// 0或 CV_HAAR_DO_CANNY_PRUNING :将会使用Canny边缘检测来排除边缘过多或过少的区域
if (eyes.size() > 0) {
for (size_t i = 0; i < eyes.size(); i++) //eyeidx是啥,哪来的
{
rectangle(imgGray, eyes[i], Scalar(0, 0, 255)); //用矩形画出检测到的眼睛的位置(黑色)
}
}
faceCascade.detectMultiScale(imgGray, faces, 1.3, 6, 0, Size(20, 20)); //检测人脸
if (faces.size() > 0)
{
for (int i = 0; i < faces.size(); i++)
{
rectangle(imgGray, Point(faces[i].x, faces[i].y),Point(faces[i].x + faces[i].width,faces[i].y + faces[i].height),Scalar(0, 255, 0), 1, 8); //框出人脸位置
string time = getTime(); //获取系统日期
//如何显示中文
//putText(imgGray, "你好", Point(faces[i].x, faces[i].y),FONT_HERSHEY_SIMPLEX, 1, Scalar(255, 0, 225), 2, 8);
putText(imgGray, time, Point(faces[i].x, faces[i].y),FONT_HERSHEY_SIMPLEX, 1, Scalar(255, 0, 225), 2, 8); //坐标,字体类型,大小,颜色,粗细,线型.
Mat faceROI;
int count = 0;
string tmp_path;
faceROI = imgGray(faces[i]); //ROI部分为将要保存的图片
resize(faceROI, faceROI, MY_SIZE); //调整ROI图片大小到指定大小
//tmp_path = format("%d.jpg", count++);
// my_path = dir_name + tmp_path;
imwrite(time + "jt.jpg", faceROI); //保存采集到的图片到指定目录
}
}
/*faceCascade.detectMultiScale(imgGray, faces, 1.2, 6, 0 | CV_HAAR_SCALE_IMAGE, Size(0, 0));
for (size_t i = 0; i < faces.size(); i++)
{
rectangle(img, faces[i], Scalar(0, 255, 255)); //用矩形画出检测到脸部的位置(黄色)
}*/
namedWindow("Camera", 2); //可调整窗口
imshow("Camera", imgGray); //一帧一帧图片进行播放
c = waitKey(1); //延迟时间
}
/* //int k=0;
string time = getTime();//获取系统日期
if(c=32)
{
//Mat roi=imgGray[faces[i].x:faces[i].x + faces[i].width,faces[i].y:faces[i].y + faces[i].height];
imwrite(time+"jt.jpg",imgGray);//截图
}*/
return 0;
}
g++ -o camera camera.cpp `pkg-config --cflags --libs opencv`
./canera