Thursday, April 14, 2022

[SOLVED] turn PIL images into video on Linux

Issue

I am using python 3 on Debian Linux, I am using the python imaging library (pillow fork) to produce a sequence of images, I would like to output the images as a video in a widely supported format (don't care too much which one as long as it's sometthing I can view in VLC and import into video editing software).

How can I do this?


Solution

One soloution is to use opencv, data can be bridged from PIL to opencv via numpy. An outline of the code I used is.

import numpy as np
from PIL import Image, ImageDraw
import cv2

videodims = (100,100)
fourcc = cv2.VideoWriter_fourcc(*'avc1')    
video = cv2.VideoWriter("test.mp4",fourcc, 60,videodims)
img = Image.new('RGB', videodims, color = 'darkred')
#draw stuff that goes on every frame here
for i in range(0,60*60):
    imtemp = img.copy()
    # draw frame specific stuff here.
    video.write(cv2.cvtColor(np.array(imtemp), cv2.COLOR_RGB2BGR))
video.release()

Notes:

  • You'll need to install the relavent packages, if using pip these are "opencv-python", "pillow" and "numpy". If using debian packages these are "python3-opencv", "python3-pil" and "python3-numpy".
  • I got the basic technique from https://blog.extramaster.net/2015/07/python-pil-to-mp4.html)
  • Extramaster claimed that passing -1 as codec parameter would pop up a codec selection list, that didn't work for me.
  • I ended up having to use Debian buster (=testing at the time of writing) as earlier releases lacked the python3-opencv package.
  • It seems if the dimensions of your frame do not match the dimensions of the video opencv will silently fail to add the frame.


Answered By - plugwash
Answer Checked By - Mary Flores (WPSolving Volunteer)