Skip to content

Video slicer

A class to cut a video into many images.

This class takes a video file and saves its frames as separate image files in a folder.

Source code in tools/video_slicer.py
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
class VideoSlicer:
    """A class to cut a video into many images.

    This class takes a video file and saves its frames as separate image files in a folder.
    """
    def __init__(self):
        """Initializes the VideoSlicer.

        It sets the initial state of the slicer.
        """
        self.__sliced: bool = False


    def slice(self, source_file: Path, target_dir: Path, suffix: str = ".jpg", step: float = 1) -> tuple:
        """Cuts the video into images and saves them to a folder.

        Args:
            source_file (Path): The path to the video file you want to cut.
            target_dir (Path): The folder where you want to save the images.
            suffix (str): The file extension for the images (for example, '.jpg'). Defaults to '.jpg'.
            step (float): How many seconds to wait between saving images. Defaults to 1.

        Returns:
            tuple: A tuple containing:
                - bool: True if the video was sliced successfully, False otherwise.
                - int: The total number of images saved.
        """
        cap = cv2.VideoCapture(str(source_file))

        if not cap.isOpened():
            return self.sliced, 0

        fps = cap.get(cv2.CAP_PROP_FPS)
        step_frames = int(fps * step)
        img_counter = 0
        frame_id = 0

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

            if not ret:
                break

            if frame_id % step_frames == 0:
                new_filename = f"{source_file.stem}_{img_counter}{suffix}"
                file_path = target_dir / new_filename
                cv2.imwrite(str(file_path), frame)
                img_counter += 1

            frame_id += 1

        cap.release()
        self.__sliced = True
        return self.sliced, img_counter


    @property
    def sliced(self) -> bool:
        """Checks if the video has been sliced.

        Returns:
            bool: True if the slice method was called and finished, False otherwise.
        """
        return self.__sliced

sliced property

Checks if the video has been sliced.

Returns:

Name Type Description
bool bool

True if the slice method was called and finished, False otherwise.

__init__()

Initializes the VideoSlicer.

It sets the initial state of the slicer.

Source code in tools/video_slicer.py
 9
10
11
12
13
14
def __init__(self):
    """Initializes the VideoSlicer.

    It sets the initial state of the slicer.
    """
    self.__sliced: bool = False

slice(source_file, target_dir, suffix='.jpg', step=1)

Cuts the video into images and saves them to a folder.

Parameters:

Name Type Description Default
source_file Path

The path to the video file you want to cut.

required
target_dir Path

The folder where you want to save the images.

required
suffix str

The file extension for the images (for example, '.jpg'). Defaults to '.jpg'.

'.jpg'
step float

How many seconds to wait between saving images. Defaults to 1.

1

Returns:

Name Type Description
tuple tuple

A tuple containing: - bool: True if the video was sliced successfully, False otherwise. - int: The total number of images saved.

Source code in tools/video_slicer.py
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
def slice(self, source_file: Path, target_dir: Path, suffix: str = ".jpg", step: float = 1) -> tuple:
    """Cuts the video into images and saves them to a folder.

    Args:
        source_file (Path): The path to the video file you want to cut.
        target_dir (Path): The folder where you want to save the images.
        suffix (str): The file extension for the images (for example, '.jpg'). Defaults to '.jpg'.
        step (float): How many seconds to wait between saving images. Defaults to 1.

    Returns:
        tuple: A tuple containing:
            - bool: True if the video was sliced successfully, False otherwise.
            - int: The total number of images saved.
    """
    cap = cv2.VideoCapture(str(source_file))

    if not cap.isOpened():
        return self.sliced, 0

    fps = cap.get(cv2.CAP_PROP_FPS)
    step_frames = int(fps * step)
    img_counter = 0
    frame_id = 0

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

        if not ret:
            break

        if frame_id % step_frames == 0:
            new_filename = f"{source_file.stem}_{img_counter}{suffix}"
            file_path = target_dir / new_filename
            cv2.imwrite(str(file_path), frame)
            img_counter += 1

        frame_id += 1

    cap.release()
    self.__sliced = True
    return self.sliced, img_counter