Python video extracts pictures, renames the pictures and puts them in the same folder

This blog can be said to benefit mankind, it is very convenient, take it away and use it directly!

1. Capture a picture from the video in the folder

       About hundreds of videos, the output result is a video intercepted file in a folder, and hundreds of videos are hundreds of folders.

# 视频提取图片
import os
import cv2

def save_img2():  #  提取视频中图片 按照每秒提取   间隔是视频帧率
    video_path = r'/home/dell/mmaction2/data/video/notrain/'  # 视频所在的路径
    f_save_path = '/home/dell/mmaction2/data/image/notrain/'  # 保存图片的上级目录
    videos = os.listdir(video_path) 
    for video_name in videos:  # 依次读取视频文件
        file_name = video_name.split('.')[0]  
        folder_name = f_save_path + file_name 
        os.makedirs(folder_name, exist_ok=True)  
        vc = cv2.VideoCapture(video_path + video_name)  
        fps = vc.get(cv2.CAP_PROP_FPS)  # 获取帧率
        print(fps)  # 帧率可能不是整数  需要取整
        rval = vc.isOpened()  # 判断视频是否打开  返回True或False
        c = 10
        while rval:  # 循环读取视频帧
            rval, frame = vc.read() 
            pic_path = folder_name + '/'
            if rval:

                if (c % round(fps) == 6):  # 每隔fps帧进行存储操作   ,可自行指定间隔
                    cv2.imwrite(pic_path + 'video_' + str(round(c/fps)) + '.png', frame) #存储为图像的命名 video_数字(第几个文件).png
                    print('video_' + str(round(c/fps)) + '.png')
                cv2.waitKey(1)  
                c = c + 0.25 #改间隔截
            else:
                break
        vc.release()
        print('save_success' + folder_name)


save_img2()

2. Transfer pictures from different folders to the same folder

With so many folders, I want to put all the output pictures in the same folder, and the names correspond to the numbers

# 将不同文件夹下的图片转到同一文件夹下
import os
import shutil

src = '/home/dell/mmaction2/data/image/weaktrain/'  #要转化的大文件夹,大文件夹下是很多小文件夹
target = '/home/dell/mmaction2/data/image/weaktrain1/'  #转入的文件夹

path = os.listdir(src)  # 000 001 002
path.sort()
count = len(path)
# print(path)#['000', '001', '002',……‘029’]
num = 1
for root, dirs, files in os.walk(src):
    files.sort()
    for j in range(len(files)):
        if files[j].endswith('png'):
            source = os.path.join(root, files[j])
            shutil.copy(source, os.path.join(target, 'trans_' + str(num).zfill(4) + '.png'))  # 文件命名
            num += 1

Guess you like

Origin blog.csdn.net/Zosse/article/details/129406081