我如何用python脚本从视频中提取每#n帧?



如何使用python脚本从视频中提取每#n帧?

我不提取每一个int(args.framegap)不挂所以谁能告诉我我做错了什么?

这是我的脚本,但它挂在提取帧,谁知道为什么或如何解决这个问题?

我也希望他们的名字正确,例如,如果我提取每5帧他们应该命名为001.png, 006.png, 011.png等。

感谢
import argparse
import cv2
import time
import os
import shutil
parser = argparse.ArgumentParser(description='arguments')
parser.add_argument('--videofile', type=str, help='path to your video file, for example --videofile C:filevideoextractvideo.mp4')
parser.add_argument('--projectname', type=str, help='name of the project to create the directories')
parser.add_argument('--framegap', type=int, help='name of the project to create the directories')
args = parser.parse_args()
doc_path = os.path.expanduser('~Documents')
data_path = os.path.expanduser('~Documents\visionsofchaos\fewshot\data')

train_filtered = data_path+str(args.projectname)+'_train'+'\'+'input_filtered'
#take every #nth frame
def video_to_frames(input_loc, output_loc):
"""Function to extract frames from input video file
and save them as separate frames in an output directory.
Args:
input_loc: Input video file.
output_loc: Output directory to save the frames.
Returns:
None
"""
try:
os.mkdir(output_loc)
except OSError:
pass
# Log the time
time_start = time.time()
# Start capturing the feed
cap = cv2.VideoCapture(input_loc)
# Find the number of frames
video_length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) - 1
print ("Number of frames: ", video_length)
count = 0
print ("Converting video..n")
# Start converting the video
while cap.isOpened():
# Extract the frame
ret, frame = cap.read()
if not ret:
continue
# Write the results back to output location.
if count % int(args.framegap) == 0:
cv2.imwrite(train_filtered + "/%#03d.png" % (count+1), frame)
count += 1
# If there are no more frames left
if (count > (video_length-1)):
# Log the time again
time_end = time.time()
# Release the feed
cap.release()
# Print stats
print ("Done extracting frames.n%d frames extracted" % count)
print ("It took %d seconds forconversion." % (time_end-time_start))
break
if __name__=="__main__":
input_loc = args.videofile
output_loc = data_path + '\' + args.projectname + '_gen\input_filtered'
video_to_frames(input_loc, output_loc)

所有的问题都有错误的缩进


你必须在if count % int(args.framegap) == 0:之外运行count += 1

你在if中运行它,所以在第一帧之后它改变为count = 1,后来if不允许运行另一个count += 1,所以它总是count = 1,这阻塞了所有代码。

count = -1
# loop
count += 1
# --- the same indentations ---
if count % int(args.framegap) == 0:
#.... code ...

count = 0
# loop

if count % int(args.framegap) == 0:
#.... code ...
# --- the same indentations ---
count += 1

我认为你也应该改变另一个if (count > (video_length-1))的缩进,因为它也在if count % int(args.framegap) == 0:里面,它可以制造问题

count = 0
# loop
if count % int(args.framegap) == 0:
#.... code ...
# --- the same indentations ---
count += 1
# --- the same indentations ---

if count > (video_length-1):  
#.... code ...

最新更新