Skip to content

Instantly share code, notes, and snippets.

@yokoleia
Forked from michaelosthege/convert.py
Last active November 25, 2020 12:03
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save yokoleia/faa6c10f702e25ae2df8929ecc24b684 to your computer and use it in GitHub Desktop.
Save yokoleia/faa6c10f702e25ae2df8929ecc24b684 to your computer and use it in GitHub Desktop.
Mass Convert MP4/AVI clips to GIF with a multithreaded Python function, using a variable to set number of threads required.
import imageio
import os, sys
import glob
import threading
import time
class TargetFormat(object):
GIF = ".gif"
MP4 = ".mp4"
AVI = ".avi"
def filenameFromPath(inputpath):
return inputpath.split("\\")[-1:][0]
def convertFile(inputpath, targetFormat):
"""Reference: http://imageio.readthedocs.io/en/latest/examples.html#convert-a-movie"""
filename = filenameFromPath(inputpath)
outputpath = "outputfiles\\" + filename.split(".")[0] + targetFormat
reader = imageio.get_reader(inputpath)
fps = reader.get_meta_data()['fps']
writer = imageio.get_writer(outputpath, fps=fps)
for i,im in enumerate(reader):
writer.append_data(im)
writer.close()
print("\t\tFinished: \t{0}".format(filenameFromPath(inputpath)))
def createThread(threads, inputpath):
t = threading.Thread(name = filenameFromPath(inputpath), target=convertFile, args=(inputpath,TargetFormat.GIF))
threads.append(t)
t.start()
def main():
maxThreads = 9
index = 0
conv_list = glob.glob("convertfiles\\*.mp4")
threads = []
while (len(threads)<len(conv_list)):
if (len(threads) - len([t for t in threads if not t.is_alive()]) < maxThreads):
inputpath = conv_list[index];
print("File {0} of {1}\tStarted: \t{2}".format(index+1, len(conv_list),filenameFromPath(inputpath)))
createThread(threads, conv_list[index] )
index+=1
if __name__ == '__main__':main()
@yokoleia
Copy link
Author

This is a multi-threaded expansion of the original script to increase efficiency when converting multiple files.

@yokoleia
Copy link
Author

Results obviously variable. With a test library of 9 mp4s, achieved ~2.6x speed increase. Varies depending on maximum threads created, number of files to convert, size of each file.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment