C++OpenCV图像处理(八)实时人脸检测案例

         对视频中的人脸进行人脸识别代码如下所示:

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());
		//解析结果
		for (int i = 0; i < detectionMat.rows; i++) {
			float confidence = detectionMat.at(i,2);
			if (confidence > 0.5) {
				//得到矩形的宽高
				int x1 = static_cast(detectionMat.at(i, 3) * frame.cols);
				int y1 = static_cast(detectionMat.at(i, 4) * frame.rows);
				int x2 = static_cast(detectionMat.at(i, 5) * frame.cols);
				int y2 = static_cast(detectionMat.at(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;
		}
	}

}

你可能感兴趣的:(c++opencv图像处理,计算机视觉-图像处理,opencv,计算机视觉,视频处理,人脸识别)