# Implementation of Matlab function rgb2ntsc in opencv using c++

I am trying to implement rgb2ntsc colorspace conversion in OpenCV using C++.

for(int i=0;i<rn;i++) {
for(int j=0;j<cn;j++) {
Vec3b intensity = image.at<Vec3b>(i,j);
R = intensity.val;
G = intensity.val;
B = intensity.val;
Y = 0.299*R+0.587*G+0.114*B;
I = 0.596*R-0.274*G-0.322*B;
Q = 0.211*R-0.523*G+0.312*B;
Result.at<Vec3b>(i,j) = (float)Y;
Result.at<Vec3b>(i,j) = (float)I;
Result.at<Vec3b>(i,j) = (float)Q;
}
}


I have done this for the implementation of rgb2ntsc. But my output image is not similar to the output of Matlab's rgb2ntsc function. Here are my input image, output image and matlab output image. Can I do any additional operation?   edit retag close merge delete

1

you need saturate_cast , before reassigning to uchar values, to avoid over/underflow

then, maybe you should better use transform , instead of those for loops (it also does automatic saturation)

1

oh, just curious, - what's your final transform matrix ? (did not make a real answer (hey, @pklab ;), because my efforts did not look exactly the same as yours.

in other words, @Tess , if you could make an answer (or a comment, we'd convert it) - highly welcome !

touché :) my comment want to become an answer but I was feeling it as partial so it remains at the background as comment.Thanks to @berak to have laid out the transform funct.

Sort by » oldest newest most voted

@ berak :Code:-

Mat image =imread(argv,1);
Mat k=(Mat_<float>(3,3) << 0.299,0.587,0.114, 0.596,-0.274,-0.322,0.211,-0.523,0.312);
Mat Result;
cvtColor(image,image,CV_BGR2RGB);
transform(image,Result,k);
cvtColor(Result,Result,CV_RGB2BGR);

more

i'm still sure, there is a way to rearrange the transform Mat, so you don't need both cvtColor calls...

1

Official site

GitHub

Wiki

Documentation