threshold 方法是通过遍历灰度图中点,将图像信息二值化,处理过后的图片只有二种色值。
其函数原型如下:
double threshold(InputArray src, OutputArray dst, double thresh, double maxval, int type)
参数信息:
第一个参数,InputArray类型的src,输入数组,填单通道 , 8或32位浮点类型的Mat即可。
第二个参数,OutputArray类型的dst,函数调用后的运算结果存在这里,即这个参数用于存放输出结果,且和第一个参数中的Mat变量有一样的尺寸和类型。
第三个参数,double类型的thresh,阈值的具体值。
第四个参数,double类型的maxval,当第五个参数阈值类型type取 THRESH_BINARY 或THRESH_BINARY_INV阈值类型时的最大值.
第五个参数,int类型的type,阈值类型,。
其它参数很好理解,我们来看看第五个参数,第五参数有以下几种类型
0: THRESH_BINARY 当前点值大于阈值时,取Maxval,也就是第四个参数,下面再不说明,否则设置为0
1: THRESH_BINARY_INV 当前点值大于阈值时,设置为0,否则设置为Maxval
2: THRESH_TRUNC 当前点值大于阈值时,设置为阈值,否则不改变
3: THRESH_TOZERO 当前点值大于阈值时,不改变,否则设置为0
4: THRESH_TOZERO_INV 当前点值大于阈值时,设置为0,否则不改变
色环图中这个区间即BGR(0,128,255)到BGR(255,0,213),则B、G、R这三个通道的范围分别为0-255,0-128,213-255。因此阈值下限lowerb=Scalar(0,0,213),阈值上限upperb=Scalar(255,128,255)
#include
#include
using namespace std;
using namespace cv;
int main()
{
Mat src,src_gary,dst;
src = imread("C:\\Users\\LiJianTao\\Pictures\\QQ图片20210605211657.jpg");
cvtColor(src, src_gary, CV_BGR2GRAY);
threshold(src_gary, dst, 125, 255, THRESH_BINARY);
imshow("src", src);
imshow("src_gary output", src_gary);
imshow("dst output", dst);
waitKey(0);
return 0;
}
#include
#include
#define DEBUG_ONE
using namespace cv;
using namespace std;
int main()
{
VideoCapture cap(0); //capture the video from web cam
if (!cap.isOpened()) // if not success, exit program
{
cout << "Cannot open the web cam" << endl;
return -1;
}
int num = 0;
int r_num = 0, b_num = 0;
int red_area = 0, blue_area = 0;
while (true)
{
Mat frame;
cap >> frame;
Mat dst, dst1;
vector<Mat>channls;
split(frame, channls);
dst = channls.at(2) - channls.at(0);//红
dst1 = channls.at(0) - channls.at(2);
threshold(dst, dst, 125, 255, THRESH_BINARY);
threshold(dst1, dst1, 125, 255, THRESH_BINARY);
imshow("red threshold", dst);
imshow("blue threshold", dst1);
vector<vector<Point>>contours_r;
vector<vector<Point>>contours_b;
vector<Vec4i>hierarchy;
vector<Vec4i>hierarchyb;
//找轮廓
findContours(dst, contours_r, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
findContours(dst1, contours_b, hierarchyb, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
#ifndef DEBUG_ONE
if (contours_r.size() > 0 && contours_b.size() > 0)//只要有存在面积就退出
{
break;
}
#endif
//延时检测
for (int red_num = 0; red_num < contours_r.size(); red_num++)
{
r_num = contourArea(contours_r[red_num]);
if (r_num > red_area)
{
red_area = r_num;
}
}
for (int blue_num = 0; blue_num < contours_b.size(); blue_num++)
{
b_num = contourArea(contours_b[blue_num]);
if (b_num > blue_area)
{
blue_area = b_num;
}
}
if (red_area > 0 && blue_area > 0)
{
num++;
}
else
{
num = 0;
}
if (num == 100)
{
break;
}
imshow("input", frame);
char a = waitKey(30);
if (a == 27)
{
break;
}
}
return 0;
}