@[TOC]基于opencv4.5的C++实现人脸检测模型测试

opencv的库文件里自带了训练好的dnn网络模型,python环境下人脸检测对于大多数人来说确实简单。但是本文环境:QT下的opoencv4.5.1(最新版了),C++。本博文也正是主要解决新版本opencv网络模型测试配置问题。
假设你已经配置好开发环境了。

首先,
找到H:\opencv\sources\samples\dnn\face_detector
记事本打开weights.meta4。把两个url标签下的文件下载下来。既得到两个文件:opencv_face_detector_uint8.pb (模型)
opencv_face_detector.pbtxt(模型配置参数)。
可将这俩文件存在原文件里

具体代码实现:

#include <opencv2/opencv.hpp>
#include <opencv2/core.hpp>
#include <opencv2/dnn.hpp>

void QuickDemo::face_dection_demo()
{
    VideoCapture capture(0); //调用摄像头
    Mat frame;
    string root_dir = "H:/opencv/sources/samples/dnn/face_detector/";
    dnn::Net net = dnn::readNetFromTensorflow(root_dir+"opencv_face_detector_uint8.pb",root_dir+"opencv_face_detector.pbtxt");//读取模型和配置参数

    while(true)
    {
        capture.read(frame);
        if(frame.empty() == 1)
        {
            break;
        }
        flip(frame,frame,1);

        //准备数据
        //1.0表示图像的色彩好保存在0到255之间;一些参数保存在models.yml中。两个false不需要rgb的转换也不需要剪切
        Mat blob = dnn::blobFromImage(frame,1.0,Size(300,300),Scalar(104,177,123),false,false);
       //blob 结果是NCHW。N是多少个,C通道数,H高度,W宽度

        net.setInput(blob);//将数据读入模型中
        Mat probs = net.forward(); //输出的第一个纬度是有多少图像,每个图像的index;
        //第二纬度,图像是第几个批次的,第几张图的;
        //第三个纬度表示有多少个框;第四个纬度,每个框有七个值,前两个是类型和dst,第三个是得分,最后四个是矩形的左上角和右上角
        Mat detectionMat(probs.size[2],probs.size[3],CV_32F,probs.ptr());
         //解析结果
        for(int i = 0; i < detectionMat.rows;i ++)
        {
            //得分
            float confidence = detectionMat.at<float>(i,2);
            if(confidence > 0.6)
            {
                int x1 = static_cast<int>(detectionMat.at<float>(i,3)*frame.cols);
                //再乘以一个宽度才能变为真实的
                int y1 = static_cast<int>(detectionMat.at<float>(i,4)*frame.rows);
                int x2 = static_cast<int>(detectionMat.at<float>(i,5)*frame.cols);
                int y2 = static_cast<int>(detectionMat.at<float>(i,6)*frame.rows);

                Rect rect(x1,y1,x2-x1,y2-y1);
                rectangle(frame,rect,Scalar(255,0,0),2,8,0);
            }
        }
        imshow("frame",frame);
        char c = waitKey(1); 
        if(c == '0')
        {
            break;
        }
    }
}

在main函数中。直接调用这个函数即可。
在这里插入图片描述

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐