项目中需要使用opencv对相机读取的yuv格式数据做处理,故记录在此。
注意下方代码中frame_len参数,因为我的yuv文件是YUYV 4:2:2格式,每个像素深度为16位(2x8bit),故数据长度需x2。可推知若为YUV 4:2:0,像素深度为12位,则x1.5。
关于YUV存储方式的详细信息可以参考https://blog.csdn.net/qq_25333681/article/details/89970216
import numpy as np
import cv2
import os
def convert_yuyv(yuv_file):
yuv_file = open(yuv_file, 'rb')
frame_len = 352 * 288 * 2
shape1 = (288, 352*2) # 用于可视化raw yuv,比例可以任意
shape2 = (288, 352, 2) # 用于yuv转bgr,对于yuyv格式,需要2通道
raw = yuv_file.read(int(frame_len))
yuv = np.frombuffer(raw, dtype=np.uint8)
yuv = yuv.reshape(shape1)
cv2.imshow("raw yuv", yuv)
cv2.waitKey(0)
yuv = yuv.reshape(shape2)
bgr = cv2.cvtColor(yuv, cv2.COLOR_YUV2BGR_YUYV)
cv2.imshow("YUV2BGR", bgr)
cv2.waitKey(0)