RGB图片文件转换为YUV格式后,将YUV数据以二进制形式写到文件中,使用7yuv软件查看。
#include<iostream>
#include<cstdio>
#include<string>
#include"opencv2/opencv.hpp"
#include "libyuv/scale.h"
#include "libyuv/convert_from.h"
using namespace std;
/*
int I420ToNV21(const uint8* src_y, int src_stride_y,
const uint8* src_u, int src_stride_u,
const uint8* src_v, int src_stride_v,
uint8* dst_y, int dst_stride_y,
uint8* dst_vu, int dst_stride_vu,
int width, int height);
*/
const std::string strCHE = "../unit_test/testdata/src.jpg";
const std::string strSHAN = "../unit_test/testdata/shan.jpg";
const std::string strTA = "../unit_test/testdata/ta.jpg";
int main(int argc, char* argv[])
{
cv::Mat src_rgb = cv::imread(strTA);
cv::Mat src_yuv_i420;
// transform RGB to YUV-I420
cv::cvtColor(src_rgb, src_yuv_i420, CV_BGR2YUV_I420);
int nWidth_rgb = src_rgb.cols;
int nHeight_rgb = src_rgb.rows;
int src_stride_y = nWidth_rgb;
int src_stride_u = nWidth_rgb / 2;
int src_stride_v = nWidth_rgb / 2;
int nWidth_yuv = src_yuv_i420.cols;
int nHeight_yuv = src_yuv_i420.rows;
cv::Mat dst_yuv_nv21(nHeight_rgb * 3 / 2, nWidth_rgb, CV_8UC1);
int dst_stride_y = nWidth_rgb;
int dst_stride_vu = nWidth_rgb;
libyuv::I420ToNV21(src_yuv_i420.data, src_stride_y, src_yuv_i420.data + nWidth_rgb * nHeight_rgb, src_stride_u, src_yuv_i420.data + nWidth_rgb * nHeight_rgb * 5 / 4, src_stride_v,
dst_yuv_nv21.data, dst_stride_y, dst_yuv_nv21.data + nWidth_rgb * nHeight_rgb, dst_stride_vu, nWidth_yuv, nHeight_yuv);
//cv::imwrite("src_yuv_nv21.jpg", dst_yuv_nv21);
FILE* fp = fopen("out_nv21_mat.yuv", "wb");
fwrite(dst_yuv_nv21.data, 1, nWidth_yuv * nHeight_yuv * 3 / 2, fp);
fclose(fp);
fp = NULL;
return 0;
}
原图
效果图如下