OpenCV人臉檢測(完整源代碼+思路)

本博文IDE爲vs2013html

OpenCV2.49ios


話很少說,先看視頻演示(20S演示):ide

例如如下:函數

https://v.youku.com/v_show/id_XMjYzMzkxMTYyMA==.html?spm=a2h0w.8278793.2736843.4#paction
url


程序截圖例如如下:spa



怎樣來用OpenCV來實現能。.net

如下給出OpenCV實現人臉檢測的通常步驟:code

1.載入人臉檢測器視頻

2.開啓攝像頭xml

3.對圖片進行灰度處理(事實上可以不處理,上圖中原圖的標題欄就是未進行灰度處理進行的檢測,這裏的灰度是爲下節人臉識別打基礎)

4.對圖片進行直方圖均衡化(事實上可以不處理。上圖中原圖的標題欄就是未進行灰度處理進行的檢測和灰度圖是爲進行均衡化識別,這裏的均衡化是爲下節人臉識別打基礎)

5.人臉檢測


總結下,假設單單僅僅要人臉檢測,可以的步驟是1,2,5

本博客把1。2。5,

1。2,3,5

1,2,3,4,5

都演示了出來。

如下是完整的代碼。本代碼還有大量凝視,在此再也不詳細說明哪一個函數有什麼用。

如下上源代碼:

#include <opencv.hpp>
#include <opencv2/core/core.hpp>
#include <iostream>

using namespace cv;

void Pic2Gray(Mat camerFrame,Mat &gray)
{
	//普通臺式機3通道BGR,移動設備爲4通道
	if (camerFrame.channels() == 3)
	{
		cvtColor(camerFrame, gray, CV_BGR2GRAY);
	}
	else if (camerFrame.channels() == 4)
	{
		cvtColor(camerFrame, gray, CV_BGRA2GRAY);
	}
	else
		gray = camerFrame;
}


int main()
{
	//載入Haar或LBP對象或人臉檢測器
	CascadeClassifier faceDetector;
	std::string faceCascadeFilename = "haarcascade_frontalface_default.xml";

	//友好錯誤信息提示
	try{
		faceDetector.load(faceCascadeFilename);
	}
	catch (cv::Exception e){}
	if (faceDetector.empty())
	{
		std::cerr << "臉部檢測器不能載入 (";
		std::cerr << faceCascadeFilename << ")!" << std::endl;
		exit(1);
	}

	//打開攝像頭
	VideoCapture camera(0);
	while (true)
	{
		Mat camerFrame;
		camera >> camerFrame;
		if (camerFrame.empty())
		{
			std::cerr << "沒法獲取攝像頭圖像" << std::endl;
			getchar();
			exit(1);
		}
		Mat displayedFrame(camerFrame.size(),CV_8UC3);


		//人臉檢測僅僅試用於灰度圖像
		Mat gray;
		Pic2Gray(camerFrame, gray);



		//直方圖均勻化(改善圖像的對照度和亮度)
		Mat equalizedImg;
		equalizeHist(gray, equalizedImg);

		//人臉檢測用Cascade Classifier::detectMultiScale來進行人臉檢測

		int flags = CASCADE_FIND_BIGGEST_OBJECT|CASCADE_DO_ROUGH_SEARCH;	//僅僅檢測臉最大的人
		//int flags = CASCADE_SCALE_IMAGE;	//檢測多我的
		Size minFeatureSize(30, 30);
		float searchScaleFactor = 1.1f;
		int minNeighbors = 4;
		std::vector<Rect> faces;
		faceDetector.detectMultiScale(equalizedImg, faces, searchScaleFactor, minNeighbors, flags, minFeatureSize);

		//畫矩形框
		cv::Mat face;
		cv::Point text_lb;
		for (size_t i = 0; i < faces.size(); i++)
		{
			if (faces[i].height > 0 && faces[i].width > 0)
			{
				face = gray(faces[i]);
				text_lb = cv::Point(faces[i].x, faces[i].y);
				cv::rectangle(equalizedImg, faces[i], cv::Scalar(255, 0, 0), 1, 8, 0);
				cv::rectangle(gray, faces[i], cv::Scalar(255, 0, 0), 1, 8, 0);
				cv::rectangle(camerFrame, faces[i], cv::Scalar(255, 0, 0), 1, 8, 0);
			}
		}


		imshow("直方圖均勻化", equalizedImg);
		imshow("灰度化", gray);
		imshow("原圖", camerFrame);

		waitKey(20);
	}

	getchar();
	return 0;
}
相關文章
相關標籤/搜索