video generator with start and end position feature
This commit is contained in:
@@ -98,7 +98,7 @@ class VideoSink:
|
||||
|
||||
|
||||
def get_video_frames_generator(
|
||||
source_path: str, stride: int = 1
|
||||
source_path: str, stride: int = 1, start: int = 0, end: int = None
|
||||
) -> Generator[np.ndarray, None, None]:
|
||||
"""
|
||||
Get a generator that yields the frames of the video.
|
||||
@@ -106,7 +106,8 @@ def get_video_frames_generator(
|
||||
Args:
|
||||
source_path (str): The path of the video file.
|
||||
stride (int): Indicates the interval at which frames are returned, skipping stride - 1 frames between each.
|
||||
|
||||
start (int) : Indicates the starting position from which video should generate frames
|
||||
end (int): Indicates the ending position at which video should stop generating frames
|
||||
Returns:
|
||||
(Generator[np.ndarray, None, None]): A generator that yields the frames of the video.
|
||||
|
||||
@@ -114,22 +115,31 @@ def get_video_frames_generator(
|
||||
```python
|
||||
>>> import supervision as sv
|
||||
|
||||
>>> for frame in sv.get_video_frames_generator(source_path='source_video.mp4', stride=2):
|
||||
>>> for frame in sv.get_video_frames_generator(source_path='source_video.mp4', stride=2, start=1, end=1000):
|
||||
... ...
|
||||
```
|
||||
"""
|
||||
video = cv2.VideoCapture(source_path)
|
||||
if not video.isOpened():
|
||||
raise Exception(f"Could not open video at {source_path}")
|
||||
|
||||
total_frames = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
|
||||
if end > total_frames:
|
||||
raise Exception(f"Requested frames are outbound")
|
||||
start = max(start, 0)
|
||||
end = min(end, total_frames)
|
||||
frame_count = 0
|
||||
success, frame = video.read()
|
||||
while success:
|
||||
if frame_count % stride == 0:
|
||||
yield frame
|
||||
frame_position = start
|
||||
video.set(cv2.CAP_PROP_POS_FRAMES, frame_position)
|
||||
while True:
|
||||
success, frame = video.read()
|
||||
if not success:
|
||||
break
|
||||
frame_position += stride
|
||||
if frame_position >= end:
|
||||
break
|
||||
video.set(cv2.CAP_PROP_POS_FRAMES, frame_position)
|
||||
frame_count += 1
|
||||
|
||||
yield frame
|
||||
video.release()
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user