1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
|
#include "opencv2/imgcodecs.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/videoio.hpp" #include <opencv2/highgui.hpp> #include <opencv2/video.hpp> #include <iostream> #include <sstream> using namespace cv; using namespace std; Ptr<BackgroundSubtractorMOG2> pBackgroundKnn;
std::vector<cv::Rect> get_foreground_objects(cv::Mat scene, double scale, bool isFlag) { if (isFlag == false) { std::vector<cv::Rect> one_rect; cv::Rect whole; whole.x = whole.y = 0; whole.height = scene.rows; whole.width = scene.cols; one_rect.push_back(whole); return one_rect; } cv::Mat img; cv::resize(scene, img, cv::Size(0, 0), scale, scale); cv::Mat fgmask, fgimg, bgimg; pBackgroundKnn->apply(img, fgmask); cv::medianBlur(fgmask,fgmask, 5); cv::morphologyEx(fgmask, fgmask, cv::MORPH_CLOSE, cv::Mat::ones(15, 3, CV_8UC1)); std::vector<std::vector<cv::Point> > region_contours; cv::findContours(fgmask, region_contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0)); std::vector<cv::Rect> objects;
for (size_t i = 0; i != region_contours.size(); ++i) { cv::Rect rect = cv::boundingRect(region_contours[i]); rect.y += rect.height * 1 / 4; rect.height *= 3 / 4.0; rect.x /= scale; rect.width /= scale; rect.y /= scale; rect.height /= scale; if (rect.area() > scene.total() /400) { objects.push_back(rect); } } return objects; } int main(int argc, char* argv[]) { pBackgroundKnn = createBackgroundSubtractorMOG2(); VideoCapture capture("..\\images\\car.avi"); if(!capture.isOpened()) exit(EXIT_FAILURE); cv::Mat frame; std::vector<cv::Rect> regions; while (char(waitKey(1)) != 'q') { if(!capture.read(frame)) exit(EXIT_FAILURE); regions = get_foreground_objects(frame, 0.25, true); for (int i = 0; i < regions.size(); ++i) { cv::Mat region_img; region_img = frame(regions[i]); cv::imshow("region_img", region_img); } } return 0; }
|