对文件目录中的多个视频进行帧提取



虽然有几种方法可以从视频中提取帧,但我想创建一个loop来提取目录中存在的多个视频的帧。

要包含的一个主要关键特性是以串行方式对帧进行编号(即1-60,然后61-120和进一步)。一种方法是每次提取一个视频,然后对所有视频重复,但这太长了。

试过的代码:(从某个地方得到它,并尝试根据我的目录更改)

i = 1  # Counter of first video
input_filenames='Dataset/videos'
for input_filename in intput_filenames:
cap = cv2.VideoCapture(input_filename)

while True:
ret, frame = cap.read()  # Read frame from first video
if ret:
cv2.imwrite(str(i) + '.jpg', frame)  
cv2.imshow('frame', frame)  # Displaying frame for testing
i += 1 # Advance file counter
else:
break # Break the interal loop when res status is False.
cv2.waitKey(100) #Wait 100msec 
cap.release() 

经过大量的搜索和尝试,我最终达到了迭代目录中的视频文件,并按连续序列提取帧的目的。

代码:

def frames_multiple_videos(filenames):
i = 1  # Counter of first video
for j in filenames:
cap = cv2.VideoCapture(j)
while True:
ret, frame = cap.read()  # Read frame from first video

if ret!=True:
cv2.imwrite(filenames +'frame' + str(i) + '.jpg', frame)  # Write frame to JPEG file (frame1.jpg, frame2.jpg, ...)
i += 1 # next file counter
else:
break
cv2.waitKey(100) #(for debugging)
cap.release() #Release must be inside the outer loop

all_frame=frames_multiple_videos('*your_directory*')

如果我猜对了,您想在特定帧数下提取目录中的每个视频,对吗?您可以试试这个代码!

for line in f.readlines(): #reading each video in directory, in this case I save in txt and read each line
frame_reader = imageio.get_reader(link_video, 'ffmpeg', mode='I')
start_idx, end_idx = 10, 70
save_mat = np.full((output_size, output_size, 3, 1), 0) #please define the size of frame
for frame_num, frame in enumerate(frame_reader):
if frame_num >= end_idx:
break
if frame_num <= start_idx:
continue
save_mat = np.concatenate((save_mat, np.expand_dims(frame, axis=3)), axis=3)

相关内容

  • 没有找到相关文章