moviepy.video.VideoClip.VideoClip#

class moviepy.video.VideoClip.VideoClip(frame_function=None, is_mask=False, duration=None, has_constant_size=True)[source]#

Base class for video clips.

See VideoFileClip, ImageClip etc. for more user-friendly classes.

Parameters:
  • is_maskTrue if the clip is going to be used as a mask.

  • duration – Duration of the clip in seconds. If None we got a clip of infinite duration

  • has_constant_size – Define if clip size is constant or if it may vary with time. Default to True

size#

The size of the clip, (width,height), in pixels.

w, h

The width and height of the clip, in pixels.

is_mask#

Boolean set to True if the clip is a mask.

frame_function#

A function t-> frame at time t where frame is a w*h*3 RGB array.

mask(default None)#
VideoClip mask attached to this clip. If mask is None,

The video clip is fully opaque.

audio(default None)#

An AudioClip instance containing the audio of the video clip.

pos#

A function t->(x,y) where x,y is the position of the clip when it is composed with other clips. See VideoClip.set_pos for more details

relative_pos#

See variable pos.

layer#

Indicates which clip is rendered on top when two clips overlap in a CompositeVideoClip. The highest number is rendered on top. Default is 0.

property aspect_ratio#

Returns the aspect ratio of the video.

compose_mask(background_mask: ndarray, t: float) ndarray[source]#

Returns the result of the clip’s mask at time t composited on the given background_mask, the position of the clip being given by the clip’s pos attribute. Meant for compositing.

(warning: only use this function to blit two masks together, never images)

Parameters:
  • background_mask – The underlying mask onto which the clip mask will be composed.

  • t – The time position in the clip at which to extract the mask.

compose_on(background: Image, t) Image[source]#

Returns the result of the clip’s frame at time t on top on the given picture, the position of the clip being given by the clip’s pos attribute. Meant for compositing.

If the clip/backgrounds have transparency the transparency will be accounted for.

The return is a Pillow Image

Parameters:
  • (Image) (backrgound) – The background image to apply current clip on top of if the background image is transparent it must be given as a RGBA image

  • t – The time of clip to apply on top of clip

  • Return

copy()#

Mixed copy of the clip.

Returns a shallow copy of the clip whose mask and audio will be shallow copies of the clip’s mask and audio if they exist.

This method is intensively used to produce new clips every time there is an outplace transformation of the clip (clip.resize, clip.subclipped, etc.)

Acts like a deepcopy except for the fact that readers and other possible unpickleables objects are not copied.

cropped(x1: int = None, y1: int = None, x2: int = None, y2: int = None, width: int = None, height: int = None, x_center: int = None, y_center: int = None)[source]#

Returns a new clip in which just a rectangular subregion of the original clip is conserved. x1,y1 indicates the top left corner and x2,y2 is the lower right corner of the cropped region. All coordinates are in pixels. Float numbers are accepted. For info on the parameters, please see vfx.Crop

display_in_notebook(filetype=None, maxduration=60, t=None, fps=None, rd_kwargs=None, center=True, **html_kwargs)#

Displays clip content in an Jupyter Notebook.

Remarks: If your browser doesn’t support HTML5, this should warn you. If nothing is displayed, maybe your file or filename is wrong. Important: The media will be physically embedded in the notebook.

Parameters:
  • clip (moviepy.Clip.Clip) – Either the name of a file, or a clip to preview. The clip will actually be written to a file and embedded as if a filename was provided.

  • filetype (str, optional) – One of "video", "image" or "audio". If None is given, it is determined based on the extension of filename, but this can bug.

  • maxduration (float, optional) – An error will be raised if the clip’s duration is more than the indicated value (in seconds), to avoid spoiling the browser’s cache and the RAM.

  • t (float, optional) – If not None, only the frame at time t will be displayed in the notebook, instead of a video of the clip.

  • fps (int, optional) – Enables to specify an fps, as required for clips whose fps is unknown.

  • rd_kwargs (dict, optional) – Keyword arguments for the rendering, like dict(fps=15, bitrate="50k"). Allow you to give some options to the render process. You can, for example, disable the logger bar passing dict(logger=None).

  • center (bool, optional) – If true (default), the content will be wrapped in a <div align=middle> HTML container, so the content will be displayed at the center.

  • kwargs – Allow you to give some options, like width=260, etc. When editing looping gifs, a good choice is loop=1, autoplay=1.

Examples

from moviepy import *
# later ...
clip.display_in_notebook(width=360)
clip.audio.display_in_notebook()

clip.write_gif("test.gif")
display_in_notebook('test.gif')

clip.save_frame("first_frame.jpeg")
display_in_notebook("first_frame.jpeg")
fill_array(pre_array, shape=(0, 0))[source]#

Fills an array to match the specified shape.

If the pre_array is smaller than the desired shape, the missing rows or columns are added with ones to the bottom or right, respectively, until the shape matches. If the pre_array is larger than the desired shape, the excess rows or columns are cropped from the bottom or right, respectively, until the shape matches.

The resulting array with the filled shape is returned.

Parameters:
  • (numpy.ndarray) (pre_array) – The original array to be filled.

  • (tuple) (shape) – The desired shape of the resulting array.

property h#

Returns the height of the video.

image_transform(image_func, apply_to=None)[source]#

Modifies the images of a clip by replacing the frame get_frame(t) by another frame, image_func(get_frame(t)).

property n_frames#

Returns the number of frames of the video.

preview(fps=15, audio=True, audio_fps=22050, audio_buffersize=3000, audio_nbytes=2)[source]#

Displays the clip in a window, at the given frames per second.

It will avoid that the clip be played faster than normal, but it cannot avoid the clip to be played slower than normal if the computations are complex. In this case, try reducing the fps.

Parameters:
  • fps (int, optional) –

  • 15. (Number of frames per seconds in the displayed video. Default to) –

  • audio (bool, optional) –

  • during (True (default) if you want the clip's audio be played) –

  • preview. (the) –

  • audio_fps (int, optional) –

  • sound. (The number of bytes used generating the audio) –

  • audio_buffersize (int, optional) –

  • sound.

  • audio_nbytes (int, optional) –

  • sound.

Examples

from moviepy import *
clip = VideoFileClip("media/chaplin.mp4")
clip.preview(fps=10, audio=False)
resized(new_size=None, height=None, width=None, apply_to_mask=True)[source]#

Returns a video clip that is a resized version of the clip. For info on the parameters, please see vfx.Resize

rotated(angle: float, unit: str = 'deg', resample: str = 'bicubic', expand: bool = False, center: tuple = None, translate: tuple = None, bg_color: tuple = None)[source]#

Rotates the specified clip by angle degrees (or radians) anticlockwise If the angle is not a multiple of 90 (degrees) or center, translate, and bg_color are not None. For info on the parameters, please see vfx.Rotate

save_frame(filename, t=0, with_mask=True)[source]#

Save a clip’s frame to an image file.

Saves the frame of clip corresponding to time t in filename. t can be expressed in seconds (15.35), in (min, sec), in (hour, min, sec), or as a string: ‘01:03:05.35’.

Parameters:
  • filename (str) – Name of the file in which the frame will be stored.

  • t (float or tuple or str, optional) – Moment of the frame to be saved. As default, the first frame will be saved.

  • with_mask (bool, optional) – If is True the mask is saved in the alpha layer of the picture (only works with PNGs).

show(t=0, with_mask=True)[source]#

Splashes the frame of clip corresponding to time t.

Parameters:
  • t (float or tuple or str, optional) –

  • display. (Time in seconds of the frame to) –

  • with_mask (bool, optional) –

  • without (False if the clip has a mask but you want to see the clip) –

  • mask. (the) –

Examples

from moviepy import *

clip = VideoFileClip("media/chaplin.mp4")
clip.show(t=4)
to_ImageClip(t=0, with_mask=True, duration=None)[source]#

Returns an ImageClip made out of the clip’s frame at time t, which can be expressed in seconds (15.35), in (min, sec), in (hour, min, sec), or as a string: ‘01:03:05.35’.

to_RGB()[source]#

Return a non-mask video clip made from the mask video clip.

to_mask(canal=0)[source]#

Return a mask a video clip made from the clip.

property w#

Returns the width of the video.

with_audio(audioclip)[source]#

Attach an AudioClip to the VideoClip.

Returns a copy of the VideoClip instance, with the audio attribute set to audio, which must be an AudioClip instance.

with_background_color(size=None, color=(0, 0, 0), pos=None, opacity=None)[source]#

Place the clip on a colored background.

Returns a clip made of the current clip overlaid on a color clip of a possibly bigger size. Can serve to flatten transparent clips.

Parameters:
  • size – Size (width, height) in pixels of the final clip. By default it will be the size of the current clip.

  • color – Background color of the final clip ([R,G,B]).

  • pos – Position of the clip in the final clip. ‘center’ is the default

  • opacity – Parameter in 0..1 indicating the opacity of the colored background.

with_effects_on_subclip(effects: List[Effect], start_time=0, end_time=None, **kwargs)[source]#

Apply a transformation to a part of the clip.

Returns a new clip in which the function fun (clip->clip) has been applied to the subclip between times start_time and end_time (in seconds).

Examples

# The scene between times t=3s and t=6s in ``clip`` will be
# be played twice slower in ``new_clip``
new_clip = clip.with_sub_effect(MultiplySpeed(0.5), 3, 6)
with_layer_index(index)[source]#

Set the clip’s layer in compositions. Clips with a greater layer attribute will be displayed on top of others.

Note: Only has effect when the clip is used in a CompositeVideoClip.

with_mask(mask: VideoClip | str = 'auto')[source]#

Set the clip’s mask.

Returns a copy of the VideoClip with the mask attribute set to mask, which must be a greyscale (values in 0-1) VideoClip.

Parameters:

mask (Union["VideoClip", str], optional) – The mask to apply to the clip. If set to “auto”, a default mask will be generated: - If the clip has a constant size, a solid mask with a value of 1.0 will be created. - Otherwise, a dynamic solid mask will be created based on the frame size.

with_opacity(opacity)[source]#

Set the opacity/transparency level of the clip.

Returns a semi-transparent copy of the clip where the mask is multiplied by op (any float, normally between 0 and 1).

with_position(pos, relative=False)[source]#

Set the clip’s position in compositions.

Sets the position that the clip will have when included in compositions. The argument pos can be either a couple (x,y) or a function t-> (x,y). x and y mark the location of the top left corner of the clip, and can be of several types.

Examples

clip.with_position((45,150)) # x=45, y=150

# clip horizontally centered, at the top of the picture
clip.with_position(("center","top"))

# clip is at 40% of the width, 70% of the height:
clip.with_position((0.4,0.7), relative=True)

# clip's position is horizontally centered, and moving up !
clip.with_position(lambda t: ('center', 50+t))
with_updated_frame_function(frame_function: Callable[[float], ndarray])[source]#

Change the clip’s get_frame.

Returns a copy of the VideoClip instance, with the frame_function attribute set to mf.

without_audio()[source]#

Remove the clip’s audio.

Return a copy of the clip with audio set to None.

without_mask()[source]#

Remove the clip’s mask.

write_gif(filename, fps=None, loop=0, logger='bar')[source]#

Write the VideoClip to a GIF file.

Converts a VideoClip into an animated GIF using imageio

Parameters:
  • filename – Name of the resulting gif file, as a string or a path-like object.

  • fps – Number of frames per second (see note below). If it isn’t provided, then the function will look for the clip’s fps attribute (VideoFileClip, for instance, have one).

  • loop (int, optional) – Repeat the clip using loop iterations in the resulting GIF.

  • progress_bar – If True, displays a progress bar

Notes

The gif will be playing the clip in real time (you can only change the frame rate). If you want the gif to be played slower than the clip you will use

# slow down clip 50% and make it a gif
myClip.multiply_speed(0.5).to_gif('myClip.gif')
write_images_sequence(name_format, fps=None, with_mask=True, logger='bar')[source]#

Writes the videoclip to a sequence of image files.

Parameters:
  • name_format – A filename specifying the numerotation format and extension of the pictures. For instance “frame%03d.png” for filenames indexed with 3 digits and PNG format. Also possible: “some_folder/frame%04d.jpeg”, etc.

  • fps – Number of frames per second to consider when writing the clip. If not specified, the clip’s fps attribute will be used if it has one.

  • with_mask – will save the clip’s mask (if any) as an alpha canal (PNGs only).

  • logger – Either "bar" for progress bar or None or any Proglog logger.

Returns:

A list of all the files generated.

Return type:

names_list

Notes

The resulting image sequence can be read using e.g. the class ImageSequenceClip.

write_videofile(filename, fps=None, codec=None, bitrate=None, audio=True, audio_fps=44100, preset='medium', audio_nbytes=4, audio_codec=None, audio_bitrate=None, audio_bufsize=2000, temp_audiofile=None, temp_audiofile_path='', remove_temp=True, write_logfile=False, threads=None, ffmpeg_params=None, logger='bar', pixel_format=None)[source]#

Write the clip to a videofile.

Parameters:
  • filename – Name of the video file to write in, as a string or a path-like object. The extension must correspond to the “codec” used (see below), or simply be ‘.avi’ (which will work with any codec).

  • fps – Number of frames per second in the resulting video file. If None is provided, and the clip has an fps attribute, this fps will be used.

  • codec

    Codec to use for image encoding. Can be any codec supported by ffmpeg. If the filename is has extension ‘.mp4’, ‘.ogv’, ‘.webm’, the codec will be set accordingly, but you can still set it if you don’t like the default. For other extensions, the output filename must be set accordingly.

    Some examples of codecs are:

    • 'libx264' (default codec for file extension .mp4) makes well-compressed videos (quality tunable using ‘bitrate’).

    • 'mpeg4' (other codec for extension .mp4) can be an alternative to 'libx264', and produces higher quality videos by default.

    • 'rawvideo' (use file extension .avi) will produce a video of perfect quality, of possibly very huge size.

    • png (use file extension .avi) will produce a video of perfect quality, of smaller size than with rawvideo.

    • 'libvorbis' (use file extension .ogv) is a nice video format, which is completely free/ open source. However not everyone has the codecs installed by default on their machine.

    • 'libvpx' (use file extension .webm) is tiny a video format well indicated for web videos (with HTML5). Open source.

  • audio – Either True, False, or a file name. If True and the clip has an audio clip attached, this audio clip will be incorporated as a soundtrack in the movie. If audio is the name of an audio file, this audio file will be incorporated as a soundtrack in the movie.

  • audio_fps – frame rate to use when generating the sound.

  • temp_audiofile – the name of the temporary audiofile, as a string or path-like object, to be created and then used to write the complete video, if any.

  • temp_audiofile_path – the location that the temporary audiofile is placed, as a string or path-like object. Defaults to the current working directory.

  • audio_codec – Which audio codec should be used. Examples are ‘libmp3lame’ for ‘.mp3’, ‘libvorbis’ for ‘ogg’, ‘libfdk_aac’:’m4a’, ‘pcm_s16le’ for 16-bit wav and ‘pcm_s32le’ for 32-bit wav. Default is ‘libmp3lame’, unless the video extension is ‘ogv’ or ‘webm’, at which case the default is ‘libvorbis’.

  • audio_bitrate – Audio bitrate, given as a string like ‘50k’, ‘500k’, ‘3000k’. Will determine the size/quality of audio in the output file. Note that it mainly an indicative goal, the bitrate won’t necessarily be the this in the final file.

  • preset – Sets the time that FFMPEG will spend optimizing the compression. Choices are: ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow, placebo. Note that this does not impact the quality of the video, only the size of the video file. So choose ultrafast when you are in a hurry and file size does not matter.

  • threads – Number of threads to use for ffmpeg. Can speed up the writing of the video on multicore computers.

  • ffmpeg_params – Any additional ffmpeg parameters you would like to pass, as a list of terms, like [‘-option1’, ‘value1’, ‘-option2’, ‘value2’].

  • write_logfile – If true, will write log files for the audio and the video. These will be files ending with ‘.log’ with the name of the output file in them.

  • logger – Either "bar" for progress bar or None or any Proglog logger.

  • pixel_format – Pixel format for the output video file.

Examples

from moviepy import VideoFileClip
clip = VideoFileClip("myvideo.mp4").subclipped(100,120)
clip.write_videofile("my_new_video.mp4")
clip.close()