栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python YUV420视频转图像帧

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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())
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/461643.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号