由于内存泄漏,OpenCV视频编写器写入空白文件?

时间:2016-12-14 18:32:07

标签: python-2.7 opencv memory-leaks raspberry-pi

我尝试使用python2.7和opencv在raspberry pi上保存视频文件。下面显示的代码始终将几个视频文件(大小为16-18 Mb)保存到usb,但在前几个文件之后,文件大小降至6 kb,并且由于它们不会打开而显得空白。

我打开任务管理器在保存期间通过python监视内存使用情况,并注意到RSS内存不断增加,直到大约200 MB,即视频文件开始显示空白时。

这是内存泄漏的确定指标,还是应该运行其他测试?

以下代码中是否存在错误,并未正确释放变量?

import cv2
import numpy as np
import datetime

dispWidth = 640
dispHeight = 480
FPS = 6 

SetupNewVideoFile = True # state variable
VidCaptureDurationMinutes = 3 


filepath = '/media/pi/9CEE-5383/Videos/'

i = 1 # counter for the video file names

fourcc = cv2.cv.CV_FOURCC('X','V','I','D') 

while True:
    # timer section that ends running file saves and triggers a new file save
    Now = datetime.datetime.now() # refresh current time
    delta = Now - VidCaptureStartTime
    print('delta: ',delta.seconds,delta.days)
    if ((delta.seconds/60) >= VidCaptureDurationMinutes) and delta.days >= 0:
        print('delta: ',delta.seconds,delta.days)
        SetupNewVideoFile = True
        Vidoutput.release()
        cap.release()

    # setting up new file saves
    if SetupNewVideoFile:
        SetupNewVideoFile = False

        title = "Video_"+str(i)+".avi"
        i += 1
        fullpath = filepath + title
        print(fullpath)

        Vidoutput  = cv2.VideoWriter(fullpath, fourcc, FPS,(dispWidth,dispHeight))
        VidCaptureStartTime = datetime.datetime.now()  # updating video start time

        cap = cv2.VideoCapture(-1) # start video capture




    ret, frame = cap.read() 
    if ret:  # display and save if a frame was successfully read
        cv2.imshow('webcam',frame)
        Vidoutput.write(frame) # save the frames

    key = cv2.waitKey(1) & 0xFF
    if key == ord('q'): # quits program
        break


# clean up 
cap.release()
Vidoutput.release()
cv2.destroyAllWindows()
cv2.waitKey(1) # these seem to be needed to flush the cv actions
cv2.waitKey(1)
cv2.waitKey(1)
cv2.waitKey(1)

1 个答案:

答案 0 :(得分:0)

经过pympler模块函数和教程(https://pythonhosted.org/Pympler/muppy.html)的更多麻烦和帮助后,我的问题仍然看起来像是内存泄漏,但我无法解决具体的错误。

另一个S.O. post(Releasing memory in Python)提到了Python 3.3版本中对内存管理的改进:

“在Python 3.3中,小对象分配器被切换为使用匿名内存映射而不是堆,因此它应该在释放内存时表现更好。”

所以我切换到Python 3.3,现在代码保存了有效的视频文件,远远超过了我之前看到的错误时间。 这不是空白文件发生原因的答案,但至少它是一个解决方案。