【问题标题】:Read many videos and convert them into images阅读许多视频并将它们转换为图像
【发布时间】:2020-11-10 23:08:56
【问题描述】:

我已经能够获得一个可以读取单个视频并将其转换为图像的程序。但是,实际上,我有很多视频,我想编写一个函数,可以一个一个地读取视频并将它们转换为图像。我的目标是将视频转换为图像,以便于处理。转换单个视频的代码如下。

import sys
import argparse

import cv2

vidcap = cv2.VideoCapture('E:/DATA/1/12.mp4')
path_out = "E:/DATA_Synth/12" 

success,image = vidcap.read()
#image=cv2.resize(image, (640, 480))
count = 0
while success:
  cv2.imwrite(path_out + "/frame%03d.jpg" % count, image)    
  #cv2.imwrite(path_out + "/frame%d.jpg" % count, image)
  success,image = vidcap.read()
  #image = cv2.resize(image, (640, 480))
  print ('Read a new frame: ', success)
  count += 1

任何建议和cmets将不胜感激

【问题讨论】:

  • 封装你当前的代码,从vidcap = ...count+=1在一个方法里面说:def get_frames(vid_file_path)然后你遍历所有的视频文件,比如:for vid_file_name in os.listdir("/your/local/directory")然后调用@ 987654326@ 在这个 for 循环内。
  • 非常感谢您的贡献。拜托,能给个例子吗?我想通过引用目录中相应视频的指示以不同方式保存帧。

标签: image opencv video


【解决方案1】:

我已将代码更新如下。

import os 
import sys
import argparse
import cv2
directory="E:/Training/video"
path_out = "E:/DATA_Synth/12" 
for vidfile in os.listdir(directory):
    if vidfile.endswith('.avi'):
        vidcap=cv2.VideoCapture(os.path.join(directory, vidfile))
        ## write your code here for converting the video to individual frames

        success,image = vidcap.read()
        #image=cv2.resize(image, (640, 480))
        count = 0
        while success:
            #vidcap.set(cv2.CAP_PROP_POS_MSEC,(count*1000))
            cv2.imwrite(path_out + "/frame%03d.jpg" % count, image)     # save frame as JPEG file
            #cv2.imwrite(path_out + "/frame%d.jpg" % count, image)
            success,image = vidcap.read()
            #image = cv2.resize(image, (640, 480))
            #print ('Read a new frame: ', success)
            count += 1
    else:
        continue

但是,仅保存了我目录中最后一个视频的帧。请问,如何修改代码,使这里写的框架名称

cv2.imwrite(path_out + "/frame%d.jpg" % count, image) 还可以包含相应视频的名称。

【讨论】:

    【解决方案2】:

    您应该创建一个循环来遍历包含所有视频的文件夹并选择每个视频并运行上述代码。

    import os 
    import sys
    import argparse
    import cv2
    directory="enter your folder directory for video"
    for vidfile in os.listdir(directory):
        if vidfile.endswith('.mp4'):
            vidcap=cv2.VideoCapture(os.path.join(directory, vidfile))
            ## write your code here for converting the video to individual frames
        else:
            continue
    

    【讨论】:

    • 亲爱的 ShriKumaran, 非常感谢您的回复。我已将代码修改如下。
    猜你喜欢
    • 2016-12-22
    • 1970-01-01
    • 2017-02-26
    • 2018-07-16
    • 2019-07-27
    • 1970-01-01
    • 2014-12-16
    • 1970-01-01
    相关资源
    最近更新 更多