Python或C++读写YUV

Python 读取YUV

用numpy.fromfile()函数来读取YUV文件。

import numpy as np

def get_yuv_frame(yuv_path, width, height):
    yuv_list = np.fromfile(yuv_path, np.uint16) # 10 bits
    # yuv_list = np.fromfile(yuv_path, np.uint8) # 8 bits

    size_uv = width * height # YUV420
    # size_uv = width * height // 4 # YUV444

    pic_y = list(yuv_list[: width * height])
    pic_u = list(yuv_list[width * height : width * height + size_uv])
    pic_v = list(yuv_list[width * height + size_uv :])
    
    return [pic_y, pic_u, pic_v]

Python 写入YUV

使用python IO,以二进制文件按序(从Y通道至V通道,从上到下,从左至右)写入每个像素值。

import numpy as np

yuv_list = [pic_y, pic_u, pic_v] # 数据格式为 [list, list, list]

def store_yuv_frame(yuv_path, yuv_list):
    with open(yuv_path, 'wb') as f: # 以二进制文件写入
        for channel in yuv_list:
            for elem in channel:
                f.write(np.uint16(elem)) # 10 bits
                # f.write(np.uint8(elem)) # 8 bits

注意指定数据类型(yuv 10 bits对应np.uint16,yuv 8 bits对应np.uint8)。

CPP读取YUV

利用fread读取数据到vector中,

#include <vector>
#include <iostream>

template<typename yuv_t>
std::vector<yuv_t> read_yuv420(const char *yuv_path, int height, int width)
{
  FILE *file = fopen(yuv_path, "rb"); // * read binary

  const int num_elems  = height * width * 3 / 2;
  std::vector<yuv_t> yuv420(num_elems);
  fread((char *) &yuv420[0], sizeof(yuv_t), yuv420.size(), file);
  fclose(file);
  return yuv420;
}

CPP写入YUV

利用fwrite将vector中数据写入YUV,

#include <vector>
#include <iostream>

template<typename yuv_t> 
bool write_yuv420(std::vector<yuv_t> yuv420, const char *yuv_path, int height, int width)
{
  FILE *file = std::fopen(yuv_path, "wb+");

  fwrite((char *) &yuv420[0], sizeof(yuv_t), yuv420.size(), file);
  fclose(file);
  return true;
}

注意指定数据类型(yuv 10 bits对应uint16_t,yuv 8 bits对应uint8_t)。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值