1

I'm using FFMPEG in python (using this tutorial) and my main goal is to take a screenshot and append it into an existing mp4 video(append it using the encoder, not raw appending).

That's the code I'm using right now, this script only writes a video of one frame(the first screenshot) and doesn't do anything with all the other screenshots.

command = [ FFMPEG_BIN,
    '-f', 'rawvideo',
    '-codec', 'rawvideo',
    '-s', '1920x1080', # size of one frame
    '-pix_fmt', 'rgb24',
    '-r', '24', # frames per second
    '-i', '-', # The input comes from a pipe
    '-an', # Tells FFMPEG not to expect any audio
    '-vcodec', 'mpeg4',
    'my_output_videofile.mp4' ]

for x in range(30):
    pipe = sp.Popen(command, stdin = sp.PIPE, stderr = sp.PIPE)
    im = np.array(ImageGrab.grab()).tostring()
    pipe.communicate(input = im)
    pipe.stdin.close()
    if pipe.stderr is not None:
        pipe.stderr.close()
    pipe.wait()

Edit: Apparently using Popen.communicate breaks the pipe (Thanks to Peter Wood !).

After fixing the pipe breaking scenario I have encountered another problem, after writing ~ 235 frames to the video the program crashes.

The new edited script:

command = [ FFMPEG_BIN,
    '-y',
    '-f', 'rawvideo',
    '-codec', 'rawvideo',
    '-s', '1920x1080', # size of one frame
    '-pix_fmt', 'rgb24',
    '-r', '24', # frames per second
    '-i', '-', # The input comes from a pipe
    '-an', # Tells FFMPEG not to expect any audio
    '-vcodec', 'mpeg4',
    'my_output_videofile.mp4' ]

pipe = sp.Popen(command, stdin = sp.PIPE, stderr = sp.PIPE)

for x in range(300):
    print x

    im = np.array(ImageGrab.grab()).tostring()
    pipe.stdin.write(im)
    pipe.stdin.flush()
Harel
  • 31
  • 4
  • Each loop you call the command again. Will that overwrite the output file? Maybe create the pipe outside the loop. – Peter Wood Mar 24 '17 at 11:19
  • @PeterWood I've been trying that method of creating the pipe outside the loop and writing in every iteration but after writing the first frame the pipe automatically closes... – Harel Mar 24 '17 at 11:23
  • See [Communicate multiple times with a process without breaking the pipe?](http://stackoverflow.com/questions/3065060/communicate-multiple-times-with-a-process-without-breaking-the-pipe) – Peter Wood Mar 24 '17 at 11:35
  • @PeterWood That actually fixed the problem ! But another problem I'm encountering right now is when I'm trying to write ~235 frames my script freezes, I'll edit the original post with the new script. – Harel Mar 24 '17 at 11:50
  • You should create a new question, and try to come up with a minimal example. See how to create a [mcve]. It's possible, as you don't read from `stdout` (or `stderr`) it's blocking. See [Non-blocking read on a subprocess.PIPE in python](http://stackoverflow.com/questions/375427/non-blocking-read-on-a-subprocess-pipe-in-python) – Peter Wood Mar 24 '17 at 12:02

0 Answers0