opencv C++实现调用摄像头动态识别人脸

前言
此章是https://my.oschina.net/mistylinux/blog/2963544 的C++版
研究项目:https://gitee.com/develops

#include
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/face.hpp>

#include
#include
#include
#include
#include

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& images, vector& 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(cascadeFile);
if (cascade->empty()) {
cerr << “文件读取失败…” << endl;
return;
}
std::vectorcv::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配置

发布了8 篇原创文章 · 获赞 3 · 访问量 1921

猜你喜欢

转载自blog.csdn.net/weixin_44017727/article/details/103349425
今日推荐