如何在循环中使用OpenCV VideoCapture?

问题描述 投票:-1回答:1

我正在尝试使用VideoCapture将视频转换为帧。在我的目录'startpath'中,我有多个.mp4文件。我想运行一个for循环,使用该循环所有这些文件将转换为.png帧,并将存储在每个视频的单独文件夹中。

但我不知道如何使用for循环使其适用于多个文件。

如果只有一个文件,我能够使代码工作。以下是代码 - :

import cv2
import os, fnmatch

startpath='C:/Users/work/Documents/data'
listOfFiles = os.listdir(startpath)

print(listOfFiles)
pattern = "*.mp4"
names = []
for entry in listOfFiles:  
    if fnmatch.fnmatch(entry, pattern):
        names.append(entry)
print (names) #this list has all the .mp4 files
vidcap=cv2.VideoCapture(C:/Users/work/Downloads/SampleVideo_1280x720_30mb.mp4)
success,image = vidcap.read()
count = 0
hello = os.path.join(startpath, 'output')
output = os.mkdir(hello)
os.chdir(hello)
while success:
   cv2.imwrite("frame%d.jpg" % count, image) 
   # save frame as JPEG file
   success,image = vidcap.read()
   print('Read a new frame: ', success)
   count += 1

任何帮助都将受到高度赞赏。

谢谢

python opencv video-capture
1个回答
0
投票

试试这个代码。我还没有运行它。但是这应该给出如何解决问题的想法。

import cv2
import os, fnmatch

startpath='C:/Users/work/Documents/data'
listOfFiles = os.listdir(startpath)

print(listOfFiles)
pattern = "*.mp4"
names = []
for entry in listOfFiles:  
    if fnmatch.fnmatch(entry, pattern):
        names.append(entry)
print (names) #this list has all the .mp4 files
for eachnames in names:
  vidcap=cv2.VideoCapture('C:/Users/work/Documents/data'+ eachnames)
  success,image = vidcap.read()
  count = 0
  hello = os.path.join(startpath, eachnames.split('.')[0])
  output = os.mkdir(hello)
 # os.chdir(hello)
  count=0
  while success:
    cv2.imwrite("frame%d.jpg" % count, hello+'/'+image) 
    # save frame as JPEG file
    success,image = vidcap.read()
    print('Read a new frame: ', success)
    count += 1

我刚添加了一个循环来遍历所有文件名并使用该名称来创建一个文件夹。此名称也用于在imwrite中保存。

© www.soinside.com 2019 - 2024. All rights reserved.