python YUV420视频转图像帧

YUV420p视频转成多帧图像

import os
import cv2
import numpy as np
from typing import List

def YUVvideo2IMGs(file, savepath, height, width ):
    """
    Convert the YUV video to RGB images and save the images at the target folder
    Args:
        file: input yuv file name
        savepath: save path of each RGB images
        height: height of images
        width: width of images

    Returns:

    """
    img_size = int(width * height * 3 / 2)

    frames = int(os.path.getsize(file) / img_size)
    with open(file, "rb") as f:
        for frame_idx in range(frames):
            yuv = np.zeros(shape=img_size, dtype='uint8', order='C')
            for j in range(img_size):
                yuv[j] = ord(f.read(1))
            img = yuv.reshape((height * 3 // 2, width)).astype('uint8')
            bgr_img = cv2.cvtColor(img, cv2.COLOR_YUV2BGR_I420)
            if bgr_img is not None:
                cv2.imwrite(os.path.join(savepath, "f%03d.png" % (frame_idx+1)), bgr_img)

多帧图像转成YUV420p

import os
import cv2
import numpy as np
from typing import List

IMG_EXTENSIONS = (
    ".jpg",
    ".jpeg",
    ".png",
    ".ppm",
    ".bmp",
    ".pgm",
    ".tif",
    ".tiff",
    ".webp",
)

def collect_images(rootpath: str) -> List[str]:
    return [
        os.path.join(rootpath, f)
        for f in os.listdir(rootpath)
        if os.path.splitext(f)[-1].lower() in IMG_EXTENSIONS
    ]

def IMG2YUVvideo(Imgdir, YUVfile):
    """

    :param Imgdir: input image folder of the
    :param YUVfile:
    :return:
    """
    Imagepaths = sorted(collect_images(Imgdir))
    img = cv2.imread(Imagepaths[0])
    (height, width, _) = img.shape
    with open(YUVfile, "wb+") as f:
        for i in Imagepaths:
            img = cv2.imread(i)
            YUV = cv2.cvtColor(img, cv2.COLOR_BGR2YUV_I420)
            YUV = YUV.reshape(height * width * 3 // 2)
            f.write(np.array(YUV, dtype=np.uint8).tobytes())
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值