OpenCV-Color Tracking

Fuction

  • An object that recognizes a particular color. And pick them out.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include "opencv2/opencv.hpp"
#include "iostream"

using namespace cv;
using namespace std;

int h_min=156;
int s_min=97;
int v_min=159;

int h_max=180;
int s_max=255;
int v_max=255; //修改这六个变量来更改需要识别的颜色

void main()
{
Mat srcImage=imread("Test.jpg"); //添加识别源。 支持图片或者视频流。
imshow("src",srcImage);
Mat tempImage=srcImage.clone();
cvtColor(srcImage,srcImage,CV_BGR2HSV);
Scalar hsv_min(h_min,s_min,v_min);
Scalar hsv_max(h_max,s_max,v_max);
Mat dstImage=Mat::zeros(srcImage.size(),CV_8U);
inRange(srcImage,hsv_min,hsv_max,dstImage);
Mat element=getStructuringElement(MORPH_RECT,Size(5,5));
morphologyEx(dstImage,dstImage,MORPH_ERODE,element,Point(-1,-1),1);
morphologyEx(dstImage,dstImage,MORPH_DILATE,element,Point(-1,-1),4);
imshow("dst",dstImage);
vector<vector<Point>>contours;
findContours(dstImage,contours,RETR_EXTERNAL,CHAIN_APPROX_NONE);
vector<Rect>rect(contours.size());
for(int i=0;i<contours.size();i++)
{
rect[i]=boundingRect(contours[i]);
int x=rect[i].x;
int y=rect[i].y;
int width=rect[i].width;
int height=rect[i].height;
rectangle(tempImage,Point(x,y),Point(x+width,y+height),Scalar(0,255,0),2);
}
imshow("result",tempImage);
waitKey(0);
}

Description

  • The OpenCV environment must be configured first.
  • Migration to the Android side using JNI may cause inaccuracies in the gamut. (My mobile phone model is Samsung S8)
  • VS2017 code construction.

Impression drawing

Comment