Kaushal
Kaushal

Reputation: 207

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);

Upvotes: 10

Views: 74835

Answers (3)

Arsalan Anwari
Arsalan Anwari

Reputation: 11

cv::Mat hsv;
std::vector<cv::Mat> channels;
cv::split(hsv, channels);

also possible

[0] = H
[1] = S
[2] = V

Upvotes: 0

zerm
zerm

Reputation: 2842

  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.

Upvotes: 27

LihO
LihO

Reputation: 42083

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);

Upvotes: 4

Related Questions