0
点赞
收藏
分享

微信扫一扫

OpenCV/DNN 人脸(目标)检测


使用深度学习模块进行人脸检测
关于 opencv-python: ​​​使用OpenCV的dnn模块实时目标检测​​

头文件 ​​quick_opencv.h​​:声明类与公共函数

#pragma once
#include <opencv2\opencv.hpp>
using namespace cv;

class QuickDemo {
public:
...
void face_detect_Demo();
};

主函数调用该类的公共成员函数

#include <opencv2\opencv.hpp>
#include <quick_opencv.h>
#include <iostream>
using namespace cv;


int main(int argc, char** argv) {
Mat src = imread("D:\\Desktop\\pandas.jpg");
if (src.empty()) {
printf("Could not load images...\n");
return -1;
}
namedWindow("input", WINDOW_NORMAL);
imshow("input", src);

QuickDemo qk;

...
qk.face_detect_Demo();
waitKey(0);
destroyAllWindows();
return 0;
}

使用深度学习模块进行人脸检测

源文件 ​​quick_demo.cpp​​:实现类与公共函数

void QuickDemo::face_detect_Demo() {
std::string pb_path = "D:\\opencv\\sources\\samples\\dnn\\face_detector\\opencv_face_detector_uint8.pb";
std::string pbtxt_path = "D:\\opencv\\sources\\samples\\dnn\\face_detector\\opencv_face_detector.pbtxt";

cv::dnn::Net net = cv::dnn::readNetFromTensorflow(pb_path , pbtxt_path);
//VideoCapture captrue("D:\\opencv-c++\\images\\two_red_line.mp4"); // 推理视频
VideoCapture captrue(0);
Mat frame, hsv;
while (true)
{
captrue.read(frame);
if (frame.empty()) {
break;
}

Mat blob = dnn::blobFromImage(frame, 1.0, Size(300, 300), Scalar(104, 177, 123), false, false);
net.setInput(blob); //NCWH
Mat probs = net.forward(); //推理
Mat detectionMat(probs.size[2], probs.size[3], CV_32F, probs.ptr<float>());

// 解析结果
for (int i = 0; i < detectionMat.rows; i++) {
float confidence = detectionMat.at<float>(i, 2);
if (confidence > 0.5) {
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 box(x1, y1, x2 - x1, y2 - y1);
rectangle(frame, box, Scalar(0, 0, 255), 2, 8, 0);
}
}
imshow("frame", frame);
int c = waitKey(10);
if (c == 27) {
break;
}
}
}



举报

相关推荐

0 条评论