1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] Unable to display video created through cv2 in colab

Discussão em 'Python' iniciado por Stack, Outubro 1, 2024 às 06:23.

  1. Stack

    Stack Membro Participativo

    I am trying to create a video from an image, But the video is not getting displayed in google colab. But the same video, when I download and play it in my local machine, It is working fine. I have provided a code to reproduce the above,

    import numpy as np
    import cv2
    from IPython.display import Video, display

    def create_random_image(width=256, height=256):
    return np.random.randint(0, 256, (height, width, 3), dtype=np.uint8)

    def modify_image_randomly(image):
    # Select random points and change pixel values
    for _ in range(100): # Modify 100 random pixels
    x = np.random.randint(0, image.shape[1])
    y = np.random.randint(0, image.shape[0])
    image[y, x] = [np.random.randint(0, 255) for _ in range(3)]
    return image

    initial_image = create_random_image()

    frame_width = initial_image.shape[1]
    frame_height = initial_image.shape[0]
    fps = 10
    num_frames = 50 # Number of frames in the video

    # Create a VideoWriter object to save as MP4
    out = cv2.VideoWriter('random_video.mp4', cv2.VideoWriter_fourcc(*'mp4v'), fps, (frame_width, frame_height))

    # Generate frames and write to video
    for i in range(num_frames):
    modified_image = modify_image_randomly(initial_image.copy()) # Modify a copy of the initial image
    out.write(modified_image)

    # Release the video writer
    out.release()

    # Display the video in Colab
    display(Video("random_video.mp4", embed=True))

    Continue reading...

Compartilhe esta Página