Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert HSV to grayscale in OpenCV

I'm a newbie in OpenCV. I'm learning the Segmentation by Watershed algorithm and I have a problem.

I have to convert the image color to grayscale for using Watershed. When I use the BGR color space, no problem but with HSV, I'm not sure that the code below is correct.

Mat im = imread("./Image/118035.jpg", CV_LOAD_IMAGE_COLOR);

Mat imHSV;
cvtColor(im, imHSV, CV_BGR2HSV);
imshow("HSV", imHSV);

cvtColor(imHSV, imHSV, CV_BGR2GRAY);
imshow("HSV to gray", imHSV);


imshow("BGR", im);
cvtColor(im, im, CV_BGR2GRAY);
imshow("BGR to gray", im);

I think, after converting from BGR to HSV, Hue = Blue, Saturation = Green, Value = Red and I can use the operator BGR2GRAY for convert from HSV to grayscale.

The 2 output images are different. Can I convert HSV to grayscale like that?

//Is it similaire with color space LAB?

like image 486
Amateur Avatar asked May 22 '14 15:05

Amateur


People also ask

How do I convert a color image to grayscale in OpenCV?

The conversion from a RGB image to gray is done with: cvtColor(src, bwsrc, cv::COLOR_RGB2GRAY); More advanced channel reordering can also be done with cv::mixChannels.

How do I convert an image to grayscale using OpenCV in Python?

Method 1: Using the cv2.Import the OpenCV and read the original image using imread() than convert to grayscale using cv2. cvtcolor() function.

How do I convert RGB to grayscale in cv2?

Step 1: Import OpenCV. Step 2: Read the original image using imread(). Step 3: Convert to grayscale using cv2. cvtcolor() function.

Is grayscale a HSV?

The HSV color 180°, 0%, 50% is a dark color, and the websafe version is hex 999999, and the color name is gray. A complement of this color would be 0°, 0%, 50%, and the grayscale version is 0°, 0%, 50%.


2 Answers

The conversion from HSV to gray is not necessary: you already have it. You can just select the V channel as your grayscale image by splitting the HSV image in 3 and taking the 3rd channel:

Mat im = imread("C:/local/opencv248/sources/samples/c/lena.jpg", CV_LOAD_IMAGE_COLOR);
    
Mat imHSV;
cvtColor(im, imHSV, CV_BGR2HSV);
imshow("HSV", imHSV);
    
//cvtColor(imHSV, imHSV, CV_BGR2GRAY);
Mat hsv_channels[3];
cv::split( imHSV, hsv_channels );
imshow("HSV to gray", hsv_channels[2]);
    
imshow("BGR", im);
cvtColor(im, im, CV_BGR2GRAY);
imshow("BGR to gray", im);
    
waitKey();
like image 62
RevJohn Avatar answered Oct 22 '22 18:10

RevJohn


hsv1 = cv2.cvtColor(frame1, cv2.COLOR_BGR2HSV)

h, s, v1 = cv2.split(hsv1)

cv2.imshow("gray-image",v1)
like image 3
Sharath Kumar Avatar answered Oct 22 '22 16:10

Sharath Kumar