from PIL import Image import os import glob import shutil import subprocess maxheight = 2000 w2xcpp = './waifu2x-converter/waifu2x-converter-cpp.exe' outformat = 'jpg' outquality = 80 for infile in glob.glob('./in/**', recursive=True): if os.path.isdir(infile): continue try: outdir = os.path.join("./out/", os.path.basename(os.path.dirname(infile))) os.makedirs(outdir, exist_ok=True) # 外部に渡すため絶対パスに変換 infile = os.path.abspath(infile) outfile = os.path.abspath(os.path.join(outdir, os.path.splitext(os.path.basename(infile))[0]+'.'+outformat)) # 出力先が存在する場合は処理しない if os.path.exists(outfile): print("FILE EXISTS!", outfile) continue img = Image.open(infile) # double型のまま処理できるので丸めるのやめた scale = maxheight / img.height # 丸めたスケールが1倍以下の時とサイズが最大以上の時は処理せずコピーする if scale <= 1.0 or img.height >= maxheight: print("SIZE OVER!", outfile) print("height:", img.height) print("scale:", scale) if os.path.splitext(os.path.basename(infile))[1] == os.path.splitext(os.path.basename(outfile))[1] : shutil.copy2(infile, outfile) else : # 画像形式を統一する print("Convert to:", outformat) img = img.convert('RGB') img.save(outfile, quality=outquality) continue # スケールが2以上の場合は2とし、3倍以上の拡大を行わない if scale >= 2.0: scale = 2.0 w2xcpp = os.path.abspath(w2xcpp) subprocess.run(f'{w2xcpp} --scale-ratio {scale} -f {outformat} -q {outquality} -j 4 -p 0 -i "{infile}" -o "{outfile}"', shell = True) except OSError as e: pass