• 【OpenCV】基于opencv的视频间隔抽帧脚本


    1. 通过指定frame_interval来确定帧间隔;

    2. 使用了joblib来加快处理速度。

    代码如下所示:

    1. import os
    2. import cv2
    3. import torchvision.transforms as T
    4. from PIL import Image
    5. from tqdm import tqdm
    6. from torchvision.utils import save_image
    7. from joblib import Parallel, delayed
    8. preprocess = T.Compose([T.Resize(256), T.CenterCrop(256), T.ToTensor()])
    9. def process_one_video(video_file, input_video_folder, target_fold, frame_interval=5):
    10. input_video_path = os.path.join(input_video_folder, video_file)
    11. video_id = os.path.splitext(video_file)[0]
    12. vidcap = cv2.VideoCapture(input_video_path)
    13. fps = vidcap.get(cv2.CAP_PROP_FPS)
    14. total_frame_num = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT))
    15. images_folder = os.path.join(target_fold, video_id)
    16. os.makedirs(images_folder, exist_ok=True)
    17. for i in range(0, total_frame_num, frame_interval):
    18. vidcap.set(cv2.CAP_PROP_POS_FRAMES, i)
    19. _, frame = vidcap.read()
    20. cv2_im = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    21. pil_im = Image.fromarray(cv2_im)
    22. image_tensor = preprocess(pil_im)
    23. save_image(image_tensor, os.path.join(images_folder, '{:06d}.jpg'.format(i)))
    24. # Handle the last frames if they are less than frame_interval
    25. last_frame_index = total_frame_num - 1
    26. if last_frame_index % frame_interval != 0:
    27. vidcap.set(cv2.CAP_PROP_POS_FRAMES, last_frame_index)
    28. _, last_frame = vidcap.read()
    29. cv2_im_last = cv2.cvtColor(last_frame, cv2.COLOR_BGR2RGB)
    30. pil_im_last = Image.fromarray(cv2_im_last)
    31. image_tensor_last = preprocess(pil_im_last)
    32. save_image(image_tensor_last, os.path.join(images_folder, '{:06d}.jpg'.format(last_frame_index)))
    33. print("Video {} has been processed. Total frames: {}".format(video_id, total_frame_num))
    34. #-----------------------------------#
    35. # 对视频进行并行处理
    36. #-----------------------------------#
    37. def extract_frames_parallel(input_video_folder, target_fold, frame_interval=5):
    38. video_files = [f for f in os.listdir(input_video_folder) if f.endswith('.mp4')]
    39. Parallel(n_jobs=256)(delayed(process_one_video)(video_file, input_video_folder, target_fold, frame_interval) for video_file in tqdm(video_files))
    40. if __name__ == "__main__":
    41. from argparse import ArgumentParser
    42. parser = ArgumentParser(description="Python script to extract frames from videos in a folder and save as jpgs.")
    43. parser.add_argument("-input_video_folder", type=str, default='/you/input/', help="The folder containing input videos.")
    44. parser.add_argument("-target_fold", type=str, default='/you/output/', help="The place to store the video frames.")
    45. parser.add_argument("-frame_interval", type=int, default=5, help="Interval between frames to extract.")
    46. args = parser.parse_args()
    47. extract_frames_parallel(args.input_video_folder, args.target_fold, args.frame_interval)

  • 相关阅读:
    CAD进阶练习(六)、CAD创建块后图形依然保持原状?
    客服聊天配置遗漏
    拥抱产业发展机遇 兑现5G商业价值
    java毕业设计云音乐后端内容管理系统Mybatis+系统+数据库+调试部署
    odoo 开发入门教程系列-一些用户界面
    论文精读:Swin Transformer: Hierarchical Vision Transformer using Shifted Windows
    ExtJs 7.X grid filter remote 自定义查询字段别名
    SENET和GateNet(推荐系统(embedding))
    微信发送图片就卡死,发送文件就死机的解决方案
    Qt | Qt For Android、Qt5.14.2安卓开发环境搭建详细步骤
  • 原文地址:https://blog.csdn.net/m0_47623548/article/details/139285039