1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

生成したアニメーションGIFを自動検証する:ループ・透過・サイズをコードで判定

1
Posted at

生成AIで「アニメーションGIFを作る」パイプラインを作ると、失敗するのは生成そのものより受け渡し後です。ループせず1回で止まる、背景が黒い四角のまま、プラットフォームのサイズ上限を静かに超えている。どれも数行のコードで機械的に判定できるので、通るまでユーザーに返さないようにしています。

まず4つを見る

from PIL import Image

MAX_BYTES = 1_000_000  # アップロード上限


def inspect(path):
    img = Image.open(path)
    frames = getattr(img, "n_frames", 1)
    loop = img.info.get("loop")          # Netscape loop extension
    has_transparency = "transparency" in img.info
    size = len(open(path, "rb").read())
    return {
        "frames": frames,
        "loop": loop,
        "transparency_index": has_transparency,
        "bytes": size,
    }

読み方は単純です。

  • frames == 1 は静止画。棄却。
  • loop が無いと1回再生で停止。loop == 0 が無限ループ。
  • transparency in img.info はパレットに透過indexがあることしか意味しません。背景がそのindexを使っている保証はありません。

最後の点が罠で、透過indexを持つGIFでも背景が不透明な矩形で塗られていることが普通にあります。

メタデータではなくピクセルを見る

def background_is_transparent(path):
    img = Image.open(path).convert("RGBA")
    w, h = img.size
    pts = [
        (0, 0), (w - 1, 0), (0, h - 1), (w - 1, h - 1),   # 四隅
        (w // 2, 0), (0, h // 2), (w - 1, h // 2),        # 辺
    ]
    return all(img.getpixel(p)[3] == 0 for p in pts)

1点だけ見ると見落とします。生成物は左上だけきれいで、右辺に薄い残りが乗ることがあり、それはチャット上でそのまま表示されます。

サイズは「検査」ではなく「予算」

上限超過の最短の直しは再エンコードです。フレーム間引き + パレット削減。

def shrink(path, out, colors=128, step=2):
    img = Image.open(path)
    frames = []
    for i in range(0, img.n_frames, step):
        img.seek(i)
        frames.append(img.convert("RGBA").quantize(colors=colors))
    frames[0].save(
        out, save_all=True, append_images=frames[1:],
        loop=0, disposal=2, optimize=True,
    )

disposal=2(背景に戻す)が透過を保つ鍵です。既定値のままだと前フレームのピクセルが後続フレームに残り、通称ゴーストトレイルになります。

失敗したら失敗として返す

生成は「フレーム数 > 1、無限ループ、境界が透過、対象サイズで容量内」の4条件が揃ったときだけ完了。揃わなければクレジットを返して終わりにします。中途半端な成果物を渡すより、失敗として返したほうが後工程が楽です。

Twitch向けに書き出す場合は順序も決まります。大きめの正方形で生成 → 検証 → 112 / 56 / 28 px にアルファを保つリサンプラで縮小 → 各サイズで容量を再確認。28 px で透過のミスが一番はっきり出ます。

この検査を組み込んだ生成ツールが EmoteLoop です(自撮りか一文から、透過・ループの512px GIFを出力)。Twitchとは提携・承認関係にありません。

1
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?