注意
yuv 也有很多种格式
cv2.COLOR_YUV2BGR_NV12 对应的格式
所有格式C++
https://docs.opencv.org/4.2.0/d8/d01/group__imgproc__color__conversions.html#ga4e0972be5de079fed4e3a10e24ef5ef0
例子:
. - #COLOR_YUV2BGR_NV12
. - #COLOR_YUV2RGB_NV12
. - #COLOR_YUV2BGRA_NV12
. - #COLOR_YUV2RGBA_NV12
. - #COLOR_YUV2BGR_NV21
. - #COLOR_YUV2RGB_NV21
. - #COLOR_YUV2BGRA_NV21
. - #COLOR_YUV2RGBA_NV21
查清楚格式即可
import os
import cv2
import numpy as np
videofile = "/Parking/img.yuv" # 输入视频
video_save_path = "/yuanqu.avi" # 输出视频
fp = open(videofile, 'rb')
filename = videofile.split('/')[-1][:-4] # for save
# fp_out = open(savepath+filename+"_out.yuv", 'wb')
height = 192
width = 384
framesize = height * width * 3 // 2
h_h = height // 2
h_w = width // 2
fp.seek(0, 2)
ps = fp.tell()
numfrm = ps // framesize
fp.seek(0, 0)
output_video_fps = 25 # 保存视频的FPS,可以适当调整
size = (384, 192)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
videoWriter = cv2.VideoWriter(
video_save_path, fourcc, output_video_fps,
size) # 最后一个是保存图片的尺寸
for i in range(numfrm):
print("%d/ %d"%(i, numfrm))
Yt = np.zeros(shape=(height, width), dtype='uint8')
Ut = np.zeros(shape=(h_h, h_w), dtype='uint8')
Vt = np.zeros(shape=(h_h, h_w), dtype='uint8')
for m in range(height):
for n in range(width):
Yt[m, n] = ord(fp.read(1))
for m in range(h_h):
for n in range(h_w):
Ut[m, n] = ord(fp.read(1))
for m in range(h_h):
for n in range(h_w):
Vt[m, n] = ord(fp.read(1))
img = np.concatenate((Yt.reshape(-1), Ut.reshape(-1), Vt.reshape(-1)))
img = img.reshape((height*3 // 2, width)).astype('uint8')
bgr_img = cv2.cvtColor(img, cv2.COLOR_YUV2BGR_NV12)
videoWriter.write(bgr_img)
# cv2.imshow("image", bgr_img)
# cv2.waitKey(0)
videoWriter.release()