时间:2021-04-26 11:03:59 | 栏目:C代码 | 点击:次
使用opencv提供的背景去除算法(KNN或高斯混合模型GMM)去除背景,然后将获取的目标二值化后通过筛选目标轮廓获得目标位置。
#include<opencv2/opencv.hpp> using namespace cv; //基于移动对象的轮廓的跟踪 int main() { Mat frame; bool flag = true; VideoCapture capture; capture.open(0); if (!capture.isOpened()) { printf("can not open ......\n"); return -1; } namedWindow("mask", WINDOW_AUTOSIZE); namedWindow("output", WINDOW_AUTOSIZE); Ptr<BackgroundSubtractor> pKNN = createBackgroundSubtractorKNN(); //Ptr<BackgroundSubtractor> pMOG2 = createBackgroundSubtractorMOG2(); while (capture.read(frame)) { Mat KNNMask; std::vector<std::vector<Point>>contours; pKNN->apply(frame, KNNMask); //(*pMOG2).apply(frame, mogMask); threshold(KNNMask, KNNMask, 100, 255, THRESH_BINARY); Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3)); morphologyEx(KNNMask, KNNMask, MORPH_OPEN, kernel, Point(-1,-1)); findContours(KNNMask, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0,0)); for (int i = 0; i < contours.size(); i++) { //轮廓面积 double area = contourArea(contours[i]); //轮廓外接矩阵 Rect rect = boundingRect(contours[i]); if (area < 500 || rect.width < 50 || rect.height < 50) continue; rectangle(frame, rect, Scalar(0,255,255),2); putText(frame, "Target", Point(rect.x, rect.y), CV_FONT_NORMAL, FONT_HERSHEY_PLAIN, Scalar(0,255,0),2,8); } imshow("mask",KNNMask); imshow("output",frame); waitKey(1); } return 0; }