May-13-2021, 07:37 AM
Hi, I am trying to split a video based on the index and value stored in a text file. The index represents the frame number and value represents frame class. Then I create multiples lists based on the count of unique values in the text file and split the videos and append the frames to a list based on the frame number. But this operation on a larger video crashes my python because of memory issues. Is there a better way to do this? Here is an example text
In the code, I am referring to line 28. Thanks for your time.
https://pastebin.com/Shdw2C0dIn the code, I am referring to line 28. Thanks for your time.
import numpy as np
import cv2
import os
from collections import defaultdict
# Create a generator to let you loop over the video in a for loop
def get_frames(vid):
while True:
ret, frame = vid.read()
if not ret:
return
yield frame
def split_videos(txt_file, video_file):
with open(txt_file,'r') as f:
frame_numbers = list(map(int, f.read().split()))
size = len(set(frame_numbers))
offset = min(frame_numbers)
frame_groups = [[] for _ in range(7)]
video = cv2.VideoCapture(video_file)
for index, frame in zip(frame_numbers, get_frames(video)):
frame_groups[index - offset].append(frame)
video.release()
frame_groups_final = [x for x in frame_groups if x]
codec = cv2.VideoWriter_fourcc(*'XVID')
for index, group in enumerate(frame_groups_final):
# Arguments are filename, codec, framerate, resolution
print((len(group[0]), len(group[0][0])))
writer = cv2.VideoWriter(f'video_{index + offset}.avi', codec, 30.0, (len(group[0][0]), len(group[0])))
for frame in group:
writer.write(frame)
writer.release()
cv2.destroyAllWindows()
