Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenCV image conversion from RGB to HSV

When I run this following code on a sample image(RGB), and then process it to display the converted HSV image, Both appear to be different...

Can anyone explain why this happens?
OR
Can you suggest a solution for this not to happen... because it's the same image after all

Mat img_hsv,img_rgb,red_blob,blue_blob;
img_rgb = imread("pic.png",1);
cvtColor(img_rgb,img_hsv,CV_RGB2HSV);
namedWindow("win1", CV_WINDOW_AUTOSIZE);
imshow("win1", img_hsv);
like image 430
Kaushal Avatar asked Jun 10 '10 18:06

Kaushal


People also ask

How do I convert an image from RGB to HSV?

HSV = rgb2hsv( RGB ) converts the red, green, and blue values of an RGB image to hue, saturation, and value (HSV) values of an HSV image. hsvmap = rgb2hsv( rgbmap ) converts an RGB colormap to an HSV colormap.

How do you convert an RGB color to his HSV space?

Convert RGB Image to HSV Image Convert the image to the HSV color space. HSV = rgb2hsv(RGB); Process the HSV image. This example increases the saturation of the image by multiplying the S channel by a scale factor.

How do you convert RGB to HSV in Python?

To convert RGB color values to HSV color values in Python, import colorsys library, call rgb_to_hsv() function, and pass the Red, Green, and Blue values as arguments. rgb_to_hsv() function takes Red, Blue, and Green values as arguments, and returns a tuple containing Hue, Saturation, and Value.

How do I convert an image from RGB to grayscale cv2?

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


2 Answers

  1. I don't know the new (2.x) OpenCV well enough yet, but usually images loaded in OpenCV are in CV_BGR channel order and not RGB, therefore you most likely want CV_BGR2HSV

  2. OpenCV does not actually "know" HSV, it will just encode Hue in first channel, Saturation in second and Value in third. If you display an image in OpenCV, highgui assumes it's a BGR image, thus interpreting the first channel (now Hue) as Blue etc.

like image 102
zerm Avatar answered Oct 21 '22 03:10

zerm


As it was explained here already, it makes no sense to display the image right after it was converted to HSV, however here's an example how the V channel could be used:

If you want to extract only V channel, you might use cvtColor and use the 3rd (V) channel from HSV image to set the intensity of grayscale copy of this image:

Mat grayImg, hsvImg;
cvtColor(img, grayImg, CV_BGR2GRAY);
cvtColor(img, hsvImg, CV_BGR2HSV);
uchar* grayDataPtr = grayImg.data;
uchar* hsvDataPtr = hsvImg.data;
for (int i = 0; i < img.rows; i++)
{
    for (int j = 0; j < img.cols; j++)
    {
        const int hi = i*img.cols*3 + j*3,
                  gi = i*img.cols + j;
        grayDataPtr[gi] = hsvDataPtr[hi + 2];
    }
}
imshow("V-channel", grayImg);
like image 44
LihO Avatar answered Oct 21 '22 05:10

LihO