I am wondering why this code does not work. Basically it is supposed to convert between RGB and CbYCr. When I convert from RGB to CbYCr then back to RGB I do not get the original RGB values. What is wrong with this code?
#define MIN(a,b) (((a)<(b))?(a):(b))
#define MAX(a,b) (((a)(b))?(a):(b))
struct _rgb {
int R;
int G;
int B;
};
typedef struct _rgb rgb;
struct _cbycr {
int Cb;
int Y;
int Cr;
};
typedef struct _cbycr cbycr;
void cbycr2rgb(rgb *c, double Y, double Cb, double Cr) {
int r = (int)(Y + 1.40200 * (Cr - 0x80));
int g = (int)(Y - 0.34414 * (Cb - 0x80) - 0.71414 * (Cr - 0x80));
int b = (int)(Y + 1.77200 * (Cb - 0x80));
c->R = MAX(0, MIN(255, r));
c->G = MAX(0, MIN(255, g));
c->B = MAX(0, MIN(255, b));
}
void rgb2cbycr(cbycr *c, int R, int G, int B) {
c->Y = (int)(0.299 * R + 0.587 * G + 0.114 * B);
c->Cb = (int)(-0.16874 * R - 0.33126 * G + 0.50000 * B);
c->Cr =(int)(0.50000 * R - 0.41869 * G - 0.08131 * B);
}
int main() {
cbycr _cbycr;
rgb _rgb;
_rgb.R = 50;
_rgb.G = 50;
_rgb.B = 50;
rgb2cbycr(&_cbycr, _rgb.R, _rgb.G, _rgb.B);
cbycr2rgb(&_rgb, _cbycr.Y, _cbycr.Cb, _cbycr.Cr);
printf("rgb=%d %d %d\n", _rgb.R, _rgb.G, _rgb.B);
return 0;
}
output: rgb=0 185 0