gpt4 book ai didi

python - python 3.7 有没有办法手动清除内存?

转载 作者:太空宇宙 更新时间:2023-11-03 20:40:04 26 4
gpt4 key购买 nike

我正在尝试制作一个程序来删除视频中的背景,以便仅显示前景。它适用于短视频,但在较长的视频上,速度会呈指数级下降,并开始使用越来越多的内存,从而导致程序崩溃。

我尝试删除 for 循环中使用的变量,如下面的代码所示。

def video_generator(name_of_video, video, cap, number_of_frames):
check, frame = cap.read()
A = np.array([])
a = np.array([])

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 = np.append(A, gray)
a = np.append(a, 'row')
image = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
else:
break

B = np.resize(A, (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)

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)

del B
del background
gc.collect()

最佳答案

没有关于 Python 如何进行垃圾回收的明确资源(除了源代码本身),但这 3 个链接应该会给您一个很好的主意。

更新

该来源实际上非常有帮助。你能从中得到多少取决于你对 C 语言的理解程度,但这些评论实际上非常有帮助。跳到collect()函数,注释很好地解释了这个过程(尽管是非常技术性的术语)。

关于python - python 3.7 有没有办法手动清除内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56911316/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com