Search code examples
pythonmoviepy

Move across image using Moviepy


Using moviepy, I'm trying to make a video where it moves across an image.

Why isn't this working?:

image = ImageClip('image.png', duration=5)
image.set_position(lambda t: ('center', 50+t) )
image.fps = 30
image.write_videofile('video.mp4')

The outputted video is just a 5s video of the image (no movement)


Solution

  • There are two issues here.

    Issue #1: ImageClip is not part of a composition

    The documentation for ImageClip.set_position() says this:

    Set the clip’s position in compositions.

    Sets the position that the clip will have when included in compositions.

    By "composition," it means a CompositeVideoClip. When an ImageClip is not part of a composition, set_position does nothing.

    Issue #2: Return value of set_position is not used

    set_position() has a somewhat confusing name. It does not actually set the position. It returns a copy of the Clip with the position set.

    So this doesn't do anything:

    image.set_position(lambda t: ('center', 50+t) )
    

    instead, you need to do this:

    image = image.set_position(lambda t: ('center', 50+t) )
    

    Full corrected code

    from moviepy.editor import ImageClip, CompositeVideoClip
    image = ImageClip('image.png', duration=5)
    image = image.set_position(lambda t: ('center', t * 10 + 50))
    image.fps = 30
    composite = CompositeVideoClip([image], size=image.size)
    composite.write_videofile('video.mp4')
    

    (Note: I also made the image movement larger so it would be more noticeable.)

    (Thanks to the author of this issue for providing example code so I could figure out the problem.)