随着时间的流逝,该程序开始运行的速度越来越慢,甚至无法使用。
我尝试删除循环中使用的变量,使用cap.release()释放与cv2一起使用的视频,并追加到列表中而不是使用np.append()函数。
def video_generator(name_of_video, video, cap, number_of_frames):
check, frame = cap.read()
A = []
a = []
if cap.isOpened():
width = int(cap.get(3))
height = int(cap.get(4))
dims = (height, width)
while cap.isOpened():
check, frame = cap.read()
if check:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY).flatten()
A.append(gray)
a.append('row')
else:
break
Data = np.array(A)
B = np.resize(Data, (number_of_frames, width * height))
U, S, V = decomposition.randomized_svd(B, 2)
background = U @ np.diag(S) @ V
foreground = ([])
def generate_frames(B, background):
for i in range(number_of_frames):
foreground = np.reshape(B[i] - background[i], dims)
frame = plt.imshow(foreground, cmap = 'gray')
plt.savefig('D:/Python_Programs/BR_SVD/Frames/' + name_of_video + '/file_' + str(i + x * number_of_frames).zfill(2) + '.png')
del frame
del foreground
gc.collect()
generate_frames(B, background)
del B
del background
gc.collect()
cap.release()
if number_of_frames_initial <= 200:
cap = cv2.VideoCapture(video)
video_generator(name_of_video, video_initial, cap_initial, number_of_frames_initial)
else:
number_of_videos = int(number_of_frames_initial/200 + 1)
time_of_videos = duration/number_of_videos
for x in range (number_of_videos):
subprocess.call ([
'ffmpeg', '-i', video_initial, '-ss', str(time_of_videos * x), '-t', str(time_of_videos), 'D:/Python_Programs/BR_SVD/Temp_Videos/video_%02d.mp4' % x])
video = 'D:/Python_Programs/BR_SVD/Temp_Videos/video_%02d.mp4' % x
cap = cv2.VideoCapture(video)
number_of_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
video_generator(name_of_video, video, cap, number_of_frames)
此代码接收视频,然后输出原始视频前景的黑白视频。