前言
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/face.hpp>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
using namespace cv;
using namespace cv::face;
static Mat norm_0_255(Mat src) {
Mat dst;
switch (src.channels())
{
case 1:
normalize(src, dst, 0, 255, NORM_MINMAX, CV_8UC1);
break;
case 3:
normalize(src, dst, 0, 255, NORM_MINMAX, CV_8UC3);
default:
src.copyTo(dst);
break;
}
return dst;
}
static void read_csv(const string& filename, vector<Mat>& images, vector<int>& labels, char separator = ':') {
ifstream file(filename.c_str(), ifstream::in);
if (!file) {
string errorMessage = "没有提供有效的输入文件, 请检查给定的文件名";
CV_Error(Error::StsBadArg, errorMessage);
}
string line, path, classLabel;
while (getline(file, line)) {
stringstream liness(line);
getline(liness, path, separator);
getline(liness, classLabel);
if (!path.empty() && !classLabel.empty()) {
images.push_back(imread(path));
labels.push_back(atoi(classLabel.c_str()));
}
}
}
#if 1
static void detectHumenFrontFace(Mat& rgb, Mat& gray) {
//加载分类器
std::string cascadeFile = "D:/this.Libraries/opencv4.0.dev.64/etc/haarcascades/haarcascade_frontalface_default.xml";
auto cascade = std::make_shared<CascadeClassifier>(cascadeFile);
if (cascade->empty()) {
cerr << "文件读取失败..." << endl;
return;
}
std::vector<cv::Rect> rects;
cascade->detectMultiScale(gray, rects);
rectangle(rgb,
Point(rects[0].x - 2, rects[0].y - 2),
Point(rects[0].x + rects[0].width, rects[0].y + rects[0].height),
Scalar(0, 255, 0));
}
int main(int argc, char* args[]) {
VideoCapture video;
video.open(0);
if (!video.isOpened()) {
cerr << "打开相机失败" << endl;
return 1;
}
while (true) {
Mat img;
video >> img;
Mat rgb;
cvtColor(img, rgb, COLOR_BGR2RGB);
Mat gray;
cvtColor(rgb, gray, COLOR_RGB2GRAY);
Mat graysmall2;
resize(gray, graysmall2, Size(gray.cols / 2, gray.rows / 2));
detectHumenFrontFace(rgb, gray);
imshow("image", rgb);
if (waitKey(10) == 'q')break;
}
return EXIT_SUCCESS;
}
#endif
效果图
IDE配置