opencv 将YUV帧转换为RGB

cqoc49vn  于 2022-11-15  发布在  其他
关注(0)|答案(1)|浏览(265)

I'm trying to convert YUV file(UYUV, YUV 422 Interleaved,BT709) to RGB with C++. I've took the example from here: https://stackoverflow.com/a/72907817/2584197 This is my code:

  1. Size iSize(1920,1080);
  2. int iYUV_Size = iSize.width * (iSize.height + iSize.height / 2);
  3. Mat mSrc_YUV420(cv::Size(iSize.width, iSize.height + iSize.height / 2),CV_8UC1);
  4. ifstream FileIn;
  5. FileIn.open(filename, ios::binary | ios::in);
  6. if (FileIn.is_open())
  7. {
  8. FileIn.read((char*)mSrc_YUV420.data, iYUV_Size);
  9. FileIn.close();
  10. }
  11. else
  12. {
  13. printf("[Error] Unable to Read the Input File! \n");
  14. }
  15. Mat mSrc_RGB(cv::Size(iSize.width, iSize.height), CV_8UC1);
  16. cv::cvtColor(mSrc_YUV420, mSrc_RGB, COLOR_YUV2RGB_UYVY);
  17. cv::imwrite(output_filename, mSrc_RGB);

But I get this error:
terminating with uncaught exception of type cv::Exception: OpenCV(4.5.5) /build/master_pack-android/opencv/modules/imgproc/src/color.simd_helpers.hpp:92: error: (-2:Unspecified error) in function 'cv::impl::(anonymous namespace)::CvtHelper<cv::impl::(anonymous namespace)::Set<2, -1, -1>, cv::impl::(anonymous namespace)::Set<3, 4, -1>, cv::impl::(anonymous namespace)::Set<0, -1, -1>, cv::impl::(anonymous namespace)::NONE>::CvtHelper(cv::InputArray, cv::OutputArray, int) [VScn = cv::impl::(anonymous namespace)::Set<2, -1, -1>, VDcn = cv::impl::(anonymous namespace)::Set<3, 4, -1>, VDepth = cv::impl::(anonymous namespace)::Set<0, -1, -1>, sizePolicy = cv::impl::(anonymous namespace)::NONE]' Invalid number of channels in input image: 'VScn::contains(scn)' where 'scn' is 1
When I change the CV_8UC1 to CV_8UC2, I don't get error, but this is the result:

I was able to do the conversion using the following python code:

  1. with open(input_name, "rb") as src_file:
  2. raw_data = np.fromfile(src_file, dtype=np.uint8, count=img_width*img_height*2)
  3. im = raw_data.reshape(img_height, img_width, 2)
  4. rgb = cv2.cvtColor(im, cv2.COLOR_YUV2RGB_UYVY)

And this is the result:

yzckvree

yzckvree1#

问题 是 UYVY 是 2 个 字节 , 所以 我 必须 将 图像 的 大小 加倍 。

  1. int iYUV_Size = iSize.width * iSize.height * 2;
  2. Mat mSrc_YUV420(cv::Size(iSize.width, iSize.height),CV_8UC2);

中 的 每 一 个
它 工作 得 很 好 。
谢谢@micka 的 帮助 !

相关问题