#define GetY(R,G,B) (0.257*(R)+0.504*(G)+0.98*(B)+16) #define GetU(R,G,B) (0.148*(R)-0.291*(G)+0.439*(B)+128) #define GetV(R,G,B) (0.439*(R)-0.368*(G)-0.071*(B)+128)
/******************************************* yuv422Planar format 数据排列: Y0Y1Y2Y3.... U0U2U4.... V1V3V5.... ********************************************/ void rgb2yuv422Planar(const unsigned char *rgbData,int height,int width,int widthstep,unsigned char*yuvData) { int i,j,temp; unsigned char *lineUV = (unsigned char *)malloc(width*sizeof(unsigned char));//偶数下标位存U,奇数下标位存V if (NULL==lineUV) { perror("malloc lineUV memory failed!"); exit(1); } memset(lineUV,0,sizeof(width*sizeof(unsigned char))); for (i=0;i<height;i++) { for (j=0;j<width;j++) //y { unsigned char b = rgbData[i*widthstep+3*j]; unsigned char g = rgbData[i*widthstep+3*j+1]; unsigned char r = rgbData[i*widthstep+3*j+2]; unsigned char *y = yuvData+i*width+j; temp = (int)GetY(r,g,b); *y = (temp<0)?0:((temp>255)?255:temp); if (0==j%2) { temp = (int)GetU(r,g,b); lineUV[j] = (temp<0)?0:((temp>255)?255:temp); } else { temp = (int)GetV(r,g,b); lineUV[j] = (temp<0)?0:((temp>255)?255:temp); } } for (j=0;j<width;j++) //u,v { if (0==j%2) //u { unsigned char *u = yuvData+height*width+i*width/2+j/2; *u = lineUV[j]; } else //v { unsigned char *v = yuvData+height*width*3/2+i*width/2+(int)(j/2); *v = lineUV[j]; } } } if (lineUV!=NULL) { free(lineUV); lineUV = NULL; } }
/******************************* yuv422Packed format 数据排列: Y0U0Y1V1Y2U2Y3V3..... ................ *******************************/ void rgb2yuv422Packed(const unsigned char *rgbData,int height,int width,int widthstep,unsigned char *yuvData) { int i,j,temp; int index = 0; for (i=0;i<height;i++) { bool bsetU = true; for (j=0;j<width;j++) { unsigned char b = rgbData[i*widthstep+3*j]; unsigned char g = rgbData[i*widthstep+3*j+1]; unsigned char r = rgbData[i*widthstep+3*j+2]; temp =(int)GetY(r,g,b); yuvData[index++] = (temp<0)?0:((temp>255)?255:temp); if (bsetU) // { temp = (int)GetU(r,g,b); yuvData[index++] = (temp<0)?0:((temp>255)?255:temp); bsetU = false; } else { temp = (int)GetV(r,g,b); yuvData[index++] = (temp<0)?0:((temp>255)?255:temp); bsetU = true; } } } }
int yuv422Packed2Planar(const unsigned char *packedData,unsigned char *planarData,int heigh,int width) { int index; int i = 0; int j = 0; int k = 0; unsigned char *y = planarData; unsigned char *u = planarData + heigh*width; unsigned char *v = planarData + heigh*width*3/2; bool flag = true; for (index=0;index<2*width*heigh;) { y[i++] = packedData[index++]; if (flag) { u[j++] = packedData[index++]; flag = false; } else { v[k++] = packedData[index++]; flag = true; } } if (2*width*heigh==index&&width*heigh==i&&width*heigh/2==j&&j==k) { return 0; } else { return -1; } }