From 7cafb371351cc5d5001159b7cd25056e5bcb2a57 Mon Sep 17 00:00:00 2001 From: Stefan Breunig Date: Thu, 23 Dec 2021 17:54:27 +0100 Subject: [PATCH] workaround when reading broken video frames Some videos are being read with additional fake/broken frames that may cause an unexpected early exit. This attempts to skip over these broken frames if more were expected, based on the initally acquired frame count. According to other reports upstream, the number of broken frames read varies. To avoid getting stuck in an endless loop, e.g. when the video is actually broken, this gives up after 1000 reads. see https://github.com/ultralytics/yolov5/issues/2064 see https://github.com/opencv/opencv/issues/15352 --- utils/datasets.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/utils/datasets.py b/utils/datasets.py index 79b871c9294b..8c9b26334bde 100755 --- a/utils/datasets.py +++ b/utils/datasets.py @@ -199,6 +199,16 @@ def __next__(self): # Read video self.mode = 'video' ret_val, img0 = self.cap.read() + + if not ret_val and self.frame < self.frames - 1: + fake_frame_skip = 1000 + while not ret_val and fake_frame_skip > 0: + fake_frame_skip -= 1 + ret_val, img0 = self.cap.read() + if not ret_val: + raise Exception( + f'Video stream ended unexpectedly. See this issue for details: https://github.com/ultralytics/yolov5/issues/2064') + while not ret_val: self.count += 1 self.cap.release()