GithubHelp home page GithubHelp logo

zulko / moviepy Goto Github PK

View Code? Open in Web Editor NEW
11.8K 253.0 1.5K 40.64 MB

Video editing with Python

Home Page: https://zulko.github.io/moviepy/

License: MIT License

Python 99.89% Dockerfile 0.11%
python video gif animation video-editing video-processing hacktoberfest

moviepy's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

moviepy's Issues

Save to Amazon S3

Hi,

I want to save my final video to Amazon S3 (or other network storage), but with current to_videofile I cannot.

Code from example:

# write the result to a file in any format
final_clip.to_videofile("myHolidays_edited.avi",fps=25, codec='mpeg4')

Can you use buffer instead of filename? Or other suggestions how can I do it.

`error: string:` When trying to import from moviepy

Refer to this line of code:

print "error: string: %s, stderr: %s"%(s,serr)

I successfully installed moviepy and every dependency, for example: import moviepy and from moviepy.editor import * works, along with import pygame, etc. I also did sudo apt-get install libav-tools for the ffmpeg library.

However, the line clip = VideoFileClip("some_video.mp4").subclip(0, 60) causes my terminal to blank into a new, unusual terminal console with one line of error: error: string:

I am using Ubunu 12.04.3 Server.

Specifying pix_fmt on FFMPEG call

The newer versions of FFMPEG default to a pixel format which is incompatible with Apple's Quicktime player. It would be convenient to offer the option to specify the pixel format, i.e. to add the flag

-pix_fmt yuv420p

to the ffmpeg call in ffmpeg_tools.py:ffmpeg_movie_from_frames.

There is a note that ffmpeg_movie_from_frames is almost deprecated. I can add the option, and propagate the keyword argument up to to_videofile and issue a pull request, but is this the most appropriate place to add the change?

FFMPEG binary not found.

I installed numpy using sudo. After i run the example it's throws below error.

root@ri-desktop:~/studio/master/moviepy-master/moviepy-master/examples# python example_with_sound.py
Traceback (most recent call last):
File "example_with_sound.py", line 8, in
from moviepy.editor import *
File "/usr/local/lib/python2.7/dist-packages/moviepy-0.2.1.8.09-py2.7.egg/moviepy/editor.py", line 22, in
from .video.io.VideoFileClip import VideoFileClip
File "/usr/local/lib/python2.7/dist-packages/moviepy-0.2.1.8.09-py2.7.egg/moviepy/video/io/VideoFileClip.py", line 3, in
from moviepy.video.VideoClip import VideoClip
File "/usr/local/lib/python2.7/dist-packages/moviepy-0.2.1.8.09-py2.7.egg/moviepy/video/VideoClip.py", line 21, in
from .io.ffmpeg_writer import ffmpeg_write_image, ffmpeg_write_video
File "/usr/local/lib/python2.7/dist-packages/moviepy-0.2.1.8.09-py2.7.egg/moviepy/video/io/ffmpeg_writer.py", line 19, in
from moviepy.conf import FFMPEG_BINARY
File "/usr/local/lib/python2.7/dist-packages/moviepy-0.2.1.8.09-py2.7.egg/moviepy/conf.py", line 61, in
raise IOError("FFMPEG binary not found. Try installing MoviePy"
IOError: FFMPEG binary not found. Try installing MoviePy manually and specify the path to the binary in the file conf.py'

Unclosed processes.

When I'm trying to get video duration

video_clip = VideoFileClip(video_file_path)
print video_clip.duration

I see 2 processes, that are never closed
_ ffmpeg -i /tmp/9ea28576d6154d568b755f4cd9718c77.mp4 -f image2pipe -pix_fmt rgb24 -vcodec rawvideo -
_ ffmpeg -i /tmp/9ea28576d6154d568b755f4cd9718c77.mp4 -vn -f s16le -acodec pcm_s16le -ar 44100 -ac 2 -

Can you advise?

something went wrong with the audio writing, Exit code 1

My video file http://d.pr/v/dAcW

Open and save:

>>> from moviepy.editor import *
>>> video_clip = VideoFileClip('7e989f661a8c4821bb542f142a91a699')
>>> video_clip.to_videofile('x.mp4')
Making file x.mp4 ...
Writing audio/video in parrallel.
Rendering video TEMP_MPY_to_videofile.mp4
Rendering audio TEMP_MPY_to_videofile_SOUND.ogg
========audio done !==========video done !
Now merging video and audio...

Running:
>>> ffmpeg -y -i TEMP_MPY_to_videofile_SOUND.ogg -i TEMP_MPY_to_videofile.mp4 -vcodec copy -acodec copy x.mp4
... ffmpeg command successful.

Your video is ready ! Fingers crossed for the Oscars !>>>

Open and create a subclip:

>>> clip = video_clip.subclip(0, video_clip.duration)
>>> clip.to_videofile('x.mp4')
Making file x.mp4 ...
Writing audio/video in parrallel.
Rendering video TEMP_MPY_to_videofile.mp4
Rendering audio TEMP_MPY_to_videofile_SOUND.ogg
======Error: wrong indices in video buffer. Maybe buffer too small.
Process Process-2:
Traceback (most recent call last):
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap
    self.run()
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/process.py", line 114, in run
    self._target(*self._args, **self._kwargs)
  File "<string>", line 2, in to_audiofile
  File "/Users/michael/Projects/lib/python2.7/site-packages/moviepy/decorators.py", line 43, in requires_duration
    return f(clip, *a, **k)
  File "/Users/michael/Projects/lib/python2.7/site-packages/moviepy/audio/AudioClip.py", line 81, in to_audiofile
    codec, bitrate, verbose)
  File "<string>", line 2, in ffmpeg_audiowrite
  File "/Users/michael/Projects/lib/python2.7/site-packages/moviepy/decorators.py", line 43, in requires_duration
    return f(clip, *a, **k)
  File "/Users/michael/Projects/lib/python2.7/site-packages/moviepy/audio/io/ffmpeg_audiowriter.py", line 88, in ffmpeg_audiowrite
    sndarray = clip.to_soundarray(tt,nbytes)
  File "<string>", line 2, in to_soundarray
  File "/Users/michael/Projects/lib/python2.7/site-packages/moviepy/decorators.py", line 43, in requires_duration
    return f(clip, *a, **k)
  File "/Users/michael/Projects/lib/python2.7/site-packages/moviepy/audio/AudioClip.py", line 65, in to_soundarray
    snd_array = self.get_frame(tt)
  File "/Users/michael/Projects/lib/python2.7/site-packages/moviepy/Clip.py", line 75, in <lambda>
    newclip = self.set_get_frame(lambda t: fl(gf, t))
  File "/Users/michael/Projects/lib/python2.7/site-packages/moviepy/Clip.py", line 115, in <lambda>
    return self.fl(lambda gf, t: gf(t_func(t)), applyto,
  File "/Users/michael/Projects/lib/python2.7/site-packages/moviepy/audio/io/AudioFileClip.py", line 71, in gf
    result[in_time] = self.buffer[inds - self._fstart_buffer]
IndexError: index 100000 is out of bounds for axis 0 with size 100000
==========video done !WARNING: something went wrong with the audio writing, Exit code 1

Now merging video and audio...

Running:
>>> ffmpeg -y -i TEMP_MPY_to_videofile_SOUND.ogg -i TEMP_MPY_to_videofile.mp4 -vcodec copy -acodec copy x.mp4
... ffmpeg command successful.

Your video is ready ! Fingers crossed for the Oscars !>>>

And the new video file is crashed.

Error: wrong indices in video buffer. Maybe buffer too small.

The following code:

wordSlide = ColorClip((1280,720), (228,232,111))
wordText = TextClip(wordStr, font="Arial-Regular", color="YellowGreen", fontsize=90)
wordAudio = AudioFileClip(path + "word.aif")
wordClip = CompositeVideoClip([wordSlide.set_audio(wordAudio),
    wordText.set_pos('center')]).set_duration(wordAudio.duration)

Produces:

Error: wrong indices in video buffer. Maybe buffer too small.
Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/local/Cellar/python/2.7.6_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 810, in __bootstrap_inner
    self.run()
  File "/usr/local/Cellar/python/2.7.6_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 763, in run
    self.__target(*self.__args, **self.__kwargs)
  File "<string>", line 2, in preview
  File "/usr/local/lib/python2.7/site-packages/moviepy/decorators.py", line 60, in requires_duration
    return f(clip, *a, **k)
  File "/usr/local/lib/python2.7/site-packages/moviepy/audio/io/preview.py", line 59, in preview
    sndarray = clip.to_soundarray(tt,nbytes)
  File "<string>", line 2, in to_soundarray
  File "/usr/local/lib/python2.7/site-packages/moviepy/decorators.py", line 60, in requires_duration
    return f(clip, *a, **k)
  File "/usr/local/lib/python2.7/site-packages/moviepy/audio/AudioClip.py", line 83, in to_soundarray
    snd_array = self.get_frame(tt)
  File "/usr/local/lib/python2.7/site-packages/moviepy/audio/AudioClip.py", line 189, in get_frame
    if (part is not False) ]
  File "/usr/local/lib/python2.7/site-packages/moviepy/audio/io/AudioFileClip.py", line 69, in <lambda>
    self.get_frame =  lambda t: self.reader.get_frame(t)
  File "/usr/local/lib/python2.7/site-packages/moviepy/audio/io/readers.py", line 173, in get_frame
    raise error
IndexError: index 45785 is out of bounds for axis 0 with size 45784

A little hack that kinda makes it go away is to do:

wordSlide = ColorClip((1280,720), (228,232,111))
wordText = TextClip(wordStr, font="Arial-Regular", color="YellowGreen", fontsize=90)
wordAudio = AudioFileClip(path + "word.aif")
wordClip = CompositeVideoClip([wordSlide.set_audio(wordAudio),
    wordText.set_pos('center')]).set_duration(wordAudio.duration - 0.01)

Although this doesn't fix anything. It just happens to work in this case, but not for other clips. Why is it crashing?

The wordAudio.duration is 1.04s in this case. On some audio files it crashes, on some it doesn't. Is this the accuracy problem with generating number of frames based on audio length?

set all filehandles to make moviepy work in cx_freeze win32gui

If moviepy is bundled in a cx_freeze win32gui app, all three filehandles (stdout, stderr and stdin) have to be set. If only one of them is not set (default=None) an "invalid filehandle" exception is thrown and moviepy can not be used.

This is already done e.g. in ffmpeg_writer.py by setting stdout to DEVNULL but unfortunately not at all Popen calls.

Is it possible to set these filehandles everywhere?

Thanks

P.S.: Is it ok to submit these issues here or shoud a fork be generated with a pull request? I have not yet worked with pull requests...

'ValueError: I/O operation on closed file'

I am seeing 'ValueError: I/O operation on closed file' in the latest build of the master branch. I had to go back to using this commit to get things working again: 954516a

I get the i/o error by running:
VideoFileClip(file_path).subclip(start, end).to_gif(gif_temp_path, fps=fps, fuzz=2)

This is the error output:
File "/Users/alexandervodovoz/.virtualenvs/hampton/lib/python2.7/site-packages/moviepy-0.2.1.7.09-py2.7.egg/moviepy/video/VideoClip.py", line 116, in save_frame
ffmpeg_write_image(filename, im)
File "/Users/alexandervodovoz/.virtualenvs/hampton/lib/python2.7/site-packages/moviepy-0.2.1.7.09-py2.7.egg/moviepy/video/io/ffmpeg_writer.py", line 122, in ffmpeg_write_image
proc.communicate() # proc.wait()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 806, in communicate
return self._communicate(input)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1377, in _communicate
self.stdin.flush()
ValueError: I/O operation on closed file

Change speed of clip based on a curve?

Does anyone have any ideas as to how to change the speed of a clip gradually over a bezier curve?

Is there any demand for this feature?
Am I the only one who wants this?

Python 3.3.3 - invalid syntax error

I'm trying to run moviepy with the Python 3.3.3 interpreter and it fails.

I'm sorry before-hand if it's a n00b error (I'm still brand new to Python) but I get the following error when running my code.

Error:

Traceback (most recent call last):
  File "C:/Users/Maxime/PycharmProjects/LearningPython/LearningClasses.py", line 2, in <module>
    from moviepy.editor import *
  File "C:\Python33\lib\site-packages\moviepy\editor.py", line 11, in <module>
    from moviepy.video.io.VideoFileClip import VideoFileClip
  File "C:\Python33\lib\site-packages\moviepy\video\io\VideoFileClip.py", line 63
    print "No audio found in %s"%filename
                               ^
SyntaxError: invalid syntax

My Code:

from moviepy.editor import *

VideoFileClip("C:/Users/Maxime/Downloads/sample_mpeg4.mp4").to_gif("test.gif")

on_color fails with TypeError when given a col_opacity parameter

Here's a simple python script that shows the issue:

from moviepy.editor import *
txt= TextClip('Hello, world!')
this_works= txt.on_color()
this_fails= txt.on_color(col_opacity= 0.5)

That last statement throws the following error:

Traceback (most recent call last):
  File "./tmp.py", line 8, in <module>
    this_fails= txt.on_color(col_opacity= 0.5)
  File "/Users/chunder/py-projects/moviepy/lib/python2.6/site-packages/moviepy-0.2.1.6.93-py2.6.egg/moviepy/video/VideoClip.py", line 497, in on_color
    colorclip = colorclip.set_opacity(col_opacity)
  File "/Users/chunder/py-projects/moviepy/lib/python2.6/site-packages/moviepy-0.2.1.6.93-py2.6.egg/moviepy/video/VideoClip.py", line 533, in set_opacity
    newclip = newclip.add_mask()
  File "/Users/chunder/py-projects/moviepy/lib/python2.6/site-packages/moviepy-0.2.1.6.93-py2.6.egg/moviepy/video/VideoClip.py", line 472, in add_mask
    return self.set_mask( mask.set_duration(self.duration))
  File "<string>", line 2, in set_duration
  File "/Users/chunder/py-projects/moviepy/lib/python2.6/site-packages/moviepy-0.2.1.6.93-py2.6.egg/moviepy/decorators.py", line 12, in apply_to_mask
    newclip = f(clip, *a, **k)
  File "<string>", line 2, in set_duration
  File "/Users/chunder/py-projects/moviepy/lib/python2.6/site-packages/moviepy-0.2.1.6.93-py2.6.egg/moviepy/decorators.py", line 22, in apply_to_audio
    newclip = f(clip, *a, **k)
  File "<string>", line 2, in set_duration
  File "/Users/chunder/py-projects/moviepy/lib/python2.6/site-packages/moviepy-0.2.1.6.93-py2.6.egg/moviepy/decorators.py", line 71, in time_can_be_tuple
    return f(clip, *a, **k)
  File "/Users/chunder/py-projects/moviepy/lib/python2.6/site-packages/moviepy-0.2.1.6.93-py2.6.egg/moviepy/Clip.py", line 195, in set_duration
    newclip.end = newclip.start + t
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'

Here's my environment:

$ pip freeze
PIL==1.1.7
decorator==3.4.0
moviepy==0.2.1.6.93
numpy==1.8.0
wsgiref==0.1.2

Problem with writing audio

Hey there. I'm experiencing a problem when writing audio. If I call .to_videofile with audio=False, then there is no problem. My videopy version number is 0.2.1.8.02.

The video I'm working with is here:
https://www.dropbox.com/s/iepmbyieferjbay/test.MP4

The code is here:

clip = mp.VideoFileClip('../snowsports/test.MP4').subclip(220,224)
clip.to_videofile("test-short.MP4")

There error message is:

MoviePy: building video file test-short.MP4
----------------------------------------
Writing audio in test-shortTEMP_MPY_to_videofile_SOUND.ogg
Done writing Audio in test-shortTEMP_MPY_to_videofile_SOUND.ogg !

Writing video into test-shortTEMP_MPY_to_videofile.MP4
Done writing video in test-shortTEMP_MPY_to_videofile.MP4 !

Now merging video and audio:

MoviePy Running:
>>> ffmpeg -y -i test-shortTEMP_MPY_to_videofile_SOUND.ogg -i test-shortTEMP_MPY_to_videofile.MP4 -vcodec copy -acodec copy test-short.MP4
MoviePy: WARNING !
   The following command returned an error:
ffmpeg version 2.2.3 Copyright (c) 2000-2014 the FFmpeg developers
  built on Jun  3 2014 06:47:04 with Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn)
  configuration: --prefix=/usr/local/Cellar/ffmpeg/2.2.3 --enable-shared --enable-pthreads --enable-gpl --enable-version3 --enable-nonfree --enable-hardcoded-tables --enable-avresample --enable-vda --cc=clang --host-cflags= --host-ldflags= --enable-libx264 --enable-libfaac --enable-libmp3lame --enable-libxvid
  libavutil      52. 66.100 / 52. 66.100
  libavcodec     55. 52.102 / 55. 52.102
  libavformat    55. 33.100 / 55. 33.100
  libavdevice    55. 10.100 / 55. 10.100
  libavfilter     4.  2.100 /  4.  2.100
  libavresample   1.  2.  0 /  1.  2.  0
  libswscale      2.  5.102 /  2.  5.102
  libswresample   0. 18.100 /  0. 18.100
  libpostproc    52.  3.100 / 52.  3.100
test-shortTEMP_MPY_to_videofile_SOUND.ogg: No such file or directory
Conversion failed!
---------------------------------------------------------------------------
IOError                                   Traceback (most recent call last)
<ipython-input-13-b6f4d3578283> in <module>()
      1 clip = mp.VideoFileClip('../snowsports/test.MP4').subclip(220,224)
----> 2 clip.to_videofile("test-short.MP4")

/usr/local/lib/python2.7/site-packages/moviepy/video/VideoClip.pyc in to_videofile(self, filename, fps, codec, bitrate, audio, audio_fps, audio_nbytes, audio_codec, audio_bitrate, audio_bufsize, temp_audiofile, rewrite_audio, remove_temp, write_logfile, para, verbose)
    286             verbose_print("\n\nNow merging video and audio:\n")
    287             ffmpeg_merge_video_audio(videofile,temp_audiofile,
--> 288                                   filename, ffmpeg_output=True)
    289 
    290             if remove_temp:

/usr/local/lib/python2.7/site-packages/moviepy/video/io/ffmpeg_tools.pyc in ffmpeg_merge_video_audio(video, audio, output, vcodec, acodec, ffmpeg_output, verbose)
     49              "-vcodec", vcodec, "-acodec", acodec, output]
     50 
---> 51     subprocess_call(cmd, verbose = verbose)
     52 
     53 

/usr/local/lib/python2.7/site-packages/moviepy/tools.pyc in subprocess_call(cmd, verbose, errorprint)
     33                     "   The following command returned an error:\n")
     34             sys_write_flush( err.decode('utf8'))
---> 35         raise IOError
     36     else:
     37         verboseprint( "\n... command successful.\n")

IOError: 

I've also tried explicitly specifying the codec as 'mpeg4'. I'm not sure if that makes any difference, but the result is the same.

ImageClip is broken

dogeImage = ImageClip("../common/doge_small.png")
Traceback (most recent call last):
  File "viddler.py", line 81, in <module>
    dogeImage = ImageClip("../common/doge_small.png")
  File "/usr/lib/python2.7/site-packages/moviepy/video/VideoClip.py", line 853, in __init__
    img = ffmpeg_read_image(img,with_mask=transparent)
  File "/usr/lib/python2.7/site-packages/moviepy/video/io/ffmpeg_reader.py", line 172, in ffmpeg_read_image
    reader = FFMPEG_VideoReader(filename, pix_fmt=pix_fmt)
  File "/usr/lib/python2.7/site-packages/moviepy/video/io/ffmpeg_reader.py", line 17, in __init__
    infos = ffmpeg_parse_infos(filename, print_infos)
  File "/usr/lib/python2.7/site-packages/moviepy/video/io/ffmpeg_reader.py", line 213, in ffmpeg_parse_infos
    line = [l for l in lines if 'Duration: ' in l][0]
IndexError: list index out of range
Exception AttributeError: "FFMPEG_VideoReader instance has no attribute 'proc'" in <bound method FFMPEG_VideoReader.__del__ of <moviepy.video.io.ffmpeg_reader.FFMPEG_VideoReader instance at 0x2ad6a28>> ignored

shell returned 1

Too stupid to rotate :D

Hi all

I really love this project. It helps me with a problem i have since three years and my sister finally will have a wedding video and not only photos. But now i am facing a problem.
I try to rotate the Images which are somehow not rotated from ffmpeg. The EXIF rotation tag allows me to detect if the image is "wrong", so that is not a problem. But i don't know how to use rotation correctly. Here is my test code:

if imgData['orientation'] == 1:
    clips.append(ImageClip(imgData['path']).resize(height = HEIGHT).set_pos('center').set_start(clipStart).fadein(FADEIN).set_duration(IMGDURATION).crossfadeout(FADEOUT)) #, width = WIDTH
else:
    #please rotate the image...
    clip = ImageClip(imgData['path']).resize(width = HEIGHT).set_pos('center').set_start(clipStart).fadein(FADEIN).set_duration(IMGDURATION).crossfadeout(FADEOUT)
    clip1 = vfx.rotation(clip, -90)
    video = CompositeVideoClip([clip1], size = MOVIESIZE)
    video.to_videofile(DSTPATH + "/video.avi", fps=25, codec=CODEC)

I tried around and fiddled with it, but did not get behind how to do this correctly. Finally all these images are put into a list (clips) and rendered over another background video. This video rendering here is just for testing purposes.
The error output i get is:

  File "/usr/local/lib/python2.7/dist-packages/moviepy/video/VideoClip.py", line 325, in blit_on
    return blit(img, picture, pos, mask=mask, ismask=self.ismask)
  File "/usr/local/lib/python2.7/dist-packages/moviepy/video/tools/drawing.py", line 43, in blit
    1.0 * mask * blitted + (1.0 - mask) * blit_region)
ValueError: operands could not be broadcast together with shapes (3,717,3) (3,1080,717)

Can you give me a hint how to do this right?
Thanks and have a nice day. :)
gn8 from switzerland

gif_writers.py uses an undefined constant

Hi, my linter turned up an undefined variable found in your library when i was browsing through it

line 161/162 in gif_writers.py

        proc1 = sp.Popen(cmd1+['-r', "%.02f"%fps, filename],
                         stdin=sp.PIPE, stdout=DEVNULL)

should be

        proc1 = sp.Popen(cmd1+['-r', "%.02f"%fps, filename],
                         stdin=sp.PIPE, stdout=os.devnull)

FFMPEG Error on current Debian Wheezy x64

Hi All

I have e recurring error with/from ffmpeg on 2 devices running (current) debian wheezy. I only have 64bit systems so i was not able to try 32 bit. The installed version of moviepy is from pip, but i tried it also with a current git clone and got the same result. When i run the command myself which moviepy runs ffmpeg -i /tmp/DSC_0384.JPG -f image2pipe -pix_fmt rgba -vcodec rawvideo - it ends with "Segmentation fault" so i think it is something with ffmpeg. But i don't know how to track it down further.

My testfile (from the example page extracted) which produces the same error as my more complex project:

#!/usr/bin/python
from moviepy.editor import *
txt_clip = TextClip("My Holidays 2013",fontsize=70,color='white')

The error from moviepy:

$ python test.py 
Traceback (most recent call last):
  File "test.py", line 5, in <module>
    txt_clip = TextClip("My Holidays 2013",fontsize=70,color='white')
  File "/usr/local/lib/python2.7/dist-packages/moviepy/video/VideoClip.py", line 971, in __init__
    ImageClip.__init__(self, tempfile, transparent=transparent)
  File "/usr/local/lib/python2.7/dist-packages/moviepy/video/VideoClip.py", line 753, in __init__
    img = ffmpeg_read_image(img,with_mask=transparent)
  File "/usr/local/lib/python2.7/dist-packages/moviepy/video/io/ffmpeg_reader.py", line 192, in ffmpeg_read_image
    reader = FFMPEG_VideoReader(filename, pix_fmt=pix_fmt)
  File "/usr/local/lib/python2.7/dist-packages/moviepy/video/io/ffmpeg_reader.py", line 34, in __init__
    self.lastread = self.read_frame()
  File "/usr/local/lib/python2.7/dist-packages/moviepy/video/io/ffmpeg_reader.py", line 117, in read_frame
    assert len(s) == nbytes
AssertionError
Exception AttributeError: "FFMPEG_VideoReader instance has no attribute 'lastread'" in <bound method FFMPEG_VideoReader.__del__ of <moviepy.video.io.ffmpeg_reader.FFMPEG_VideoReader instance at 0x25fa5f0>> ignored

Ffmpeg version:

$ ffmpeg -version
ffmpeg version 0.8.10-6:0.8.10-1, Copyright (c) 2000-2013 the Libav developers
  built on Feb  5 2014 03:52:19 with gcc 4.7.2
*** THIS PROGRAM IS DEPRECATED ***
This program is only provided for compatibility and will be removed in a future release. Please use avconv instead.
ffmpeg 0.8.10-6:0.8.10-1
libavutil    51. 22. 2 / 51. 22. 2
libavcodec   53. 35. 0 / 53. 35. 0
libavformat  53. 21. 1 / 53. 21. 1
libavdevice  53.  2. 0 / 53.  2. 0
libavfilter   2. 15. 0 /  2. 15. 0
libswscale    2.  1. 0 /  2.  1. 0
libpostproc  52.  0. 0 / 52.  0. 0

Any help is much appreciated! I know the problem is not on your side. Debian would like to use avconv in the future but i realize that this is no easy task to change.

set_duration ignored on TextClip

I am using:

  • Windows 8.1 64bit
  • Python 2.7.8 32bit
  • moviepy 0.2.1.8.10
  • latest ffmpeg binary static 32bit build
  • latest imagemagick 32bit build

also installed numpy, Decorator, tqdm, scipy, PyGame and Pillow

I edited the conf.py file to match my paths to binaries - and they both work (i know this because both VideoFileClip and write_gif method works flawlessly)

Now with the actual problem, when i try to execute this code:

from moviepy.editor import TextClip

text = (TextClip("my text",
                 fontsize=16, color='white', font="Arial")
        .set_pos((0, 0))
        .set_duration(5.5))

i get IOError: MoviePy error: failed to read the duration of file:

C:\Programowanie\Python278\python.exe E:/Mega/Dev/python/PyCharm/wanted-gif/example.py
Traceback (most recent call last):
  File "E:/Mega/Dev/python/PyCharm/wanted-gif/example.py", line 4, in <module>
    fontsize=16, color='white', font="Arial")
  File "C:\Programowanie\Python278\lib\site-packages\moviepy\video\VideoClip.py", line 1259, in __init__
    ImageClip.__init__(self, tempfilename, transparent=transparent)
  File "C:\Programowanie\Python278\lib\site-packages\moviepy\video\VideoClip.py", line 1011, in __init__
    img = ffmpeg_read_image(img,with_mask=transparent)
  File "C:\Programowanie\Python278\lib\site-packages\moviepy\video\io\ffmpeg_reader.py", line 183, in ffmpeg_read_image
    reader = FFMPEG_VideoReader(filename, pix_fmt=pix_fmt)
  File "C:\Programowanie\Python278\lib\site-packages\moviepy\video\io\ffmpeg_reader.py", line 22, in __init__
    infos = ffmpeg_parse_infos(filename, print_infos)
  File "C:\Programowanie\Python278\lib\site-packages\moviepy\video\io\ffmpeg_reader.py", line 239, in ffmpeg_parse_infos
    filename, infos))
IOError: MoviePy error: failed to read the duration of file c:\users\aseeon\appdata\local\temp\tmpwpfe_8.png.
Here are the file infos returned by ffmpeg:

ffmpeg version N-66289-gb76d613 Copyright (c) 2000-2014 the FFmpeg developers
  built on Sep 15 2014 22:02:10 with gcc 4.8.3 (GCC)
  configuration: --enable-gpl --enable-version3 --disable-w32threads --enable-avisynth --enable-bzlib --enable-fontconfig --enable-frei0r --enable-gnutls --enable-iconv --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --enable-libfreetype --enable-libgme --enable-libgsm --enable-libilbc --enable-libmodplug --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libopus --enable-librtmp --enable-libschroedinger --enable-libsoxr --enable-libspeex --enable-libtheora --enable-libtwolame --enable-libvidstab --enable-libvo-aacenc --enable-libvo-amrwbenc --enable-libvorbis --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxavs --enable-libxvid --enable-decklink --enable-zlib
  libavutil      54.  7.100 / 54.  7.100
  libavcodec     56.  1.100 / 56.  1.100
  libavformat    56.  4.101 / 56.  4.101
  libavdevice    56.  0.100 / 56.  0.100
  libavfilter     5.  1.100 /  5.  1.100
  libswscale      3.  0.100 /  3.  0.100
  libswresample   1.  1.100 /  1.  1.100
  libpostproc    53.  0.100 / 53.  0.100
Input #0, png_pipe, from 'c:\users\aseeon\appdata\local\temp\tmpwpfe_8.png':
  Duration: N/A, bitrate: N/A
    Stream #0:0: Video: png, rgba, 53x18, 25 tbr, 25 tbn, 25 tbc
At least one output file must be specified

So this looks like set_duration on TextClip is ignored, and instead N/A from ffmpeg is taken and error occurs. Could you help me with this issue?

Cannot convert mov to gif

In [1]: from moviepy.editor import *

In [2]: clip = (VideoFileClip("timelapse.mov").subclip(1,37).speedx(6).fx( vfx.blackwhite, preserve_luminosity=True))

In [3]: clip.write_gif('timelapse.gif',loop=1,program='ImageMagick')

MoviePy: building GIF file timelapse.gif
----------------------------------------
Generating GIF frames.
|----------| 0/145   0% [elapsed: 00:00 left: ?, ? iters/sec]---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-3-35e583d45ded> in <module>()
----> 1 clip.write_gif('timelapse.gif',loop=1,program='ImageMagick')

/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/moviepy-0.2.1.8.05-py2.7.egg/moviepy/video/VideoClip.pyc in write_gif(self, filename, fps, program, opt, fuzz, verbose, loop, dispose)
    455             name = "%s_GIFTEMP%04d.png"%(fileName, i+1)
    456             tempfiles.append(name)
--> 457             self.save_frame(name, t, savemask=True)
    458 
    459         verbose_print(verbose, "Done generating GIF frames.\n")

/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/moviepy-0.2.1.8.05-py2.7.egg/moviepy/video/VideoClip.pyc in save_frame(self, filename, t, savemask)

/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/moviepy-0.2.1.8.05-py2.7.egg/moviepy/decorators.pyc in time_can_be_tuple(f, clip, *a, **k)
     91     a = map(fun,a)
     92     k = dict( [(m, fun(n)) for m,n in k.items()])
---> 93     return f(clip, *a, **k)

/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/moviepy-0.2.1.8.05-py2.7.egg/moviepy/video/VideoClip.pyc in save_frame(self, filename, t, savemask)
    132             mask = 255 * self.mask.get_frame(t)
    133             im = np.dstack([im, mask]).astype('uint8')
--> 134         ffmpeg_write_image(filename, im)
    135 
    136 

/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/moviepy-0.2.1.8.05-py2.7.egg/moviepy/video/io/ffmpeg_writer.pyc in ffmpeg_write_image(filename, image, logfile)
    204         err = "\n".join(["MoviePy running : %s"%cmd,
    205                           "WARNING: this command returned an error:",
--> 206                           proc.stderr.read().decode('utf8')])
    207         raise IOError(err)
    208 

ValueError: I/O operation on closed file

There is no mention of it in documentation. I will add an exception before trying to convert.

Problems with preview + missing explanation of crop + resize not working

Hey, I came here via your GIF tutorial and though I've meanwhile managed to output my first few GIFs ๐ŸŽ‰ your documentation doesn't cover a few things I'm having problems with or questions about.

  • I can't seem to preview clips - I've tried both preview and show, and always get attribute errors:
    AttributeError: VideoFileClip instance has no attribute 'preview'
    AttributeError: VideoFileClip instance has no attribute 'show'
  • I have no idea how crops work. What are x1 and x2? I thought they stood for start and stop of the crop horizontally, but that can't be it.
  • I can't get resize to work, I always get an import error for that:
    ImportError: fx resize needs OpenCV or Scipy or PIL

I'm running MoviePy with virtualenv, could that be why my OpenCV install isn't recognised? (Currently trying to find out how to install Scipy on Mavericks.)

(Btw. if you'd prefer me to split these up into separate GitHub issues, I'll happily do so.)

Problems with complex mask

I'm trying to cut out some areas with mask, shift them in time, mix together and finally put on background, but there are blend artifacts โ€” accuracy loss or something.

from moviepy.editor import *

def cycle(clip, ismask=False, transparent=False):
    d = clip.duration
    result = CompositeVideoClip([
                clip, 
                clip.set_start(d/2),
                clip.set_start(d)
             ], 
             ismask=ismask, transparent=transparent) \
             .subclip(d/2, 3*d/2)
    return result

gif = VideoFileClip("./source.gif", audio=False)
gif_mask = VideoFileClip("./source_mask.gif", audio=False)
bg = gif.copy()

mask_mf = lambda t: gif_mask.reader.get_frame(t)[:,:,0]/255.0
mask = VideoClip(ismask=True, make_frame=mask_mf).set_duration(gif.duration)
cat = gif.set_mask(mask)

composition = CompositeVideoClip([bg, cycle(cat, transparent=True)])
composition.preview()
#composition.write_gif('result.gif', fuzz=10, fps=24)

There are no artifacts with "binary" mask:
mask_mf = lambda t: gif_mask.reader.get_frame(t)[:,:,0]/255

source.gif
source_mask.gif
result.gif

Windows - Unable to export simple sequence to gif

So I installed Numpy, ImageMagick, ffmpeg (all in 64 bits since I run Python 2.7 64 bits).

When I run the following code:

from moviepy.editor import *

VideoFileClip('D:/vids/myvideo.mp4').\
    subclip((10, 0.00), (10, 10.00)).\
    to_gif('D:/vids/test.gif')

I get the following error message:

MoviePy: Generating GIF frames
MoviePy: running convert -delay 4 -dispose 1 -loop 0 `seq -f D:/vids/test_TEMP%04g.png 1 1 250` -coalesce -fuzz 01% -layers OptimizeTransparency D:/vids/test.gif
convert.exe: unable to open image ``seq': No such file or directory @ error/blob.c/OpenBlob/2643.
convert.exe: no decode delegate for this image format ``seq' @ error/constitute.c/ReadImage/555.
convert.exe: unrecognized option `-f' @ error/convert.c/ConvertImageCommand/1614.
MoviePy: GIF generated !

So since seq is not usable in Windows, I also installed Gow (Gnu on Windows) and it's still not running.

Help?

AssertionError in ffmpeg_reader.py

I get this error when trying to use moviepy

>>> from moviepy.editor import *
>>> VideoFileClip("test.mp4")
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File ".../local/lib/python2.7/site-packages/moviepy/v
ideo/io/VideoFileClip.py", line 46, in __init__
    self.reader = FFMPEG_VideoReader(filename, pix_fmt=pix_fmt)
  File ".../local/lib/python2.7/site-packages/moviepy/v
ideo/io/ffmpeg_reader.py", line 33, in __init__
    self.lastread = self.read_frame()
  File .../local/lib/python2.7/site-packages/moviepy/v
ideo/io/ffmpeg_reader.py", line 109, in read_frame
    assert len(s) == nbytes
AssertionError

(This line)

Python version: 2.7.3
pip freeze: (I installed moviepy via pip)

Pygments==1.6
argparse==1.2.1
bpython==0.12
decorator==3.4.0
moviepy==0.2.1.7
numpy==1.8.0
tqdm==1.0
wsgiref==0.1.2

ffmpeg version

ffmpeg 0.8.10-4:0.8.10-0ubuntu0.12.04.1
libavutil    51. 22. 2 / 51. 22. 2
libavcodec   53. 35. 0 / 53. 35. 0
libavformat  53. 21. 1 / 53. 21. 1
libavdevice  53.  2. 0 / 53.  2. 0
libavfilter   2. 15. 0 /  2. 15. 0
libswscale    2.  1. 0 /  2.  1. 0
libpostproc  52.  0. 0 / 52.  0. 0

infinite audio loop

It would be great to have a way to specify that a specific audio file has to loop all over the duration of the video clip

Enhancement: loading animated gifs, passing frame range to subclip()

I've tried to load animated gif with VideoFileClip and got

  File "D:\dev\projects\python\movie_py\venv\lib\site-packages\moviepy\video\io\ffmpeg_reader.py", line 215, in ffmpeg_parse_infos
    hms = map(float, line[match.start()+1:match.end()].split(':'))
AttributeError: 'NoneType' object has no attribute 'start'
Exception AttributeError: "FFMPEG_VideoReader instance has no attribute 'proc'" in <bound method FFMPEG_VideoReader.__del__ of <moviepy.video.io.ffmpeg_reader.FFMPEG_VideoReader instance at 0x023D95A8>> ignored

So I had to convert source.gif frames/xx_%05d.png first and then load frames with ImageSequenceClip()

Second: it would be nice if you could specify start/end frame in subclip() along with start/end time

Create a mailing list

Moviepy is wonderful project, turning very popular (almost 1200 stars!). We need a mailing list to

  • send Important announces (new releases, big api changes, etc.)
  • discuss raw ideas (don't replace github issues)
  • share examples and success stories :)
  • get community support

http://librelist.com/ is a good option.

Possible memory leak

Hi,
I need to process a lot of videos, but not many at a time. However I keep running into memory issues, even after upgrading hardware. I think I have tracked down the issue and any help would be appreciated.

It appears that the ffmpeg_reader/writer stays open even if a clip is deleted. Here is an example:

import psutil
from moviepy.editor import *
import time

initial_set = psutil.get_pid_list()

clip = VideoFileClip("sync_test2/1/GOPR0185.MP4", audio=False)
new_set = psutil.get_pid_list()
new_ps = set(new_set)-set(initial_set)
print new_ps

for new_p in new_ps:
    p = psutil.Process(new_p)
    print p.name
    print p.get_memory_percent()

del clip

time.sleep(2) # give subprocess time to close the processes

check_set = psutil.get_pid_list()
for new_p in new_ps:
    if new_p in check_set:
        print str(new_p) + " is still open!"

When I run this I get:

set([19228, 19229])
ffmpeg
1.26245461454
ffmpeg
0.0
19228 is still open!
19229 is still open!

So my questions are: Is it possible to explicitly close the reader/writer after I am done with a clip? Is there a different way to delete a the clip? Is this a bug? Is there a different way for me to test this?

I can also try to fix this in my fork if you can point me to a good place to start.
Thanks.

ffmpeg hangs

I was using:

"from moviepy.video.io.ffmpeg_writer import FFMPEG_VideoWriter as FFW"
and
"from moviepy.video.io.ffmpeg_reader import FFMPEG_VideoReader as FFR"

To read a video, rotate the frame, and save it to a new video. (I'm sure there's an easier way to do that using your tool...but anyway)

ffmpeg would consistently hang after about 200 frames. I got it working by adding:

self.proc.stdout.close()
self.proc.stderr.close()
to the end of init in ffmpeg_writer.py

and

self.proc.stdin.close()
self.proc.stderr.close()
to the end of initialize() in ffmpeg_reader.py

based on the comments here:
http://stackoverflow.com/questions/16523746/ffmpeg-hangs-when-run-in-background

The video I was reading/writing is 1920x1080, 50seconds, ~20606kbps, 29fps, .mov file
and I'm using windows 7 if that matters.

It makes pygame crash

Python 2.7.6 (default, Feb 26 2014, 12:07:17) 
[GCC 4.8.2 20140206 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from moviepy.editor import *
>>> backgroundClip = ColorClip((1280,720))
>>> backgroundClip.set_duration(2).preview
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 2, in preview
  File "/usr/lib/python2.7/site-packages/moviepy/decorators.py", line 60, in requires_duration
    return f(clip, *a, **k)
  File "/usr/lib/python2.7/site-packages/moviepy/video/io/preview.py", line 94, in preview
    imdisplay(img, screen)
  File "/usr/lib/python2.7/site-packages/moviepy/video/io/preview.py", line 13, in imdisplay
    a = pg.surfarray.make_surface(imarray.swapaxes(0, 1))
  File "/usr/lib/python2.7/site-packages/pygame/surfarray.py", line 243, in make_surface
    return numpysf.make_surface (array)
  File "/usr/lib/python2.7/site-packages/pygame/_numpysurfarray.py", line 368, in make_surface
    blit_array (surface, array)
  File "/usr/lib/python2.7/site-packages/pygame/_numpysurfarray.py", line 437, in blit_array
    surface.get_buffer ().write (data, 0)
IndexError: bytes to write exceed buffer size
>>> 
~ % pacman -Q python2-pygame
python2-pygame 1.9.1-8
~ % 

"Bad File Descriptor" when creating VideoFileClip

Hello,

I'm using moviepy 0.2.1.8.10 on OS X 10.7.5 with python 2.7.8
Executing:

from moviepy.editor import VideoFileClip
VideoFileClip("some_video.mp4")

always throws a
IOError: [Errno 9] Bad file descriptor
at
moviepy-0.2.1.8.10-py2.7.egg/moviepy/audio/io/readers.py

I've attached a screenshot of the traceback, in case it's useful.
Any idea why this error is occurring?

screen shot 2014-09-15 at 5 42 42 pm

Tabs in python code

Some of the files have tabs instead of spaces in some places. This is a barrier against using the package in Python3

The files I found were:
moviepy/video/compositing/transitions.py
moviepy/video/fx/even_size.py
moviepy/video/fx/fadeout.py
moviepy/video/fx/headblur.py
moviepy/video/fx/mirror_x.py
moviepy/video/fx/mirror_y.py
moviepy/video/fx/scroll.py
moviepy/video/fx/time_mirror.py
moviepy/video/io/sliders.py
moviepy/video/tools/tracking.py

and after detabbing, I could import moviepy.editor in python3 .

"list index out of range" error or Arch Linux x86-64

When the interline parameter of TextClip is not specified or is above about -19 (the specific number seems to depend on font and font size), I get this error:

Traceback (most recent call last):
File "movie3.py", line 18, in
font='Courier').
File "/usr/lib/python2.7/site-packages/moviepy/video/VideoClip.py", line 842, in init
ImageClip.init(self, tempfile, transparent=transparent)
File "/usr/lib/python2.7/site-packages/moviepy/video/VideoClip.py", line 651, in init
img = ffmpeg_reader.read_image(img,with_mask=transparent)
File "/usr/lib/python2.7/site-packages/moviepy/video/io/ffmpeg_reader.py", line 152, in read_image
vf = FFMPEG_VideoReader(filename, pix_fmt=pix_fmt)
File "/usr/lib/python2.7/site-packages/moviepy/video/io/ffmpeg_reader.py", line 17, in init
self.load_infos(print_infos)
File "/usr/lib/python2.7/site-packages/moviepy/video/io/ffmpeg_reader.py", line 55, in load_infos
line = [l for l in lines if ' Video: ' in l][0]
IndexError: list index out of range

Closing VideoFileClip

Hi,

I'm using moviepy in an artwork, making concatenated videos selected from a list of 10k video files. I'm running this process in an infinite loop (making a video and displaying it), but I can't find a way to close the video files I used, and after a while it halts on the "python - IOError: [Errno 24] Too many open files" error. It is on the constructor of VideoFileClip.

Is there a way to release the files, cause I can't find any in the object methods?
Many thanks.

ffmpeg_writer.py

Hi when I do something like:

myVideoClip.to_videoFile("myFileName.mp4", codec="libx264")

I get a broken pipe error which originates from where ffmpeg_writer.py create the ffmpeg subprocess around line 78:

        cmd = (
            [ FFMPEG_BINARY, '-y',
            "-loglevel", "panic" if logfile==DEVNULL else "info",
            "-f", 'rawvideo',
            "-vcodec","rawvideo",
            '-s', "%dx%d"%(size[0],size[1]),
            '-pix_fmt', "rgba" if withmask else "rgb24",
            '-r', "%.02f"%fps,
            '-i', '-', '-an',
            '-vcodec', 'libx264']
            + (['-b',bitrate] if (bitrate!=None) else [])

            # http://trac.ffmpeg.org/ticket/658
            + (['-pix_fmt', 'yuv420p']
                  if ((codec == 'libx264') and
                     (size[0]%2 == 0) and
                     (size[1]%2 == 0))

               else [])

            + [ '-r', "%d"%fps, filename]
            )

        self.proc = sp.Popen(cmd, stdin=sp.PIPE,
                                  stderr=logfile,
                                  stdout=DEVNULL)

If you remove the line '-vcodec', 'libx264' parameter it seems to work. I don't know why this causes an error, or how to resolve it so that a codec can be specified. Maybe stderr could provide some useful information here.

List decorator and pygame as dependencies on PyPI

When I installed moviepy via "pip install moviepy", it did not automatically install the "decorator" and "pygame" modules, which are also available through pip. I had to install these manually.

Can not load the fonts

Hi,

I can't get the TextClip to work, since any font I tried errors out. I'm on MacOS 10.9.2.

~ % python
Python 2.7.6 (default, Apr  9 2014, 11:48:52) 
[GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.38)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from moviepy.editor import *
>>> txt = TextClip("V. Zulkoninov - Ukulele Sonata", font='Arial-regular')

MoviePy: WARNING !
   The following command returned an error:
convert: unable to read font `Arial-regular' @ warning/annotate.c/RenderType/871.
convert: unable to read font `Arial-regular' @ error/annotate.c/RenderFreetype/1126.
convert: Postscript delegate failed `/var/tmp/magick-687910PjuTb0L0M2g': No such file or directory @ error/ps.c/ReadPSImage/840.
convert: unable to read font `Arial-regular' @ warning/annotate.c/RenderType/871.
convert: unable to read font `Arial-regular' @ error/annotate.c/RenderFreetype/1126.
convert: Postscript delegate failed `/var/tmp/magick-687918Bk0Mx9P3V8w': No such file or directory @ error/ps.c/ReadPSImage/840.
convert: no images defined `PNG32:/var/folders/lf/myf7bjr57_jg7_5c4014bh640000gn/T/tmpGNVPDe.png' @ error/convert.c/ConvertImageCommand/3150.
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/site-packages/moviepy/video/VideoClip.py", line 1078, in __init__
    subprocess_call(cmd, verbose=False )
  File "/usr/local/lib/python2.7/site-packages/moviepy/tools.py", line 34, in subprocess_call
    raise IOError
IOError
>>> 

Can't write a movie with default codec

It seems I can only use the 'raw' encoding.

>>> video.to_movie("myHolidays_edited.avi",fps=24)
Making file myHolidays_edited.avi ...
Rendering video :
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "moviepy/VideoClip.py", line 323, in to_movie
    codec = 0 if (codec=='raw') else cv2.VideoWriter_fourcc(*codec)
AttributeError: 'module' object has no attribute 'VideoWriter_fourcc'
>>> video.to_movie("myHolidays_edited.avi",fps=24,codec='raw')
Making file myHolidays_edited.avi ...
Rendering video : 0%  10%  20%  30%  40%  50%  60%  70%  80%  90%  done !
>>> 

I have cv2 version 2.4.6.1, if that matters.

Setting conf.py ffmpeg path on the fly from python

Hi there,

at the moment it is not possible to modify the FFMPEG_BINARY or IMAGEMAGICK_BINARY from a running python environment. The only way to modify it is to hardcode it in the conf.py or set the PATH environment to let it find the binaries automaitcally.

The problem ist when trying to bundle an application with cx_freeze as Win32Gui (without console) app. In that case os.environ["PATH"] is ignored and the binaries can not be found. If bundled as a console app, the binaries can be found by appending the ffmpeg path to os.environ["PATH"].

The problem is, that conf.py can not be loaded and modified if ffmpeg can not be found.

A possible soultion would be not to raise the IOError.
Then it is possible to import first only moviepy.conf and modify it on the fly:

import moviepy.conf as movieconf
movieconf.FFMPEG_BINARY = os.path.join("my_path", "ffmpeg", "ffmpeg.exe")

All calls to moviepy after setting the path now work.

Additionally there could be a function to get the FFMPEG path for other moviepy modules.

def get_mffpeg_binary():
    if not try_cmd(FFMPEG_BINARY):
        raise IOError("FFMPEG binary not found...")
    return FFMPEG_BINARY

See also the pull request from @sanfx with the xml config which has the same target to not hardcode the ffmpeg paths.

Reading video on Ubuntu 13.10 does not work

Thanks for the nice library. However, I cannot get it to work on any of the video files that I try. I took the ffmpeg_reader.py and ripped out a few small parts to make it standalone.

Tried with Python 2.7 and Python 3.3. Reinstalled ffmpeg to be sure.

I executed:

filename = '/path/to/my/video/file'
vf = FFMPEG_VideoReader(filename)
vf.close()

In all cases the line in read_frame() reads not enough bytes:

s = self.proc.stdout.read(self.depth_w_h)

Now, note that read() returns at most the given number of bytes, but any subsequent call to read that I make does not yield any more bytes.

Related: Is there a perhaps an example movie on the web which is known to work?

Write_Gif returns errno 2

Calling write_gif

from moviepy.editor import *

clip_file = "./Import-csv.mp4"

clip = (VideoFileClip("./Import-csv.mp4", audio=False).subclip((0,0.0),(0,16.25)))

clip.write_gif("./Import_csv.gif")

returns the following error:

MoviePy Running:
convert -delay 3 -dispose 1 -loop 0 Import_csv_GIFTEMP*.png -coalesce -fuzz 01% -layers OptimizeTransparency Import_csv.gifTraceback (most recent call last):
File "/Users/doboyle/convert.py", line 7, in <module>
  clip.write_gif("Import_csv.gif")
  File "<string>", line 2, in write_gif
  File "/Library/Python/2.7/site-packages/moviepy/decorators.py", line 49, in requires_duration
    return f(clip, *a, **k)
  File "/Library/Python/2.7/site-packages/moviepy/video/VideoClip.py", line 476, in write_gif
    subprocess_call( cmd, verbose = verbose )
  File "/Library/Python/2.7/site-packages/moviepy/tools.py", line 27, in subprocess_call
    proc = sp.Popen(cmd, stderr = sp.PIPE)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 709, in __init__
    errread, errwrite)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1326, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory
[Finished in 25.9s with exit code 1]

write_videofile jumps

Hi to all

i'm trying to create a pipeline for frame-by-frame analysis of medical images (cineangiographies)

i wrote a little script that reads a DICOM file that contains an angiograpy and generates the corresponding .avi file

from moviepy.editor import *
import numpy as np
import matplotlib.pyplot as plt
import SimpleITK as stk
import dicom
import os
import shutil

dicomfilePath = "/home/salvatore/Didattica/data/IMG00001"
outputVideoPath = "/home/salvatore/Videos/"

fileDicom = stk.ReadImage(dicomfilePath)
infoDicom = dicom.read_file(dicomfilePath)

matrice = stk.GetArrayFromImage(fileDicom)

nframes = matrice.shape[0]
cine_fps = infoDicom.CineRate
patient_id = infoDicom.PatientID
study_id = infoDicom.StudyID
altro = infoDicom.InstanceNumber

# i create a temporary directory
directory = "/home/salvatore/Documents/appoggio"
if not os.path.exists(directory):
    os.makedirs(directory)

# then i save all frames
for i in range(0,nframes):
    plt.imsave(directory + "/frame" + str(i) + ".tiff", matrice[i,:,:], cmap=plt.cm.gray)

# using such frames to create a Sequence Clip
newVideo = ImageSequenceClip(directory,fps=cine_fps)

# write to video file
newVideo.write_videofile(outputVideoPath + patient_id + ".avi", fps=cine_fps , codec='png' ) 

# delete dir
shutil.rmtree(directory)

i have this "jumps" in my final video

https://www.youtube.com/watch?v=VfinQD6buZA&feature=youtu.be

ideas?

Windows 8 Error

I am reporting here by Zulko's permission.

http://zulko.github.io/blog/2014/01/23/making-animated-gifs-from-video-files-with-python/#comment-1342388341

I use below code:

import os
from moviepy.editor import *
files = sorted( os.listdir("clips/") )
clips = [ VideoFileClip('clips/%s'%f) for f in files]
video = concatenate(clips)
video.to_videofile("demos.mp4",fps=25, codec="mpeg4")

If there is only one mp4 in clips folder, script works ok and demos.mp4 created. But if there are two mp4 videos in clips folder, script throws error. Output is below:

MoviePy: building video file demos.mp4
----------------------------------------
Writing audio in TEMP_MPY_to_videofile_SOUND_demos.ogg

|----------| 0/952   0% [elapsed: 00:00 left: ?, ? iters/sec]
|#---------| 113/952  11% [elapsed: 00:00 left: 00:05, 165.93 iters/sec]
|##--------| 214/952  22% [elapsed: 00:01 left: 00:04, 181.20 iters/sec]
|###-------| 300/952  31% [elapsed: 00:01 left: 00:03, 177.51 iters/sec]
|####------| 420/952  44% [elapsed: 00:02 left: 00:02, 191.78 iters/sec]
|#####-----| 551/952  57% [elapsed: 00:02 left: 00:01, 204.68 iters/sec]
|#######---| 672/952  70% [elapsed: 00:03 left: 00:01, 210.39 iters/sec]
|########--| 797/952  83% [elapsed: 00:03 left: 00:00, 215.41 iters/sec]
|#########-| 920/952  96% [elapsed: 00:04 left: 00:00, 218.74 iters/sec]

Done writing Audio in TEMP_MPY_to_videofile_SOUND_demos.ogg !

Writing video into TEMP_MPY_to_videofile_demos.mp4

|----------| 0/1078   0% [elapsed: 00:00 left: ?, ? iters/sec]
|----------| 38/1078   3% [elapsed: 00:00 left: 00:14, 72.66 iters/sec]
|----------| 83/1078   7% [elapsed: 00:01 left: 00:12, 80.74 iters/sec]
|#---------| 130/1078  12% [elapsed: 00:01 left: 00:11, 84.75 iters/sec]
|#---------| 173/1078  16% [elapsed: 00:02 left: 00:10, 84.97 iters/sec]
|##--------| 216/1078  20% [elapsed: 00:02 left: 00:10, 84.91 iters/sec]
|##--------| 263/1078  24% [elapsed: 00:03 left: 00:09, 86.31 iters/sec]
|##--------| 312/1078  28% [elapsed: 00:03 left: 00:08, 87.96 iters/sec]
|###-------| 351/1078  32% [elapsed: 00:04 left: 00:08, 86.62 iters/sec]
|###-------| 399/1078  37% [elapsed: 00:04 left: 00:07, 87.58 iters/sec]
|####------| 434/1078  40% [elapsed: 00:05 left: 00:07, 85.77 iters/sec]
|####------| 475/1078  44% [elapsed: 00:05 left: 00:07, 85.39 iters/sec]
|####------| 514/1078  47% [elapsed: 00:06 left: 00:06, 84.72 iters/sec]
Traceback (most recent call last):
  File "C:\Users\slome\Desktop\text.py", line 6, in <module>
    video.to_videofile("demos.mp4",fps=25, codec="mpeg4")
  File "C:\Python27\lib\site-packages\moviepy-0.2.1.7.15-py2.7.egg\moviepy\video\VideoClip.py", line 282, in to_videofile
    verbose=verbose)
  File "C:\Python27\lib\site-packages\moviepy-0.2.1.7.15-py2.7.egg\moviepy\video\io\ffmpeg_writer.py", line 136, in ffmpeg_write_video
    frame = clip.get_frame(1.0*i/fps)
  File "C:\Python27\lib\site-packages\moviepy-0.2.1.7.15-py2.7.egg\moviepy\video\compositing\concatenate.py", line 64, in gf
    return clipslist[i].get_frame(t - tt[i])
  File "C:\Python27\lib\site-packages\moviepy-0.2.1.7.15-py2.7.egg\moviepy\video\io\VideoFileClip.py", line 66, in <lambda>
    self.get_frame = lambda t: self.reader.get_frame(t)
  File "C:\Python27\lib\site-packages\moviepy-0.2.1.7.15-py2.7.egg\moviepy\video\io\ffmpeg_reader.py", line 156, in get_frame
    result = self.read_frame()
  File "C:\Python27\lib\site-packages\moviepy-0.2.1.7.15-py2.7.egg\moviepy\video\io\ffmpeg_reader.py", line 118, in read_frame
    assert len(s) == nbytes
AssertionError

Could you look into this please?

VideoFileClip error

Hi when I try to pass a .mp4 file to VideoFileClip I get the following backtrace in iPython:

----> 1 VideoFileClip("./test.mp4")

/usr/local/lib/python2.7/dist-packages/moviepy/video/io/VideoFileClip.pyc in __init__(self, filename, ismask, has_mask, audio, audio_buffersize, audio_fps, audio_nbytes, verbose)
     56         # Make a reader

     57         pix_fmt= "rgba" if has_mask else "rgb24"
---> 58         self.reader = FFMPEG_VideoReader(filename, pix_fmt=pix_fmt)
     59 
     60         # Make some of the reader's attributes accessible from the clip


/usr/local/lib/python2.7/dist-packages/moviepy/video/io/ffmpeg_reader.pyc in __init__(self, filename, print_infos, bufsize, pix_fmt)
     40 
     41         self.pos = 1
---> 42         self.lastread = self.read_frame()
     43 
     44 

/usr/local/lib/python2.7/dist-packages/moviepy/video/io/ffmpeg_reader.pyc in read_frame(self)
     95                     self.duration)+
     96                    "Using the last valid frame instead.")
---> 97             result = self.lastread
     98 
     99         else:

AttributeError: FFMPEG_VideoReader instance has no attribute 'lastread'

Edit: I got it fixed by building/installing the latest version of ffmpeg from github. The one in the ubuntu 12.04 repo is out of date.

supress console window of popen calls if used with cx_freeze win32gui

If moviepy is used with cx_freeze as a win32gui app (I think py2exe has the same issues) there is always a black console window opened when the popen calls are made.

This can be suppressed by setting the Popen parameter creationflags=0x08000000 (CREATE_NO_WINDOW).

I think this is a windows only parameter and this must be handled seperately for win/linux.

'to_gif' raises IOError/OSError when no 'program' parameter is given

Because the to_gif function uses the ImageMagick as default program to generate the gif. But when there's no ImageMagick, there is no fallback for ffmpeg.

I fixed it by manually changing the parameter to 'ffmpeg' (which is bad) but maybe the best thing would be to add a GIF_PROGRAM variable in the conf.py for people to choose from imagemagick or ffmpeg ?

TextClips can cause an Exception if the text argument starts with a '@'

I noticed making TextClips with twitter bodies that it would cause an exception to get raised:

Creating a TextClip with a body like this

@raymondh, list comprehensions are awesome!

it would raise an error like this:

TypeError: coercing to Unicode: need string or buffer, NoneType found

I believe the issue spawns at line 1175 of moviepy/video/VideoClip. The __init__checks if the text does not start with '@' and if it does not, then it creates a temporary file for. If it does start with '@' then no temporary file is created, and the exception is raised at line 1230 when an os.path.exists is called on the temptxt, which does not exist because of the check performed above! I am unsure what the initial check is there for, but I am pretty sure it is part of the issue. What is it checking for exactly? Is there a better way to perform this check than make sure the user input does not start with '@'?

Thanks for the awesome library zulko!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.