适用场景
根据画面中对象的颜色进行识别追踪,此种方法有一定局限性,首先目标颜色一定要与其他背景有着非常明显的区分,光照条件不经常变化不会导致对象颜色的突变。
处理思路
- 利用颜色范围过滤
- 标注与测量
操作步骤
- inRange过滤
- 形态学操作提取
- 轮廓查找
- 外接矩形获取
- 位置标定
代码
#include <opencv2/opencv.hpp>
#include <iostream>
#include <math.h>
using namespace std;
using namespace cv;
int main(void)
{
Mat frame,mask,dst;
VideoCapture cap;
namedWindow("inputvideo",0);
resizeWindow("inputvideo",272,480);
namedWindow("track mask",0);
resizeWindow("track mask",272,480);
namedWindow("dst",0);
resizeWindow("dst",272,480);
if(!cap.open("/work/opencv_video/color_check.mp4"))
{
cout << "video is err" << endl;
return -1;
}
//开操作 掩膜
Mat kernel = getStructuringElement(MORPH_RECT,Size(3,3));
Rect rect;
while(true)
{
cap>>frame;
if(frame.empty())
{
break;
}
imshow("inputvideo",frame);
dst = frame.clone();
cvtColor(frame,frame,COLOR_BGR2HSV);
inRange(frame,Scalar(35,43,46),Scalar(77,255,255),mask);
//开操作 消除噪点
morphologyEx(mask,mask,MORPH_OPEN,kernel);
imshow("track mask",mask);
vector<vector<Point>> contours;
findContours(mask,contours,RETR_TREE,CHAIN_APPROX_SIMPLE);
for(size_t i=0;i<contours.size();i++)
{
rect = boundingRect(contours[i]);
if(rect.width >10 && rect.height >10 )
{
rectangle(dst,rect,Scalar(0xF7,0x09,0xF7),3);
}
}
imshow("dst",dst);
if(waitKey(100)>0)
break;
}
cap.release();
destroyAllWindows();
return 0;
}