天天看点

opencv 视频中的人脸打码

思想很简单,就是调用摄像头,获取图像帧,将图像帧放入opencv带的人脸识别库检测出窗口。最后使用滤波函数对检测窗口进行模糊操作。再拷贝回原图。完成

#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/photo.hpp"
#include <iostream>
#include <string>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/objdetect.hpp>
#include <opencv2\imgproc\types_c.h>
//#include <opencv2/gpu/gpu.hpp>
using namespace cv;
using namespace std;
string xmlPath = "E:/opencv_learn/opencv_test/haarcascade_frontalface_default.xml";
//xmlpath 字符串记录那个.xml文件的路径
void detectAndDisplay(Mat image);
int main(int argc, char** argv)
{
	string path = "E:/opencv_learn/opencv_test/1.jpg";//以检测图片1.jpg为例
	Mat image = imread(path, -1);

	CascadeClassifier a;     //创建脸部对象
	if (!a.load(xmlPath))     //如果读取文件不出错,则检测人脸
	{
		cout << "无法加载xml文件" << endl;
		return 0;
	}
	VideoCapture cam(0);
	Mat frame;
	cam.set(CAP_PROP_FOURCC, 'GPJM');
	cam.set(CAP_PROP_FRAME_WIDTH, 1920);
	cam.set(CAP_PROP_FRAME_HEIGHT, 1080);
	cam >> frame;
	Rect roi(250, 250, image.cols, image.rows);
	for (; waitKey(10) != 27; cam >> frame) { //esc 的ascall码是27;
		detectAndDisplay(frame);
		//imshow("frame", frame);
	
	}
	//detectAndDisplay(image);// 检测人脸
	return 0;

}

void detectAndDisplay(Mat image)
{
	CascadeClassifier ccf;      //创建脸部对象
	ccf.load(xmlPath);           //导入opencv自带检测的文件
	vector<Rect> faces;
	Mat gray;
	//image *= 1. / 255;
	cvtColor(image, gray, CV_BGR2GRAY);
	equalizeHist(gray, gray);
	ccf.detectMultiScale(gray, faces, 1.1, 3, 0, Size(50, 50), Size(500, 500));
	Mat image1;
	
	for (size_t i = 0; i < faces.size(); i++)
	{	
		cout << faces[i].width <<' '<<faces[i].height << endl;
		Point center(faces[i].x + faces[i].width, faces[i].y + faces[i].height);
		if (faces[i].width * faces[i].height < 10000) continue; #去除过小框
		rectangle(image, Point(faces[i].x, faces[i].y), center, Scalar(0, 0, 255), 2, 8);
		image1 = image(Rect(faces[i].x, faces[i].y, faces[i].width, faces[i].height));
		boxFilter(image1, image1, -1, Size(77,77));
		image1.copyTo(image(Rect(faces[i].x, faces[i].y, faces[i].width, faces[i].height)));
		imshow("1", image);
		//waitKey(0);
	}
	

}
           

效果图,人脸检测对正脸准确率高,侧脸很难识别。

opencv 视频中的人脸打码

继续阅读