Opencv基于颜色对象检测和跟踪

Opencv基于颜色对象检测和跟踪详细代码

#include   
#include   
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#include "opencv2/calib3d/calib3d.hpp"
#include 
#include 
#include 

#include 
#include 
#include
#include"glew.h"
#include
#include

//#include 

using namespace std;
using namespace cv;


//定义追踪目标的直方图
Rect roi;
void processFrame(Mat &mask, Rect &rect);

int main(int argc, char**argv)
{
	VideoCapture capture;
	capture.open("C:/Users/58214/Pictures/data/4.mp4");
	if (!capture.isOpened())
	{
		printf("could not load video data.....\n");
		return -1;
	}

	//创建窗口
	Mat frame,mask;
	//形态学结构元素--其中Size不适合选择过大,否则影响成像效果
	Mat kernel1 = getStructuringElement(MORPH_RECT, Size(3,3), Point(-1, -1));
	Mat kernel2 = getStructuringElement(MORPH_RECT, Size(5, 5), Point(-1, -1));

	namedWindow("input video", CV_WINDOW_AUTOSIZE);
	namedWindow("tracking video", CV_WINDOW_AUTOSIZE);

	//读取视频每一帧
	while (capture.read(frame))
	{
		//imshow("input video", frame);
		//颜色过滤(inRange过滤)找出目标 绿色--最低颜色要求,最高颜色要求
		inRange(frame, Scalar(0, 127, 0), Scalar(120, 255, 120), mask);
		//imshow("tracking video", mask);

		//形态学操作,开操作去除噪声
		morphologyEx(mask, mask, MORPH_OPEN, kernel1, Point(-1, -1),1);
		//imshow("tracking video", mask);
		//该步骤处理完,原来有的图像很多被去掉了,需要膨胀操作把正确画面补齐
		dilate(mask, mask, kernel2, Point(-1, -1), 4);
		imshow("tracking video", mask);

		//轮廓查找与位置标定
		processFrame(mask, roi);
		//定义直方图属性
		rectangle(frame, roi, Scalar(48, 122, 44), 3, 8, 0);
		imshow("input video", frame);

		char c = waitKey(100);
		if (c == 27)
		{
			break;
		}
	}

	capture.release();
	waitKey(0);
	return 0;
}

void processFrame(Mat &binary, Rect &rect)
{
	//定义轮廓数组
	vector<vector<Point>>contours;
	//层次
	vector<Vec4i>hireachy;
	//轮廓查找 最外层RETR_EXTERNAL
	findContours(binary, contours, hireachy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0, 0));
	//确定轮廓是否存在
	if (contours.size() > 0)//轮廓存在
	{
		double maxarea = 0.0;
		for (size_t t = 0; t < contours.size(); t++)
		{
			//面积 static_cast执行非多态的转换,用于代替C中通常的转换操作
			//如果原来轮廓面积是167.7,则转换成167
			double area = contourArea(contours[static_cast<int>(t)]);
			if (area > maxarea)
			{
				maxarea = area;
				//寻找到最大的外接矩形
				rect = boundingRect(contours[static_cast<int>(t)]);
			}
		}
	}
	else
	{
		rect.x = rect.y = rect.width = rect.height = 0;
	}
}

你可能感兴趣的:(Opencv,opencv)