使用C ++在OpenCV中实现Matlab函数'rgb2ntsc'

时间:2015-09-02 16:32:37

标签: c++ matlab opencv image-processing

我正在尝试使用C ++在OpenCV中实现Matlab函数'rgb2ntsc'。

根据Matlab: YIQ = rgb2ntsc(RGB),RGB是输入彩色图像。

enter image description here

使用C ++在OpenCV中进行矩阵乘法有一些标准:

1)每个矩阵的相同数量的通道(2通道或1通道) 2)矩阵应该是浮点值

那么如何将输入彩色图像(输入有3个通道)与NTSC组件相乘?

2 个答案:

答案 0 :(得分:3)

您应该使用OpenCV中的Vec3f类型(实际上是3x1矩阵):

// I assume you have RGB values as unsigned char in [0-255] interval
// here using a dummy color
unsigned char R = 255;
unsigned char G = 127;
unsigned char B = 64;

// construct a Vec3f from those, divide by 255 to get them in [0-1] interval
Vec3f colorRGB(R/255.0f, G/255.0f, B/255.0f);

// matrix for RGB -> YIQ conversion
Matx33f matYIQ( 0.299f,  0.587f,  0.114f,
                0.596f, -0.274f, -0.322f,
                0.211f, -0.523f,  0.312f);

// do the conversion
// a warning ... I & Q can be negative
// Y => [0,1]
// I => [-1,1]
// Q => [-1,1]
Vec3f colorYIQ = matYIQ * colorRGB;

---编辑---

这是一个更好的版本,仅使用OpenCV功能转换整个图像

// let's define the matrix for RGB -> YIQ conversion
Matx33f matYIQ( 0.299f,  0.587f,  0.114f,
                0.596f, -0.274f, -0.322f,
                0.211f, -0.523f,  0.312f);

// I assume you have a source image of type CV_8UC3 
// CV_8UC3: 3 channels, each on unsigned char, so [0,255]
// here is a dummy one, black by default, 256x256
Mat ImgRGB_8UC3(256, 256, CV_8UC3);

// We need to convert this to a new image of type CV_32FC3
// CV_32FC3: 3 channels each on 32bit float [-inf, +inf]
// we need to do this because YIQ result will be in [-1.0, 1.0] (I & Q)
// so this obviously cannot be stored in CV_8UC3
// At the same time, we will also divide by 255.0 to put values in [0.0, 1.0]
Mat ImgYIQ_32FC3;
ImgRGB_8UC3.convertTo(ImgYIQ_32FC3, CV_32FC3, 1.0/255.0);

// at this point ImgYIQ_32FC3 contains pixels made of 3 RGB float components in [0-1]
// so let's convert to YIQ
// (cv::transform will apply the matrix to each 3 component pixel of ImgYIQ_32FC3)
cv::transform(ImgYIQ_32FC3, ImgYIQ_32FC3, matYIQ);

答案 1 :(得分:0)

不确定我是否正确,但YIQ有3个与RGB相同的值,因此图片保持3个频道。

如果你用浮点数或整数乘以浮点数,你得浮点数,所以我看不到乘法的问题。也许我无法正确理解你的问题。上面的乘法应该是:

Y = 0.299*R+0.587*G+0.114*B,
I = 0.596*R-0.274*G-0.322*B,

等等。在我看来。

如果RGB是整数表示,您可能会想到:

template<typename intType>
float convertIntToFloat(intType number){
    return (1.0/std::numeric_limits<intType>::max())*number;
}

将其转换为浮动。