HSV颜色识别demo

HSV(Hue, Saturation, Value)色彩空间是一种区别与RGB的表示形式。其模型可视为一个倒立的棱锥或圆锥。

其中H为色调,用角度度量,取值范围为0°~360°,从红色开始按逆时针方向计算,红色为0°,绿色为120°,蓝色为240°。它们的补色是:黄色为60°,青色为180°,品红为300°;

S为饱和度,饱和度S表示颜色接近光谱色的程度。一种颜色,可以看成是某种光谱色与白色混合的结果。其中光谱色所占的比例愈大,颜色接近光谱色的程度就愈高,颜色的饱和度也就愈高。饱和度高,颜色则深而艳。光谱色的白光成分为0,饱和度达到最高。通常取值范围为0%~100%,值越大,颜色越饱和。

V为亮度,明度表示颜色明亮的程度,对于光源色,明度值与发光体的光亮度有关;对于物体色,此值和物体的透射比或反射比有关。通常取值范围为0%(黑)到100%(白)。

下面是一个比较直观的HSV表示图

 

HSV色彩空间常用与选取颜色或图像编辑,下面是发现的一个比较有趣的小demo是关于用HSV进行肤色识别的demo

#include<opencv2/core/core.hpp>
#include<opencv2/imgproc/imgproc.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<iostream>

using namespace cv;
using namespace std;

int main(int argc, char** argv)
{
	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;
	}

	namedWindow("Control", CV_WINDOW_NORMAL); //create a window called "Control"  

	int iLowH = 0;
	int iHighH = 0;

	int iLowS = 0;
	int iHighS = 0;

	int iLowV = 0;
	int iHighV = 0;

	//Create trackbars in "Control" window  
	cvCreateTrackbar("LowH", "Control", &iLowH, 359); //Hue (0 - 359)  
	cvCreateTrackbar("HighH", "Control", &iHighH, 259);

	cvCreateTrackbar("LowS", "Control", &iLowS, 255); //Saturation (0 - 255)  
	cvCreateTrackbar("HighS", "Control", &iHighS, 255);

	cvCreateTrackbar("LowV", "Control", &iLowV, 255); //Value (0 - 255)  
	cvCreateTrackbar("HighV", "Control", &iHighV, 255);

	while (true)
	{
		Mat imgOriginal;

		bool bSuccess = cap.read(imgOriginal); // read a new frame from video  

		if (!bSuccess) //if not success, break loop  
		{
			cout << "Cannot read a frame from video stream" << endl;
			break;
		}

		Mat imgHSV;
		vector<Mat> hsvSplit;
		cvtColor(imgOriginal, imgHSV, COLOR_BGR2HSV); //Convert the captured frame from BGR to HSV  

		// hsv[2] 是v通道 做亮度均衡
		split(imgHSV, hsvSplit);
		equalizeHist(hsvSplit[2], hsvSplit[2]);
		merge(hsvSplit, imgHSV);
		Mat imgThresholded;

		inRange(imgHSV, Scalar(iLowH, iLowS, iLowV), Scalar(iHighH, iHighS, iHighV), imgThresholded); //Threshold the image  

		//open (remove noise)  
		Mat element = getStructuringElement(MORPH_RECT, Size(5, 5));
		morphologyEx(imgThresholded, imgThresholded, MORPH_OPEN, element);

		//close (connect connected-component)  
		morphologyEx(imgThresholded, imgThresholded, MORPH_CLOSE, element);

		imshow("Thresholded Image", imgThresholded); //show the thresholded image  
		imshow("Original", imgOriginal); //show the original image  

		char key = (char)waitKey(300);
		if (key == 27)
			break;
	}

	return 0;

}

调整HSV值可以大体检测到人体肤色部位如脸

 

 

代码来自:http://blog.csdn.NET/zwhlxl/article/details/46381353

  

 

posted on 2016-10-12 15:27  klitech  阅读(10534)  评论(0编辑  收藏  举报

导航