Search code examples
python-3.xpixelmoviepy

How to set the color of individual pixels with moviepy


I want to create a custom video where each pixel represents the result of a mathematical function. I've tried clip.get_frame(f)[y][x] = (r, g, b) but that doesn't work, the video stays unmodified.

How could I go about doing this? Also, are there better plugins for doing this kind of thing?


Solution

  • You should use the VideoClip class with a make_frame function (a function t -> frame at time t where frame is a w*h*3 RGB array representing the pixels). [Docs]

    Here's an example make_frame function using numpy; it generates a random array of pixels for each t.

    from moviepy.editor import *
    import numpy as np
    
    def make_frame(t):
        w, h = 320, 180  # Width an height.
        return np.random.random_integers(0, 255, (h,w,3))
    
    clip = VideoClip(make_frame, duration=2)
    clip.write_gif('random.gif', fps=15)
    

    As a result, we get:

    Random Pixels Animation