rgb2ntsc matlab code in c++

Please help me to write matlab rgb2ntsc function code in c++

A = parse_inputs(varargin{:});
T = [1.0 0.956 0.621; 1.0 -0.272 -0.647; 1.0 -1.106 1.703].';
[so(1) so(2) thirdD] = size(A);
if thirdD == 1,% A is RGBMAP, M-by-3 colormap
A = A/T; else % A is truecolor
image RBG A = reshape(reshape(A,so(1)*so(2),thirdD)/T,so(1),so(2),thirdD);
end;
That there snippet converts from YIQ to RGB. It is usually a good idea to research the thing you are working with. Wikipedia is often a good place to start.
https://en.wikipedia.org/wiki/YIQ#Formulas

In any case, it is a simple matrix multiplication. Here's something, assuming your input is organized as an iterable sequence of component values (such as an array), where every three values make an RGB triplet or a YIQ triplet, in that order.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
template <typename T>
T clamp( T min, T value, T max )
{
  return !(min < value) ? min : (!(value < max) ? max : value);
}

template <typename RGB_Component_Iterator, typename YIQ_Component_Iterator>
void rgb2ntsc( 
  RGB_Component_Iterator first, 
  RGB_Component_Iterator last, 
  YIQ_Component_Iterator result )
{
  while (first != last)
  {
    decltype(*first) R = *first++;  if (first == last) break;
    decltype(*first) G = *first++;  if (first == last) break;
    decltype(*first) B = *first++;
    *result++ = clamp(  0.0000,  R*0.299 + G*0.587 + B*0.114,  1.0000 );
    *result++ = clamp( -0.5957,  R*0.596 - G*0.274 - B*0.322,  0.5957 );
    *result++ = clamp( -0.5226,  R*0.211 - G*0.523 + B*0.312,  0.5226 );
  }
}

template <typename YIQ_Component_Iterator, typename RGB_Component_Iterator>
void ntsc2rgb( 
  YIQ_Component_Iterator first, 
  YIQ_Component_Iterator last, 
  RGB_Component_Iterator result )
{
  while (first != last)
  {
    decltype(*first) Y = *first++;  if (first == last) break;
    decltype(*first) I = *first++;  if (first == last) break;
    decltype(*first) Q = *first++;
    *result++ = clamp( 0.0,  Y + I*0.956 + Q*0.621,  1.0 );
    *result++ = clamp( 0.0,  Y - I*0.272 - Q*0.647,  1.0 );
    *result++ = clamp( 0.0,  Y - I*1.106 + Q*1.703,  1.0 );
  }
}

I haven't tested it on anything, JSYK. Also, keep in mind that the conversion is lossy -- not all YIQ values can represented in RGB and vice versa.

To convert an entire image you can just pass an iterator to the first and last elements:

1
2
3
4
void convert_rgb_image_to_ntsc_image( double* rgb_image, int width, int height, double* ntsc_image )
{
  rgb2ntsc( rgb_image, rgb_image + 3*width*height, ntsc_image );
}

It even works in-place:

1
2
3
4
void convert_rgb_image_to_ntsc_image( double* image, int width, int height )
{
  rgb2ntsc( image, image + 3*width*height, image );
}

Obviously, this doesn't handle interlacing or anything like that. You'll have to structure your code to fix that however you want.

Good luck!
Topic archived. No new replies allowed.