Simple color detection by Hue - Hue(HSV)값으로 특정색 검출하기
OpenCV 2019. 11. 17. 16:03 |Hue is the color portion of the model, expressed as a number from 0 to 360 degrees:
Red: falls between 0 and 60 degrees.
Yellow: falls between 61 and 120 degrees.
Green: falls between 121-180 degrees.
Cyan: falls between 181-240 degrees.
Blue: falls between 241-300 degrees.
Magenta: falls between 301-360 degrees.
For HSV, OpenCV Hue range is [0,179], Saturation range is [0,255] and Value range is [0,255]. Different software uses different scales. So if you are comparing OpenCV values with them, you need to normalize these ranges.
HSV(Hue)를 이용하면 RGB를 이용하는 것 보다 간단히 특정색을 검출할 수 있다. OpenCV의 Hue값은 0~179 이다.
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 44 45 46 47 48 49 | #include <opencv2/opencv.hpp> using namespace std; using namespace cv; int lowerHue = 40, upperHue = 80; // Green Mat src, src_hsv, mask, dst; void OnHueChenaged(int pos, void* userdata) { Scalar lowerb(lowerHue, 100, 0); Scalar upperb(upperHue, 255, 255); inRange(src_hsv, lowerb, upperb, mask); // Checks if array elements lie between the elements of two other arrays. dst.setTo(0); // 매번 초기화 해 주지 않으면 이전에 선택한 색과 겹친다. src.copyTo(dst, mask); // The method copies the matrix data to another matrix. Before copying the data, the method invokes: m.create(this->size(), this->type()); // so that the destination matrix is reallocated if needed.While m.copyTo(m); works flawlessly, the function does not handle the case of a // partial overlap between the sourceand the destination matrices. When the operation mask is specified, if the Mat::create call shown above // reallocates the matrix, the newly allocated matrix is initialized with all zeros before copying the data. imshow("mask", mask); imshow("dst", dst); } int main(int argc, char** argv) { src = imread("candies.jpg", IMREAD_COLOR); if (src.empty()) { cerr << "Image load failed." << endl; return -1; } imshow("src", src); cvtColor(src, src_hsv, COLOR_BGR2HSV); namedWindow("mask"); createTrackbar("Lower Hue", "mask", &lowerHue, 179, OnHueChenaged); createTrackbar("Upper Hue", "mask", &upperHue, 179, OnHueChenaged); OnHueChenaged(NULL, NULL); waitKey(0); return 0; } |
Original candy image.
Mask for green color.
Green candies detected.
'OpenCV' 카테고리의 다른 글
Haar-cascade Detection 얼굴 검출 (10) | 2019.12.15 |
---|---|
QR Code detect and decode - QR 코드 리더 (0) | 2019.12.15 |
Simple copy and save in cv::imshow() 간단하게 이미지 복사, 저장 하기 (0) | 2019.11.17 |
Finding a homography matrix - OpenCV 두 평면 사이의 투영 변환 행렬 (0) | 2019.11.03 |
Keypoint matching - OpenCV 키포인트 매칭 (0) | 2019.11.02 |