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)。