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

前言

#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配置

转载于:https://my.oschina.net/mistylinux/blog/2965687

  • 1
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值