Skip to content

Instantly share code, notes, and snippets.

@recuraki
Created July 12, 2020 07:17
Show Gist options
  • Select an option

  • Save recuraki/8974b2509ce4491befcd588bbe9e398c to your computer and use it in GitHub Desktop.

Select an option

Save recuraki/8974b2509ce4491befcd588bbe9e398c to your computer and use it in GitHub Desktop.
mp4のサムネイル作成スクリプト
"""
このスクリプトはなに?
各種実験データの動画(mp4)のサムネイルを作ります。
実行したディレクトリ配下のすべてのmp4をrecurciveに取得し、
「そのmp4の配下のgifディレクトリ」にmp4を作ります。
サムネイルは1,2,3,4,11,22,33...%の時間軸を切り取ります
また、実行時に元のmp4がなくなったgifを削除します。
"""
import cv2
from PIL import Image, ImageDraw
from copy import deepcopy
from glob import glob
import re
import os
import sys
from pathlib import Path
isOverride = False
isUnlinkGif = True
if isUnlinkGif:
# 不要なgifを削除
curdir = Path.cwd()
paths = glob('**/*.gif', recursive=True)
for path in paths:
giffile = Path(path)
if len(giffile.parents) < 2:
continue
mp4file = Path(giffile.parents[1] / str(giffile.name[:-4]))
if mp4file.exists() is False:
print(giffile, "DELETE")
giffile.unlink()
curdir = Path.cwd()
paths = glob('**/*.mp4', recursive=True)
faillist = []
for path in paths:
file = path
filedir = Path(file).parent
basename = Path(file).name
gifdir = filedir / "gif"
gifdir.mkdir(exist_ok=True)
gifname = str(gifdir / basename) + ".gif"
if isOverride is False and Path(gifname).exists():
#print(" [SKIP]")
continue
print(path)
try:
cap = cv2.VideoCapture(file)
frame = cap.get(cv2.CAP_PROP_FRAME_COUNT)
fps = cap.get(cv2.CAP_PROP_FPS)
video_len_sec = frame / fps
w = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
h = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
l = list(range(11, 100, 5))
l = [2,1,2,3,4] + l
images = []
for i in l:
t = i /100 * video_len_sec * 1000
t = int(t)
print(" .", end="")
sys.stdout.flush()
cap.set(cv2.CAP_PROP_POS_MSEC, t)
res, img = cap.read()
asp = 800 / w
ds = tuple([int(w*asp),int(h*asp)])
img = cv2.resize(img, dsize=ds )
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
im = Image.fromarray(img)
images.append(deepcopy(im))
images[0].save(gifname, save_all=True, append_images=images[1:], optimize=False, duration=400, loop=0)
print("[DONE]")
except:
print(file)
print(" [SKIP]")
faillist.append(file)
for f in faillist:
print("[FAIL] {0}".format(f))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment