Threshold 对单通道数组应用的固定阈值操作

1.CV_EXPORTS_W double threshold( InputArray src, OutputArray dst,  double thresh, double maxval, int type )
//src: 原始数组(单通道,8-bit, 32-bit 浮点数)
//dst: 输出数组(与输入数组保持一致)
//thresh: 阈值(门槛值)
//maxval (CV_THRESH_BINARY 和 CV_THRESH_BINARY_INV 的最大值)
//type : 阈值类型(这里只介绍两种)
threshold_type=CV_THRESH_BINARY:如果 src(x,y)>threshold ,dst(x,y) = maxvalue; 否则,dst(x,y)=0;
threshold_type=CV_THRESH_BINARY_INV:如果 src(x,y)>threshold,dst(x,y) = 0; 否则,dst(x,y) = maxvalue.
2.HSV颜色分量范围
在运行程序时找对象的颜色对应范围可以参考这个表格,如果想要精确,也可以用ps等
Threshold 对单通道数组应用的固定阈值操作_第1张图片
/*
检测图像
*/
#include<opencv2\opencv.hpp>
#include<iostream>
using namespace cv;
using namespace std;

void detectHSColor(const Mat& img, double minHue, double maxHue, double minSat, double maxSat, Mat& mask);

int main() {
	double t = (double)getTickCount();
	Mat img = imread("D://图片//5.jpg");
	if (img.empty()) {
		cout << "加载失败" << endl;
		return -1;
	}

	Mat mask;
	detectHSColor(img, 35, 28, 178, 219, mask);        //这里的色调饱和度范围要对应设置
	Mat result(img.size(), CV_8UC3, Scalar(0,0,0));
	img.copyTo(result,mask);
	imshow("show_result", result);

	double Time = ((double)getTickCount() - t) / getTickFrequency();
	cout << "Time = " << Time << endl;
	waitKey(0);

	destroyAllWindows;
	return 0;
}

void detectHSColor(const Mat & img, double minHue, double maxHue, double minSat, double maxSat, Mat & mask)  //H是色调区间,S是饱和度区间
{
	Mat hsv;
	cvtColor(img, hsv, CV_BGR2HSV);   //转换成HSV
	vector<Mat> channels;
	split(hsv, channels);     //分离通道信息

	Mat mask1;         //色调掩码
	threshold(channels[0], mask1, maxHue, 255, THRESH_BINARY_INV);
	Mat mask2;
	threshold(channels[0], mask2, minHue, 255, THRESH_BINARY);
	Mat Hmask;
	if (minHue < maxHue)
		Hmask = mask1 & mask2;
	else
		Hmask = mask1 | mask2;

	threshold(channels[1], mask1, maxSat, 255, THRESH_BINARY_INV);    //饱和度掩码
	threshold(channels[1], mask2, minSat, 255, THRESH_BINARY);
	Mat Smask;
	Smask = mask1 & mask2;

	mask = Hmask & Smask;    //组合掩码
	imshow("mask", mask);     //观察mask
}

运行结果:
Threshold 对单通道数组应用的固定阈值操作_第2张图片
这里由于背景和小狗的毛发颜色交叉太大,就这样了,以后处理好的效果



你可能感兴趣的:(Threshold 对单通道数组应用的固定阈值操作)