python之图片与视频互转

图片转视频

def image_to_video(image_dir, video_dir, fps):
    im_list = [i for i in os.listdir(image_dir) if i.endswith('jpg')]
    im_list.sort(key=lambda x: int(x.replace("frame", "").split('.')[0]))  # 最好再看看图片顺序对不

    # fourcc = cv2.VideoWriter_fourcc(*'XVID')  # opencv版本是3
    # fourcc = cv2.VideoWriter_fourcc(*'MJPG')  # avi
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')  # mp4
    videoWriter = cv2.VideoWriter(video_dir, fourcc, fps, (1920, 1080))
    # videoWriter = cv2.VideoWriter(video_dir, fourcc, fps, img_size)

    for i in im_list:
        im_name = os.path.join(image_dir ,i)
        frame = cv2.imdecode(np.fromfile(im_name, dtype=np.uint8), -1)
        frame = cv2.resize(frame, (1920, 1080)) #必须设置此步骤,不然文件夹下分辨不一致的图片不会写入视频
        videoWriter.write(frame)


    videoWriter.release()
    print('finish')

视频转图片

def video_to_img(video_path, frame_save_dir, frame_interval=1000):
    """

    :param video_path: 视频路径
    :param frame_save_dir: 视频帧的存储路径
    :param frame_interval: 视频帧的采样间隔
    :return:
    """
    cap = cv2.VideoCapture(video_path, )
    suc = cap.isOpened()
    frame_count = 0
    while suc:
        suc, frame = cap.read()  # suc是bool变量,用于判断视频帧是否存在
        frame_count += 1
        if (suc and frame_count % frame_interval == 0):
            save_path = os.path.join(frame_save_dir, "{:04d}.jpg".format(frame_count))  # 格式化命名,不足补零
            cv2.imwrite(save_path, frame)
            print(frame_count, suc)
    cap.release()

图片压缩

def image_compress(path,new_path):
    if not os.path.exists(new_path):
        os.makedirs(new_path)
    # 获取文件夹里面的图片
    path_list = [path +os.sep + i for i in os.listdir(path)]
    # print(path_list)
    # 循环图片路径,依次对图片进行压缩
    for _path in path_list:
        im = Image.open(_path)
        (x, y) = im.size  # 读取图片尺寸(像素)
        x_1 = 800  # 定义缩小后的标准宽度
        y_1 = int(y * x_1 / x)  # 计算缩小后的高度
        # x_1 = x  # 定义缩小后的标准宽度
        # y_1 = y  # 计算缩小后的高度
        out = im.resize((x_1, y_1), Image.ANTIALIAS)  # 改变尺寸,保持图片高品质
        # 判断图片的通道模式,若图片在RGBA模式下,需先将其转变为RGB模式
        if out.mode == 'RGBA':
            # 转化为rgb格式
            out = out.convert('RGB')
        # 最后保存为jpg格式的图片,这里因为图片本身为jpg所以后缀不更改
        out.save(f'{new_path}{os.sep}{_path.split(os.sep)[-1]}')

批量复制图片

def batch_copy_file(source_file,out_filepath,copy_num):
    if not os.path.exists(out_filepath):
        os.makedirs(out_filepath)
    if os.path.isdir(source_file):
        source_files=[source_file+os.sep+i for i in os.listdir(source_file) ]
    elif os.path.isfile(source_file):
        source_files=[source_file]
    else:
        raise Exception("文件夹不存在")
    frame_num=1
    for _source in source_files:
        # source_file_name=_source.split(os.sep)[-1]
        # print(source_file_name)
        for i in range(copy_num):
            # shutil.copyfile(_source,os.path.join(out_filepath,source_file_name.split('.')[0]+'-'+str(i)+'.'+source_file_name.split('.')[-1]))
            shutil.copyfile(_source,os.path.join(out_filepath,"frame"+str(frame_num)+'.jpg'))
            frame_num+=1
posted @ 2022-12-22 09:57  wan了个蛋  阅读(310)  评论(0编辑  收藏  举报