OpenCV video和image互转

video --> image

#!/usr/bin/env python
# coding: utf-8


import os
import glob
import shutil
import numpy as np
import cv2 
from tqdm import tqdm
import multiprocessing
from argparse import ArgumentParser, SUPPRESS


def build_argparser():
    
    parser = ArgumentParser(add_help=False)
    args = parser.add_argument_group('Options')
    args.add_argument('-h', '--help', action='help', default=SUPPRESS, help='Show this help message and exit.')
    args.add_argument("-i", "--original_avi_path", help="Required. The absolute path of the input lidar .avi format data.", required=True, type=str)
    args.add_argument("-o", "--now_png_path",help="Required. The absolute path of the output lidar .png format data.", required=True, type=str)
    args.add_argument("-n", "--num_processes",help="Required. Number of processes,recommended 4-20", required=True, type=int)
    return parser

args = build_argparser().parse_args()
original_path = args.original_avi_path #后面加/
now_path      = args.now_png_path #"/media/ls/871d73ac-db1f-4753-b7fd-32262a9e36e0/Wsl/Wsl/PointCloud/Makedata/data/cloud_txt"
num_processes = args.num_processes


def try_multiP_read_avi_create_img(avi_path,now_path):
    
    avi_name = ((avi_path.split('/')[-1]).split('.')[-2]).split(' ')
    cap=cv2.VideoCapture(avi_path)
    i = 0
    while (cap.isOpened()):
        flag,frame=cap.read()
        if frame is None:
            break
        if flag == True:
            #print("4"*30)
            png_path = now_path + os.sep + avi_name[0] + "_"+ avi_name[1] + "_" + "%06d"%(i+1) +".png"
            #print("5"*30)
            cv2.imwrite(png_path,frame,[cv2.IMWRITE_JPEG_QUALITY,100])
            i += 1
            print(png_path)

        
def read_video_create_img(original_path,now_path):
    
    
    if os.path.exists(now_path):
        shutil.rmtree(now_path)
    os.mkdir(now_path)

    
    pool = multiprocessing.Pool(processes=num_processes)
    for avi_path in sorted(glob.glob(original_path + '/'+'*.avi')):
        #print(avi_path)
        #print("1"*30)
        pool.apply_async(try_multiP_read_avi_create_img, (avi_path,now_path))
    pool.close()
    pool.join()


read_video_create_img(original_path,now_path)

print("All files have been processed!!!")
print("All files have been processed!!!")
print("All files have been processed!!!")

图片隔5张取图

import os
import glob
import shutil
import cv2
import multiprocessing


original_path = "/media/wxf/Elements/data/video"  # 后面加/
now_path = "/media/wxf/Elements/data/video/img" # "/media/ls/871d73ac-db1f-4753-b7fd-32262a9e36e0/Wsl/Wsl/PointCloud/Makedata/data/cloud_txt"
num_processes = 6


def try_multiP_read_avi_create_img(avi_path, now_path):
    avi_name = ((avi_path.split('/')[-1]).split('.')[-2]).split(' ')[0]

    cap = cv2.VideoCapture(avi_path)
    i = 0
    while (cap.isOpened()):
        flag, frame = cap.read()
        if frame is None:
            break
        if flag == True:

            if i % 5 == 0:
                png_path = now_path + os.sep + avi_name + "_" + "%06d" % (i ) + ".png"
                print(png_path)
                cv2.imwrite(png_path, frame, [cv2.IMWRITE_JPEG_QUALITY, 100])
            i += 1



def read_video_create_img(original_path, now_path):
    if os.path.exists(now_path):
        shutil.rmtree(now_path)
    os.mkdir(now_path)

    pool = multiprocessing.Pool(processes=num_processes)
    for avi_path in sorted(glob.glob(original_path + os.sep + '*.avi')):
        print(avi_path)
        # print("1"*30)
        pool.apply_async(try_multiP_read_avi_create_img, (avi_path, now_path))
    pool.close()
    pool.join()

if __name__ == "__main__":
    read_video_create_img(original_path, now_path)

    print("All files have been processed!!!")
    print("All files have been processed!!!")
    print("All files have been processed!!!")

image --> video

import os
import cv2
import multiprocessing

# image path
im_dir = '/media/ls/871d73ac-db1f-4753-b7fd-32262a9e36e0/Wsl/Wsl/PointCloud/Makedata/data/bev_r'
# output video path
video_dir = '/media/ls/871d73ac-db1f-4753-b7fd-32262a9e36e0/Wsl/Wsl/PointCloud/Makedata/data/bev_video'
if not os.path.exists(video_dir):
    os.makedirs(video_dir)
# set saved fps
fps = 5
# get frames list
frames = sorted(os.listdir(im_dir))
#print(frames)
# w,h of image
img = cv2.imread(os.path.join(im_dir, frames[0]))
img_size = (img.shape[1], img.shape[0])
# # get seq name
seq_name = im_dir.split('/')[-1]
# # splice video_dir
video_dir = os.path.join(video_dir, seq_name + '.avi')
fourcc = cv2.VideoWriter_fourcc('M', 'J', 'P', 'G')
# # also can write like:fourcc = cv2.VideoWriter_fourcc(*'MJPG')
# # if want to write .mp4 file, use 'MP4V'
videowriter = cv2.VideoWriter(video_dir, fourcc, fps, img_size)


for frame in frames:
    f_path = os.path.join(im_dir, frame)
		image = cv2.imread(f_path)
    videowriter.write(image)
videowriter.release()
       
print("All Done !!!")
print("All Done !!!")
print("All Done !!!")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值