ffmpegとwaifu2xで動画を拡大してみる。

コンピュータ

waifu2xの画像の拡大機能をつかって動画を拡大してみたいと思います。
ffmpegは動画から静止画を出力する機能があるので、すべてのフレームをpng画像で出力し、それをwaifu2xで拡大します。
拡大したpngファイルをffmpegで再度動画に作り直します。
ffmpegとwaifu2xを何度か実行することになりますが、テンポラリファイルを扱うのでその後始末を考えて手順をpyhtonスクリプトで実行させます。

スクリプト

#!/usr/bin/python3

#
# 動画の再作成
#

import os
import subprocess
from subprocess import PIPE
import glob

in_path = '/var/share/Video/HS3005C.mp4'
out_path = './HS3005C.mp4'

temp_dir = './remake_move_temp'
temp_audio_path = "{}/temp.aac".format(temp_dir)
waifu2x_temp_dir = './waifu2x_temp'

fps = "29.97"

os.mkdir(temp_dir)
os.mkdir(waifu2x_temp_dir)

cmd = ['ffmpeg','-i',in_path,'-vn','-acodec','copy',temp_audio_path]
proc = subprocess.run(cmd, stdout=PIPE, stderr=subprocess.DEVNULL, text=True)

if (proc.returncode == 0):
    print("音声分離成功")

cmd = ['ffmpeg', '-i', in_path, '-r', fps, "{}/image%06d.png".format(temp_dir)]
proc = subprocess.run(cmd, stdout=PIPE, stderr=subprocess.DEVNULL, text=True)

if (proc.returncode == 0):
    print("静止画抽出成功")

for f in glob.glob("{}/image*.png".format(temp_dir)):
    ifile = f
    ofile = "{}/{}".format(waifu2x_temp_dir, os.path.basename(f))
    print(ofile)

    cmd = ['waifu2x-converter-cpp', '-f', 'png', '--noise-level', '3', '--scale-ratio', '2', '-m', 'noise-scale', '-p', '0', '-i', ifile,'-o', ofile]
    proc = subprocess.run(cmd, stdout=PIPE, stderr=PIPE, text=True)

print("拡大終了")

cmd = ['ffmpeg', '-framerate', fps, '-i', "{}/image%06d.png".format(waifu2x_temp_dir), '-i', temp_audio_path, '-c:v', 'libx264', '-c:a', 'copy', '-map', '0:v:0', '-map', '1:a:0', '-r', fps, out_path]
proc = subprocess.run(cmd, stdout=PIPE, stderr=PIPE, text=True)

if (proc.returncode == 0):
    print("動画作成成功")

for f in os.listdir(temp_dir):
    os.remove("{}/{}".format(temp_dir,f))

for f in os.listdir(waifu2x_temp_dir):
    os.remove("{}/{}".format(waifu2x_temp_dir,f))

if (os.path.exists(temp_dir)):
    print("{}を削除".format(temp_dir))
    os.rmdir(temp_dir)

if (os.path.exists(waifu2x_temp_dir)):
    print("{}を削除".format(waifu2x_temp_dir))
    os.rmdir(waifu2x_temp_dir)

感想

一応拡大された動画は出来上がりましたが、静止画ほど効果的では無かったです。エンコードを何度も実行しているので劣化が進んだことが想像できます。また、この処理はものすごく時間がかかります。1枚のpngファイルの拡大時間を7秒だとすると1秒30フレームの30分動画を拡大処理するのに要する時間は30分x60秒x30フレームx7秒=378000秒=6300分=105時間となります。強力なGPUがあれば改善されるかもしれませんが、個人的に実用するにはハードルが高そうです。

コメント