轮廓特征属性及应用(八)——颜色物体识别与跟踪
颜色空间转换——cvtColor()
颜色区间范围筛选——inRange()
先上ppt:
代码:1.滑动条HSV参数debug工具
///滑动条HSV参数debug工具
#include "opencv2/opencv.hpp"
using namespace cv;
Mat srcImg;
Mat hsvImg;
Mat dstImg;
int h_min = 35, s_min = 43, v_min = 46 ;//初始化为绿色的hsv取值范围
int h_max = 77, s_max = 255, v_max = 255;
void onChange(int,void* )
{
Scalar hsv_min = Scalar(h_min, s_min, v_min);
Scalar hsv_max = Scalar(h_max, s_max, v_max);
inRange(hsvImg, hsv_min, hsv_max, dstImg);//属于这个范围的会变成白色,其他为黑,存放在dstImg中
imshow("HSV-Filter", dstImg);
}
int main()
{
srcImg = imread("bgr.jpg", CV_LOAD_IMAGE_COLOR);
cvtColor(srcImg,hsvImg,CV_BGR2HSV);
dstImg = Mat::zeros(srcImg.size(),CV_8U);//dstImg需同srcImg相同大小,且类型为CV_8U
namedWindow("HSV-Filter",CV_WINDOW_NORMAL);
createTrackbar("h_min", "HSV-Filter", &h_min, 180, onChange, &dstImg);
createTrackbar("h_max", "HSV-Filter", &h_max, 180, onChange, &dstImg);
createTrackbar("s_min", "HSV-Filter", &s_min, 255, onChange, &dstImg);
createTrackbar("s_max", "HSV-Filter", &s_max, 255, onChange, &dstImg);
createTrackbar("v_min", "HSV-Filter", &v_min, 255, onChange, &dstImg);
createTrackbar("v_max", "HSV-Filter", &v_max, 255, onChange, &dstImg);
imshow("srcImg", srcImg);
onChange(0,0);//使得一开始就显示"HSV-Filter"窗口
waitKey(0);
return 0;
}
运行结果:
代码:2.视频中颜色识别与跟踪
///视频中颜色识别与跟踪
#include "opencv2/opencv.hpp"
using namespace cv;
#include ;
using namespace std;
int main()
{
//1.定义VideoCapture类video读取视频
VideoCapture video("1.mp4");
if (!video.isOpened())//VideoCapture类的异常检测
{
cout << "video open error!" << endl;
return 0;
}
double height = video.get(CV_CAP_PROP_FRAME_HEIGHT);//获得VideoCapture类中的信息
double width = video.get(CV_CAP_PROP_FRAME_WIDTH);
double count = video.get(CV_CAP_PROP_FRAME_COUNT);
double FPS = video.get(CV_CAP_PROP_FPS);
//2.遍历帧
Mat frame;
for (int i = 0; i < count; i++)
{
video >> frame;
if (frame.empty())//帧的异常检测
{
cout << "frame empty" << endl;
return 0;
}
//3.颜色筛选
Mat hsvImg;
cvtColor(frame, hsvImg, CV_BGR2HSV);
int h_min = 35, s_min = 108, v_min = 140;//筛选出绿色区域的值,由debug工具调试得来
int h_max = 77, s_max = 255, v_max = 255;
Scalar hsv_min = Scalar(h_min, s_min, v_min);
Scalar hsv_max = Scalar(h_max, s_max, v_max);
Mat dstImg = Mat::zeros(frame.size(), CV_8U);//dstImg需同frame相同大小,且类型为CV_8U
inRange(hsvImg, hsv_min, hsv_max, dstImg);//属于这个范围的会变成白色,其他为黑,存放在dstImg中
medianBlur(dstImg, dstImg, 5);//中值滤波去除噪声
imshow("dstImg", dstImg);//显示颜色删选结果
//4.查找轮廓
vector> contours;
findContours(dstImg, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
//5.查找正外接矩形
vector boundRect(contours.size());
boundRect[0] = boundingRect(contours[0]);
//6.绘制正外接矩形并添加文字
rectangle(frame, boundRect[0], Scalar(0, 255, 0), 1, 8);
putText(frame, "Green", Point(boundRect[0].x, boundRect[0].y), CV_FONT_HERSHEY_PLAIN, 1, Scalar(0, 255, 0), 1, 8);
//7.显示每一帧,并按原FPS显示
imshow("frame", frame);
if (waitKey(1000 / FPS) == 27)//经过换算,每(1000/Fps)显示一帧,与原视频FPS一样。且Esc控制跳出循环退出
{
cout << "ESC退出" << endl;
}
}
return 0;
}
运行结果: