opencv c++ 基于颜色的对象追踪

1、色彩空间转换:对应HSV格式图片的颜色区间

        opencv c++ 基于颜色的对象追踪_第1张图片

        通过API:inrange获取对应颜色的mask图像:参考 :(70条消息) opencv c++ 图像色彩空间转换 掩膜mask处理(12)_lucust的博客-CSDN博客

2、视频帧颜色分析提取

        a)查看帧图像颜色分布。

        通过插件image watch 来可以快速获取如下像素点坐标,像素值信息。

        

        b)获取正确的颜色range,从而获取mask

        c)对mask图像进行颜色分析。

3、代码示例,捕捉视频中的狗子

帧图像处理函数:

void QuickDemo::color_follow(Mat& image)
{
	Mat hsv, mask;
	cvtColor(image, hsv, COLOR_BGR2HSV);
	namedWindow("hsv", WINDOW_FREERATIO);
	imshow("hsv", hsv);
	inRange(hsv, Scalar(0, 23, 200), Scalar(10, 60, 240), mask);
	namedWindow("mask", WINDOW_FREERATIO);
	imshow("mask", mask);

	//细节处理
	Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3));
	morphologyEx(mask, mask, MORPH_OPEN, kernel);
	namedWindow("mask2", WINDOW_FREERATIO);
	imshow("mask2", mask);

	
	vector> contours;
	vector hierachy;
	findContours(mask, contours, hierachy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point());

	//多边形逼近,从而获取最大轮廓
	int height = mask.rows, width = mask.cols;
	double* maxarea = new double(-1);
	int* cindex = new int(-1);
	for (size_t t = 0; t < contours.size(); ++t) {
		//轮廓边框获取
		Rect box = boundingRect(contours[t]);
		if (box.width > width || box.height > height)
			continue;
		double area = contourArea(contours[t], false);
		double leng = arcLength(contours[t], true);
		if (area > *maxarea) {
			*maxarea = area;
			*cindex = t;
		}
	}

	//轮廓边框提取
	if (*cindex > 1) {
		RotatedRect rrt = minAreaRect(contours[*cindex]);
		ellipse(image, rrt, Scalar(0, 255, 0), 2, 8);
		circle(image, rrt.center, 4, Scalar(255, 0, 0));
	}
}

视频调用函数: 

void QuickDemo::video_read()
{
	VideoCapture capture("https://vd2.bdstatic.com/mda-nm5g3zgbjevd91w5/sc/cae_h264/1670325876387029950/mda-nm5g3zgbjevd91w5.mp4?v_from_s=hkapp-haokan-hbf&auth_key=1670417537-0-0-2ebdb5136e257b5fb1faddcd9b7f985d&bcevod_channel=searchbox_feed&cd=0&pd=1&pt=3&logid=1337063066&vid=10611913257713275693&abtest=104960_2&klogid=1337063066");
	if (capture.isOpened()) {
		cout << "ok!" << endl;
	}
	//获取合适帧率
	int fps = capture.get(CAP_PROP_FPS);
	int width = capture.get(CAP_PROP_FRAME_WIDTH);
	int height = capture.get(CAP_PROP_FRAME_HEIGHT);
	int num = capture.get(CAP_PROP_FRAME_COUNT);
	int type = capture.get(CAP_PROP_FOURCC);
	cout << "fps" << fps << endl;
	cout << "width" << width << endl;
	cout << "height" << height << endl;
	cout << "num" << num << endl;
	cout << "type" << type << endl;
	Mat frame;
	
	while (true)
	{
		//capture >> frame;//尽量不用
		//逐帧传入视频
		bool ret = capture.read(frame);
		if (!ret)break;
		

		color_follow(frame);
		imshow("frame", frame);
		char c = waitKey(fps);
		if (c == 27)
			break;


	}
	capture.release();
	
}

opencv c++ 基于颜色的对象追踪_第2张图片opencv c++ 基于颜色的对象追踪_第3张图片

 

 

你可能感兴趣的:(opencv,c++,opencv,c++,计算机视觉)