From f0aeded1424c9962da851686cd31c77b17537a03 Mon Sep 17 00:00:00 2001 From: Lycoris <32864669+lycoris1129@users.noreply.github.com> Date: Sat, 18 Oct 2025 12:47:07 +0800 Subject: [PATCH] Fixes failed to delete images because the timing of gc is uncertain (#1710) * Prevents resource leak in video_utils when getting width and height Added the with statement when opening the image to ensure that the file handle is properly closed after its contents are read. Otherwise, shutil.rmtree(img_dir) will fail when called after the encode_video_frames function completes. Signed-off-by: Lycoris <32864669+lycoris1129@users.noreply.github.com> --------- Signed-off-by: Lycoris <32864669+lycoris1129@users.noreply.github.com> --- src/lerobot/datasets/video_utils.py | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/lerobot/datasets/video_utils.py b/src/lerobot/datasets/video_utils.py index 740cdb60..0de79191 100644 --- a/src/lerobot/datasets/video_utils.py +++ b/src/lerobot/datasets/video_utils.py @@ -342,8 +342,8 @@ def encode_video_frames( # Define video output frame size (assuming all input frames are the same size) if len(input_list) == 0: raise FileNotFoundError(f"No images found in {imgs_dir}.") - dummy_image = Image.open(input_list[0]) - width, height = dummy_image.size + with Image.open(input_list[0]) as dummy_image: + width, height = dummy_image.size # Define video codec options video_options = {} @@ -373,11 +373,12 @@ def encode_video_frames( # Loop through input frames and encode them for input_data in input_list: - input_image = Image.open(input_data).convert("RGB") - input_frame = av.VideoFrame.from_image(input_image) - packet = output_stream.encode(input_frame) - if packet: - output.mux(packet) + with Image.open(input_data) as input_image: + input_image = input_image.convert("RGB") + input_frame = av.VideoFrame.from_image(input_image) + packet = output_stream.encode(input_frame) + if packet: + output.mux(packet) # Flush the encoder packet = output_stream.encode()