user2820068
user2820068

Reputation: 79

cv2 - Prevent file from getting corrupted if script gets terminated?

I'm trying to make a security camera script with cv2. It works as long as the script is running but if it gets terminated for any reason the output file gets corrupted. Is there a way to make sure that the release function gets called no matter what or is there a better way to record video that can't be corrupted? I'm open to suggestions about other libraries, sub-processes, what have you.

I tried using a try statement:

import cv2

video_filename = 'webcam_test.mp4'
fourcc = cv2.VideoWriter_fourcc(*'X264')
frame_rate = 30
cap = cv2.VideoCapture(0)
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
writer = cv2.VideoWriter(video_filename, fourcc, frame_rate, (width,height))

try:
    while True:
        ret, frame = cap.read()
        writer.write(frame)
finally:
    cap.release()
    writer.release()

I also tried atexit:

import cv2
import atexit

video_filename = 'webcam_test.mp4'
fourcc = cv2.VideoWriter_fourcc(*'X264')
frame_rate = 30
cap = cv2.VideoCapture(0)
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
writer = cv2.VideoWriter(video_filename, fourcc, frame_rate, (width,height))

def release_resources():
    cap.release()
    writer.release()

atexit.register(release_resources)

while True:
    ret, frame = cap.read()
    writer.write(frame)

Upvotes: 0

Views: 73

Answers (0)

Related Questions