YUY2转换为RGB的多种方法

在视频采集图像分析中,需要将采集的格式转换为所需的RGB格式,这里有两种方法:

方法1:

步骤1:转换为RGB24格式

int ConvertYUY2toRGB24(char* pOutputRgb,
                       unsigned char* pInputBuffer,
                       int tInputWidth,
                       int tInputHeight) {
  unsigned char* yuyv = pInputBuffer;
  int z = 0, i = 0, j = 0;

  for (i = 0; i < tInputHeight; i++) {
    for (j = 0; j < tInputWidth; j++) {
      int r, g, b;
      int y, u, v;

      if (!z)
        y = yuyv[0] << 8;
      else
        y = yuyv[2] << 8;
      u = yuyv[1] - 128;
      v = yuyv[3] - 128;

      r = (y + (359 * v)) >> 8;
      g = (y - (88 * u) - (183 * v)) >> 8;
      b = (y + (454 * u)) >> 8;

      r = (r > 255) ? 255 : ((r < 0) ? 0 : r);
      g = (g > 255) ? 255 : ((g < 0) ? 0 : g);
      b = (b > 255) ? 255 : ((b < 0) ? 0 : b);

      *pOutputRgb++ = b;
      *pOutputRgb++ = g;
      *pOutputRgb++ = r;

      if (z++) {
        z = 0;
        yuyv += 4;
      }
    }
  }
  return 0;
}

步骤2:发现格式颜色R和B是反的,再进行调换下

void RGBTOBGR(char* data, int length) {
  for (int i = 0; i < length; i++) {
    char tmp = data[3*i];
    data[3*i] = data[3*i+2];
    data[3*i+2] = tmp;
  }
}

方法2:采用libyuv库进行转换

步骤1:转换为ARGB格式

  uint8_t* argb_data = new uint8_t[width * height * 4];
  libyuv::YUY2ToARGB(videoFrame, width * 2, argb_data, width * 4, width, height);

步骤2:转后发现R和B相反的,再转换下

void ARGBTOABGR(int* data, int length) {
  int transBlue = 0;
  for (int i = 0; i < length; i++) {
    transBlue = (int)(data[i] >> 16);
    data[i] &= 0xFF00FFFF;
    data[i] |= (data[i] << 16 & 0x00FF0000);
    data[i] &= 0xFFFFFF00;
    data[i] |= (transBlue & 0x000000FF);
  }
}

已测试,直接可用。

你可能感兴趣的:(window多媒体技术,yuy2,rgb,libyuv)