c++ - 在 OpenCV 中从 RGB 转换为 YUYV

标签 c++ opencv colors video-streaming libyuv

有没有办法将 RGB 格式转换为 YUYV (YUY 4:2:2) 格式?我注意到 OpenCV 有反向操作,但出于某种原因没有 RGB 到 YUYV。也许有人可以指出执行此操作的代码(甚至在 OpenCV 库之外)?

更新

我找到了 libyuv 库,它可以通过将 BGR 转换为 ARGB,然后将 ARGB 转换为 YUY2 格式(希望这与 YUYV 4:2:2 相同)来实现此目的。但这似乎不起作用。您是否碰巧知道 yuyv 缓冲区的尺寸/类型应该是什么样子?它的步幅如何?

澄清 YUYV 和 YUY2 是相同的格式,如果有帮助的话。

更新 2 这是我使用 libyuv 库的代码:

  Mat frame;
  // Convert original image im from BGR to BGRA for further use in libyuv
  cvtColor(im, frame, CVX_BGR2BGRA);
  // Actually libyuv requires ARGB (i.e. reverse of BGRA), so I swap channels here
  int from_to[] = { 0,3, 1,2, 2,1, 3,0 };
  mixChannels(&frame, 1, &frame, 1, from_to, 4);
  // This is the most confusing part. Not sure what argb_stride suppose to be - length of a row in bytes or size of single value in the array?
  const uint8_t* argb_data = frame.data;
  int argb_stride = 8;

  // Also it is not clear what size of yuyv frame should be since we duplicate one Y 
  Mat yuyv(frame.rows, frame.cols, CVX_8UC2);
  uint8_t* yuyv_data = yuyv.data;
  int yuyv_stride = 16;
  // Do actual conversion
  libyuv::ARGBToYUY2(argb_data, argb_stride, yuyv_data, yuyv_stride, 
  frame.cols, frame.rows);
  // Then I feed yuyv_data to video stream buffer and see green or purple image instead of video stream.

更新 3

  Mat frame;
  cvtColor(im, frame, CVX_BGR2BGRA);

  // ARGB
  int from_to[] = { 0,3, 1,2, 2,1, 3,0 };
  Mat rgba(frame.size(), frame.type());
  mixChannels(&frame, 1, &rgba, 1, from_to, 4);
  const uint8_t* argb_data = rgba.data;
  int argb_stride = rgba.cols*4;

  Mat yuyv(rgba.rows, rgba.cols, CVX_8UC2);
  uint8_t* yuyv_data = yuyv.data;
  int yuyv_stride = width * 2;
  int res = libyuv::ARGBToYUY2(argb_data, argb_stride, yuyv_data, yuyv_stride, rgba.cols, rgba.rows);

enter image description here

最佳答案

看起来虽然方法称为 ARGBToYUY2,但它需要 BGRA channel 顺序(不是反向)。

关于c++ - 在 OpenCV 中从 RGB 转换为 YUYV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39876798/

相关文章:

c++ - 从动态索引中选择一个 constexpr 索引

c++ - 从 std::vector 删除范围 vector 的最佳方法

c++ - 范围解析和 this 运算符

c++ - 在 OpenCV C++ 中绘制一条穿过 Blob 的曲线

用于创建图像镜像并将其与一定量的白色混合的 Python 代码。

c++ - 通过引用将数组从 Delphi 7 传递到 C++ Dll

c++ - Qt OpenCV 应用程序无法在 Raspberry Pi 显示屏上运行

python - 错误:调用cv.ShowImage时发生mat.isContinuous()

java - 使用一些键在 android 中创建随机颜色(对于相同的键,它应该生成相同的颜色)

c++ - Ncurses C++ 打印前景色/背景色交换的文本