查看YUV格式文件

本文介绍了一种从RGB图片格式转换为YUV格式的方法,并使用libyuv库中的I420ToNV21函数将YUV I420格式转换为YUV NV21格式,最终将转换后的二进制数据保存为文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}

原图

效果图如下

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值