How to convert an input image from one color space to another space

来源:互联网 发布:dwg转换pdf软件 编辑:程序博客网 时间:2024/06/05 03:50

Mainly we will cover the case that converting BGR to/ from HSV using opencv library.

RGB: 一般用于电脑显示的三原色。 代表R(red), G(green), B(blue).  任何一种standard color or brightness 均为一个combination of Red, Green, Blue components. 通常使用24bits 存储。 即8 bits for every color component(0 - 255)。 白色使用 255 Red + 255 Green + 255 Blue 组成的。 RGB 颜色空间是computer software 的standard color format. 然而对于计算机视觉(computer vision) 来说, RGB values 很大的依赖于我们的光照环境以及是否有阴影。 所以想比较而言, 在处理(handling)lighting differences的情况下, HSV is much better, because the HSV gives you an easy to use color values.


HSV stands for Hue-Saturation-Value, Hue 代表color(颜色的信息在这个通道中). 由于color 很难veu分割出来并进行比较, 所以Hue 常常通过一个角度(circular angles)表示, 当用float 存储这个值的时候, 该值的范围在0.0-1.0. 由于是circular value, 所以这也意味着1.0 和 0.0 是想同的(the same)。 for example, a hue of 0.0 is red, a hue of 0.25 is green, a hue of 0.5 is blue, a hue of 0.75 is pink, a hue of 1.0 is red again。Saturation(饱和度) is the greyness, so that a saturation value near 0 means it is dull or grey. where a Saturation of 0.8 might be very strong colors. Value is the brighness of the pixel. so 0.1 is black. 0.9 is white. 1. 1.0 should be bright white or a bright color, Most software chooses full brightness V to mean white, where OpenCV chooses full brightness V to mean bright color.


另外除此之外, 还有CMYK(printing), YUV 等颜色模型。

OpenCV中, 默认的pixel format 是BGR的, 除非特别说明, OpenCV中的彩色图像像素的格式是BGR通道排布的。

另外, 我们应该知道, OpenCV 并不知道HSV,  it will just encode the Hue in the first channel , Saturation in scond channel  and Value in the third channel., if you display the image in opencv, highgui will assume it is a BGR image, thus interpreting the first channel(now Hue) as Blue etc.

所以, 将一幅BGR编码的图像转为HSV图像之后, it will not make sense to display the image。 

if you want to extract only V channel, that is use the third channel from HSV image to set the intensity of grayscale copy of this image:

#include <opencv2/core/core.hpp>#include <opencv2/highgui/highgui.hpp>#include <opencv2/imgproc/imgproc.hpp>#include <iostream>using namespace std;using namespace cv;int main() {    Mat img = imread("F:\\opencvLearning\\test.jpg");    if(!img.data) {        cout << "Failure" << endl;    } else {    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;                const int gi = i * img.cols + j;                grayDataPtr[gi] = hsvDataPtr[hi + 2];        }    }////method 2//    Mat planes[3];//    split(hsvImg, planes); // planes[2] is the V channel    namedWindow("V", WINDOW_AUTOSIZE);    imshow("V", grayImg);    waitKey(0);    destroyAllWindows();    }    return 0;}

运行结果如下:




0 0
原创粉丝点击