OpenCV讀入圖片序列進行HOG行人檢測並儲存為視訊

masikkk發表於2013-11-13

此程式是用OpenCV的預設SVM引數進行檢測,若圖片過大過多,處理起來會比較慢。


#include <stdio.h>
#include <iostream>
#include <fstream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/objdetect/objdetect.hpp>
#include <opencv2/ml/ml.hpp>

using namespace std;
using namespace cv;

int main()
{
	Mat src;
	string ImgName;//圖片檔名
	//ifstream fin("Seq4List.txt");//開啟圖片序列的檔案列表
	ifstream fin("subset.txt");

	namedWindow("ImageSeq",0);

	VideoWriter videoWriter;//視訊寫入器
	videoWriter.open("Seq6.avi", CV_FOURCC('x','v','I','D'),25,Size(1292,964));//注意若圖片尺寸與寫入器的尺寸不同的話可能失敗
	if(!videoWriter.isOpened()) cout<< "建立VideoWriter失敗"<<endl;

	HOGDescriptor people_detect_hog; //HOG特徵檢測器
	//採用預設的已經訓練好了的SVM係數作為檢測的模型
	people_detect_hog.setSVMDetector(HOGDescriptor::getDefaultPeopleDetector());
	
	while(getline(fin,ImgName))
	{
		cout<<"處理:"<<ImgName<<endl;
		string fullName = "D:\\TrackingTool-Matlab\\seq4\\" + ImgName;//加上路徑名,"\\"表示轉義字元"\"
		src = imread(fullName);

		vector<Rect> found, found_filtered; //矩形框陣列
		//對輸入的圖片進行多尺度行人檢測,檢測視窗移動步長為(8,8)
		people_detect_hog.detectMultiScale(src, found, 0, Size(8, 8), Size(32, 32), 1.05, 2);
		//找出所有沒有巢狀的矩形框r,並放入found_filtered中,如果有巢狀的話,則取外面最大的那個矩形框放入found_filtered中
		for(int i=0; i < found.size(); i++)
		{
			Rect r = found[i];
			int j=0;
			for(; j < found.size(); j++)
				if(j != i && (r & found[j]) == r)
					break;
			if( j == found.size())
				found_filtered.push_back(r);
		}

		//畫矩形框,因為hog檢測出的矩形框比實際人體框要稍微大些,所以這裡需要做一些調整
		for(int i=0; i<found_filtered.size(); i++)
		{
			Rect r = found_filtered[i];
			r.x += cvRound(r.width*0.1);
			r.width = cvRound(r.width*0.8);
			r.y += cvRound(r.height*0.07);
			r.height = cvRound(r.height*0.8);
			rectangle(src, r.tl(), r.br(), Scalar(0,255,0), 3);
		}

		videoWriter << src;//寫入一幀到檔案

		imshow("ImageSeq",src);
		waitKey(50);//注意:imshow之後必須有waitKey(),否則無法顯示影象
	}

	videoWriter.release();
	//system("pause");
	return 0;
}


效果:



原始碼下載,環境為VS2010 + OpenCV2.4.4

http://download.csdn.net/detail/masikkk/6547695

OpenCV讀入圖片序列進行HOG行人檢測並儲存為視訊

相關文章