如何使用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:\file\video\extract\video.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)发布于 2022-05-03 19:45:50
所有问题都会造成错误的凹痕。
您必须在count += 1之外运行if count % int(args.framegap) == 0:
您可以在if中运行它,所以在第一个框架之后,它会更改为count = 1,然后if不允许运行anercount += 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 ...https://stackoverflow.com/questions/72103377
复制相似问题