1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

pythonでgifアニメを画像で切り分けて加工後元に戻す

Posted at

pythonでgifアニメを画像で切り分けて加工後gifに戻します
gifアニメの元画像をなくした時に再度編集したい時とかにご利用ください

ファイル構造

├── gifStep1.py
├── gifStep2.py
├── step1
│   └── input.gif
├── step2
│   ├── step1で出力されたinput.gifの分割画像
├── step3
│   ├── 加工後のpngファイル(gifでも可。その場合「gifStep2.py」のpngの部分をgifに変更する)
└── step4
    └── output.gif

gitを保存する

分割したいgitをstep1のフォルダーに入れる。input.gifに名前を変更する
(プログラムのファイル名を修正してもよいです)

aimkbiz.gif

gifを分割するプログラム

gifStep1.py

from pathlib import Path
from PIL import Image, ImageSequence

IMAGE_PATH = 'step1/input.gif'
DESTINATION = 'step2'
DEBUG_MODE = True

def main():
    frames = get_frames(IMAGE_PATH)
    write_frames(frames, IMAGE_PATH, DESTINATION)

# フレーム一覧を取得する
def get_frames(path):
    im = Image.open(path)
    return (frame.copy() for frame in ImageSequence.Iterator(im))

# フレーム毎に画像を保存する
def write_frames(frames, name_original, destination):
    path = Path(name_original)

    stem = path.stem
    extension = path.suffix

    dir_dest = Path(destination)
    if not dir_dest.is_dir():
        dir_dest.mkdir(0o700)
        if DEBUG_MODE:
            print('Destionation directory is created: "{}".'.format(destination))

    for i, f in enumerate(frames):
        name = '{}/{}-{}{}'.format(destination, stem, i + 1, extension)
        f.save(name)
        if DEBUG_MODE:
            print('A frame is saved as "{}".'.format(name))

if __name__ == '__main__':
    main()

実行

python3 gifStep1.py

分割した画像
image.png

画像を加工

step2に分割された画像が保存されるので、加工した画像をstep3に入れる

画像をマージしてgitにするプログラム

from PIL import Image
import os

list_file_name = []
list_images = []
dir = 'step3/'
for file_name in os.listdir(dir):
    if file_name.endswith('png'):
        list_file_name.append(dir + file_name)

list_file_name.sort()
ratio = 0.25
for i in list_file_name:
    img = Image.open(i)
    list_images.append(img)
list_images[0].save('step4/output.gif',save_all=True, append_images=list_images[1:],
optimize=True, duration=200, loop=0)

実行する

今回は背景だけ透過した画像をgifにしました

python3 gifStep2.py
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?