1、软件工具
ubuntu18.4
openCV3.4.13
准备工作在其他文档
2、代码
#include <opencv2/core.hpp>
#include <opencv2/videoio.hpp>
#include <opencv2/highgui.hpp>
#include "opencv2/imgproc.hpp"
#include <opencv2/objdetect.hpp>
#include <iostream>
#include <stdio.h>
using namespace cv;
using namespace std;
int main(int, char**)
{
Mat Colorimg;
Mat Grayimg;
Mat Face;
vector<Rect> Allface;
vector< uchar > Jpgface;
//--- INITIALIZE VIDEOCAPTURE
VideoCapture cap;
// open the default camera using default API
// cap.open(0);
// OR advance usage: select any API backend
int deviceID = 0; // 0 = open default camera
int apiID = cv::CAP_ANY; // 0 = autodetect default API
// open selected camera using selected API
cap.open(deviceID, apiID); //打开相机
// check if we succeeded
if (!cap.isOpened()) {
cerr << "ERROR! Unable to open camera\n";
return -1;
}
//--- GRAB AND WRITE LOOP
cout << "Start grabbing" << endl
<< "Press any key to terminate" << endl;
CascadeClassifier Classifier("/usr/local/share/OpenCV/haarcascades/haarcascade_frontalface_alt2.xml");//分类器,人脸识别xml文件,训练的结果文件
for (;;)
{
// wait for a new frame from camera and store it into 'frame'
cap.read(Colorimg);
// check if we succeeded
if (Colorimg.empty()) {
cerr << "ERROR! blank frame grabbed\n";
break;
}
cvtColor(Colorimg,Grayimg,CV_BGR2GRAY); //灰度处理
equalizeHist(Grayimg,Grayimg); //权重处理
Classifier.detectMultiScale(Grayimg,Allface);//从输入的对象中检测出不同尺寸的对象,把检测到的人脸都保存下来
if(Allface.size())
{
rectangle(Colorimg,Allface[0],Scalar(255,255,0));//在人脸上画框
Face = Grayimg(Allface[0]); //把最大的那张人脸放入Face容器
imencode(".jpg",Face,Jpgface); //把图片转成.jpg格式
//到这儿可以结合智能云进行在线识别了
}
// show Camero and wait for a key with timeout long enough to show images
imshow("Camero", Colorimg);
if (waitKey(5) >= 0)
break;
}
// the camera will be deinitialized automatically in VideoCapture destructor
return 0;
}
3、有些代码未解释看其他文章