目标检测方法

背景差分法:

主要参考:OpenCV2.4use createBackgroundSubtractorMOG,OpenCV3.0背景差分法示例。直接调用类的效果并不好,还没我自己写的背景差分好用,主要是阈值的问题,调用类好像不能更改阈值。

调用类:

void main()
{
	Mat frame; //current frame
	Mat fgMaskMOG2; //fg mask fg mask generated by MOG2 method
	Ptr<BackgroundSubtractor> pMOG2; //MOG2 Background subtractor
	char keyboard; //input from keyboard
		
	namedWindow("Frame");
	namedWindow("FG Mask MOG 2");
	//create Background Subtractor objects
	pMOG2 = new BackgroundSubtractorMOG2();  //MOG2 approach


	VideoCapture capture("VID.mp4");
	if (!capture.isOpened()){
		//error in opening the video input
		cerr << "Unable to open video file: " <<"VID.mp4"<< endl;
		exit(EXIT_FAILURE);
	}
	//read input data. ESC or 'q' for quitting
	keyboard = 0;
	while (keyboard != 'q' && keyboard != 27){
		//read the current frame
		if (!capture.read(frame)) {
			cerr << "Unable to read next frame." << endl;
			cerr << "Exiting..." << endl;
			exit(EXIT_FAILURE);
		}
		//update the background model
		pMOG2->operator()(frame, fgMaskMOG2);
		//get the frame number and write it on the current frame
		stringstream ss;
		rectangle(frame, cv::Point(10, 2), cv::Point(100, 20),
			cv::Scalar(255, 255, 255), -1);
		ss << capture.get(CV_CAP_PROP_POS_FRAMES);
		string frameNumberString = ss.str();
		putText(frame, frameNumberString.c_str(), cv::Point(15, 15),
			FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 0));
		//show the current frame and the fg masks
		imshow("Frame", frame);
		imshow("FG Mask MOG 2", fgMaskMOG2);
		//get the input from the keyboard
		keyboard = (char)waitKey(30);
	}
	//delete capture object
	capture.release();
	
}

自定义阈值:

void main()
{
	VideoCapture capture("VID.mp4");
	Mat tempframe, currentframe, previousframe;
	Mat frame;
	int framenum = 0;
	while (1)
	{
		capture >> frame;
		tempframe = frame;
		framenum++;
		if (!capture.read(frame)) {
			cerr << "Unable to read next frame." << endl;
			cerr << "Exiting..." << endl;
			waitKey(0);
			exit(EXIT_FAILURE);
		}
		if (framenum == 1)
		{
			cvtColor(tempframe,previousframe,CV_BGR2GRAY);
		}
		if (framenum > 1)
		{
			cvtColor(tempframe, currentframe, CV_BGR2GRAY);
			absdiff(currentframe, previousframe, currentframe);
			threshold(currentframe, currentframe, 100, 255.0, CV_THRESH_BINARY);//
			dilate(currentframe, currentframe, Mat());//膨胀
			erode(currentframe, currentframe, Mat());//腐蚀
			imshow("camera", tempframe);
			imshow("moving area", currentframe);

		}
		waitKey(33);
	}

}

猜你喜欢

转载自blog.csdn.net/qq_40250862/article/details/82956099