对视频中的人脸进行人脸识别代码如下所示:
void QuickDemo::face_detection_demo() {
std::string root_dir = "D:/opencv/opencv/sources/samples/dnn/ace_detector/";
//读取深度学习网络
dnn::Net net = dnn::readNetFromTensorflow(root_dir+"opencv_face_detector_uint8.pb",root_dir+"opencv_face_detector.pbtxt");
//网络模型加载好了我们需要加载视频
VideoCapture capture("D:/opencv/opencv/sources/samples/data/vtest.avi");
Mat frame;
while (true) {
capture.read(frame);
if (frame.empty()) {
break;
}
//To do something.....
Mat blob = dnn::blobFromImage(frame, 1.0, Size(300, 300), Scalar(104, 177, 123), false, false);
net.setInput(blob);
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);
int c = waitKey(1);
if (c == 27) {//退出
break;
}
}
}
使用OpenCV进行实时人脸识别

该代码演示了如何利用OpenCV的dnn模块从TensorFlow加载预训练模型,对视频进行人脸检测。通过读取视频帧,将图像转换为网络输入,然后前向传播获取人脸检测结果,并在检测到人脸时在视频帧上绘制矩形。
1843

被折叠的 条评论
为什么被折叠?



