3
\$\begingroup\$

As a 'trying to learn Python' project, I am using ffmpy to stitch together a timelapse from a series of still images. I'd like the script to output a couple of formats for web use.

This is what I have:

#!/usr/bin/env python3

import datetime
import ffmpy
import os

now = datetime.datetime.now()
ydr = now.strftime('%Y')
mdr = now.strftime('%m')
ddr = now.strftime('%d')

ipath = str(os.path.dirname(os.path.abspath(__file__))) + '/images/' + ydr + '/' + mdr + '/*/*.jpg'
opath1 = str(os.path.dirname(os.path.abspath(__file__))) + '/videos/' + ydr + mdr + '.mp4'
opath2 = str(os.path.dirname(os.path.abspath(__file__))) + '/videos/' + ydr + mdr + '.webm'

ff = ffmpy.FFmpeg(
    inputs={ipath: '-loglevel info -pattern_type glob -framerate 18 '},
    outputs={opath1: '-c:v libx264 -vf "scale=1280:-1,hqdn3d=luma_spatial=1" -pix_fmt yuv420p'}
)
ff.run()

ff = ffmpy.FFmpeg(
    inputs={ipath: '-loglevel info -pattern_type glob -framerate 18 '},
    outputs={opath2: '-c:v libvpx -vf "scale=1280:-1,hqdn3d=luma_spatial=1" -b:v 1M -c:a libvorbis'}
)
ff.run()

It works, but it's kinda ugly and I'm pretty sure there's a more efficient and 'Pythonic' way of doing this. Any pointers?

\$\endgroup\$
2
\$\begingroup\$
  • Use path.join() instead of manually concatenating file paths

    This will make sure that it will work on different OS's, windows uses \ backslashes for instance

  • No need to convert with strftime

    A datetime has years, months and days as properties, if you want them in str format you could:

    map(str, iterable) to convert them into strings

Code

import datetime
import os.path

now = datetime.datetime.now()
y, m = map(str, (now.year, now.month))

location = os.path.dirname(os.path.abspath(__file__))
ipath = os.path.join(location, 'images', y, m + '.jpeg')
video_path_mp4 = os.path.join(location, 'videos', y, m + '.mp4')
video_path_webm = os.path.join(location, 'videos', y, m + '.webm')
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.