Reputation: 11
i am doing infinite loop to save a video , when i kill the process the file of the video don't open , although the size of the video is very big and this tell me that he is saving the file , but for some reason he can't open it, the release is out of the loop . i would be happy to get solution to this problem thanks
while True:
frame, frame_id, time_video = next(self.distributor_frame)
if frame is not None:
self.out.write(frame)
else:
break
self.out.release()
Upvotes: 0
Views: 603
Reputation: 146
If you are working with classes, make sure you implement the __del__
method to properly release the video when the garbage collector deletes your object.
class MyClass:
def __init__(self, save_output_at:str, window_size_hw:tuple[int, int], save_output_fps:int):
self.out = cv2.VideoWriter(filename=save_output_at,
fourcc=cv2.VideoWriter_fourcc(*'mp4v'),
frameSize=window_size_hw[::-1],
fps=save_output_fps)
# [Your write bucles...]
def close(self):
"""
Release the video_writer.
"""
if self.out.isOpened():
self.out.release()
def __del__(self):
"""
Destructor.
"""
self.close()
Upvotes: 0
Reputation: 23042
If you just want to be able to CTRLC out of the program, you can catch Python's built-in KeyboardInterrupt
exception and then continue to close the resource.
try:
while True:
frame, frame_id, time_video = next(self.distributor_frame)
if frame is not None:
self.out.write(frame)
else:
break
except KeyboardInterrupt:
print('Stopped by keyboard interrupt')
self.out.release()
Normally, if you just send a SIGINT (CTRLC) to stop the script, it will raise an exception in Python, and this exception will cut the program. However, you can intercept this signal with except KeyboardInterrupt
and just simply do nothing, i.e., pass
or print
some message (like I did) or whatever you like. But since we caught the exception and aren't raising it again, the program doesn't end from the interrupt while inside that block.
Alternatively, subclass (or create a class that includes) the VideoWriter
and give it a context manager---then even if you get an exception, the resource will be closed. This answer has some good discussion about how to create a context manager yourself.
Upvotes: 2