C++ OpenCV 图像从 RGB 到 HSV 的转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3017538/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
OpenCV image conversion from RGB to HSV
提问by Kaushal
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...
当我在示例图像(RGB)上运行以下代码,然后对其进行处理以显示转换后的 HSV 图像时,两者似乎不同...
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);
回答by zerm
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
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.
我还不太了解新的 (2.x) OpenCV,但通常在 OpenCV 中加载的图像采用 CV_BGR 通道顺序而不是 RGB,因此您很可能需要 CV_BGR2HSV
OpenCV 实际上并不“知道”HSV,它只会在第一个通道中编码色调,在第二个通道中编码饱和度,在第三个通道中编码值。如果您在 OpenCV 中显示图像,highgui 假定它是 BGR 图像,因此将第一个通道(现在是色调)解释为蓝色等。
回答by LihO
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:
正如这里已经解释的那样,在将图像转换为 HSV 后立即显示是没有意义的,但是这里有一个如何使用 V 通道的示例:
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:
如果只想提取 V 通道,则可以使用cvtColor
HSV 图像中的第 3 (V) 通道来设置此图像的灰度副本强度:
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);
回答by Arsalan Anwari
cv::Mat hsv;
std::vector<cv::Mat> channels;
cv::split(hsv, channels);
also possible
也可以
[0] = H
[1] = S
[2] = V