目標檢測方法
阿新 • • 發佈:2018-12-13
背景差分法:
主要參考: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); } }