HSV顏色識別demo

HSV(Hue, Saturation, Value)色彩空間是一種區別與RGB的表示形式。其模型可視爲一個倒立的棱錐或圓錐。ios

其中H爲色調,用角度度量,取值範圍爲0°~360°,從紅色開始按逆時針方向計算,紅色爲0°,綠色爲120°,藍色爲240°。它們的補色是:黃色爲60°,青色爲180°,品紅爲300°;web

S爲飽和度,飽和度S表示顏色接近光譜色的程度。一種顏色,能夠當作是某種光譜色與白色混合的結果。其中光譜色所佔的比例愈大,顏色接近光譜色的程度就愈高,顏色的飽和度也就愈高。飽和度高,顏色則深而豔。光譜色的白光成分爲0,飽和度達到最高。一般取值範圍爲0%~100%,值越大,顏色越飽和。ide

V爲亮度,明度表示顏色明亮的程度,對於光源色,明度值與發光體的光亮度有關;對於物體色,此值和物體的透射比或反射比有關。一般取值範圍爲0%(黑)到100%(白)。oop

下面是一個比較直觀的HSV表示圖ui

 

HSV色彩空間經常使用與選取顏色或圖像編輯,下面是發現的一個比較有趣的小demo是關於用HSV進行膚色識別的demospa

#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值能夠大致檢測到人體膚色部位如臉.net

 

 

代碼來自:http://blog.csdn.NET/zwhlxl/article/details/46381353component

相關文章
相關標籤/搜索