OpenCV 简单识别人脸的小程序

#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/face.hpp>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>

using namespace cv;
using namespace std;
using namespace cv::face;

static void detecHumenFrontFace(Mat& rgb, Mat& gray)
{
	string cascadeFile = "D:/environment/opencv4.1.1/build/etc/haarcascades/haarcascade_frontalface_alt2.xml";
	
	CascadeClassifier cascade;

	cascade.load(cascadeFile);

	if (cascade.empty())
	{
		cerr << "Open File error!" << endl;

		return;
	}

	vector<cv::Rect> rects;

	cascade.detectMultiScale(gray, rects, 1.1, 3, 0 | CASCADE_SCALE_IMAGE, Size(30, 30)); //追踪效果
	
	if (rects.size() > 0)
	{
		cout << "检测到人脸!" << endl;

		for (auto it = rects.begin(); it != rects.end(); it++)
		{
			rectangle(rgb,
				Point((*it).x, (*it).y),
				Point((*it).x + (*it).width, (*it).y + (*it).height),
				Scalar(0, 255, 0), 2);
		}
	}
	
}


int main()
{
	VideoCapture video;
	
	//video = VideoCapture(CAP_DSHOW);

	//cv::String url = "http://admin:admin@192.168.0.109:8081";

	video.open(0);
	
	if (!video.isOpened())
	{
		cout << "Open Video Failed!" << endl;
		
		return -1;
	}

	video.set(CAP_PROP_FOURCC, VideoWriter::fourcc('M', 'J', 'P', 'G'));
	video.set(CAP_PROP_FPS,30);
	video.set(CAP_PROP_FRAME_WIDTH, 640);
	video.set(CAP_PROP_FRAME_HEIGHT, 480);

	Mat img, rgb, gray, graysmall2;

	double fps, t;

	char string[10];

	while (1)
	{
		t = (double)getTickCount();

		video >> img;

		t = ((double)getTickCount() - t) / getTickFrequency();

		fps = 1.0 / t;

		sprintf_s(string, "%.2f", fps);

		std::string fpsString("FPS:");

		fpsString += string;
			
		if (!video.read(img)) break;

		cvtColor(img, rgb, COLOR_BGR2RGB);

		cvtColor(rgb, gray, COLOR_RGB2GRAY);

		resize(gray, graysmall2, Size(gray.cols / 2, gray.rows / 2));

		detecHumenFrontFace(img, gray);//detecHumenFrontFace(rgb, gray);

		putText(img, fpsString, Point(5, 20), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 0, 255));

		imshow("Video", img);//imshow("Video", rgb);

		if (waitKey(10) >= 0 )
		{
			break;
		}
	}

	cv::destroyAllWindows();

	video.release();

	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值