2026年11月24日 星期二

AI神器(AGY CLI)採開放源碼套件,免費生成GIF動畫圖檔

一張可愛的靜態角色圖變成生動的「揮手打招呼 GIF」,直覺往往是丟給生成式 AI(如 Stable Video Diffusion)去算。但實戰上你一定遇過兩大痛點:第一是沒有高階獨立顯卡根本跑不動,第二是 AI 每一幀重繪容易讓角色五官走樣、頭髮亂飄!

其實,只要改用經典的「2D 紙娃娃拆解、背景修補(Inpainting)與關節驅動傳輸線」,純靠 CPU 就能在 0.5 秒內精準驅動手腕揮動,且角色臉部與背景 100% 零變形!

👉 PYTHON核心元件「OpenCV + NumPy + Pillow」全自動動圖管線的底層架構、關鍵程式碼對位。

一、 全景架構圖:2D 紙娃娃拆解與關節驅動傳輸線

這套系統的核心精神是「把會動的手掌剪成透明零件,把被遮住的背景頭髮無痕補齊,最後用三角函數節拍器帶動關節旋轉」。整體信號流如下:

[原始角色圖 chibi_wave_source.jpg]
   ├── 路徑 A(前景零件萃取):ROI 區域鎖定 ──> 膚色閾值篩選 ──> 形態學閉合/膨脹 ──> [透明背景手部零件 hand_rgba]
   └── 路徑 B(背景無痕補洞):手部遮罩擴大 ──> Telea 影像修補 (Inpainting) ────────> [無手部遮擋的完整背景 bg_inpainted]
                                                                                              │
[正弦波節拍器 math.sin] ──> 算出揮手角度 (wave_deg) ──> 繞手腕軸心旋轉手部零件 ──────────────┴──> [圖層 alpha 混合合成]
                                                                                                         │
[呼吸律動產生器] ──> 網格座標重映射 (cv2.remap 邊緣鎖死) ──> [疊加閃亮星星特效] ──> [中位切分 256 色量化] ──> [chibi_wave.gif]

二、 四大核心工程直覺拆解

1. 為什麼要先「背景補洞(Inpainting)」?(解決穿幫難題)

如果直接把原圖的手剪下來旋轉,手揮開之後,原本被手掌遮住的「棕色頭髮」會變成一個白色大破洞!因此程式先用 cv2.inpaint(Telea 演算法)像修圖軟體的「內容感知填補」一樣,把被手遮住的頭髮紋理自動推演補齊,確保手怎麼揮都不會穿幫。

2. 形態學操作(Morphology:閉運算與膨脹)的物理意義

單靠膚色範圍(r > 205...)抓出來的手掌內部會有反光小孔洞,且不包含「深棕色的手部輪廓線」。程式先用 MORPH_CLOSE(閉運算)填平掌心內部孔洞,再用 dilate(膨脹)往外擴張一圈,精準把深色外框線一起包進手部圖層裡。

3. 邊緣鎖死的呼吸律動(cv2.remap + interior 衰減遮罩)

若整張圖直接上下移動,GIF 四周白邊會出現黑線或撕裂。程式設計了一個「越靠近四個邊界、位移量衰減為 0」的平滑阻尼遮罩(interior),讓角色身體中心跟著呼吸微微起伏搖擺,但最外圍 7 像素的邊框死死釘在原地不動。

4. 雙倍頻正弦波節拍器(Double-Wave Oscillator)

一般單週期正弦波一個循環只揮一次手;程式在 wave_deg 中乘上 2.0(2.0 * math.pi * 2.0 * t),讓角色在一次呼吸起伏(t 從 0 到 1)的期間,手腕輕快地來回揮動兩次,呈現活潑的打招呼節奏。

三、 關鍵代碼與工程物理本質對位表

階段步驟 核心程式碼 工程與物理本質 一句話白話直覺
1. 座標比例正規化 sx, sy = w / 296.0, h / 297.0 解析度無關的相對座標映射(Resolution Independence) 不管輸入圖片被放大或縮小,自動按比例換算手掌與手腕的精準座標位置。
2. 膚色與連通域過濾 connectedComponentsWithStats 連通分量標記與面積閾值雜訊濾波 抓出指定區域內的膚色色塊,並把面積太小的零星雜點踢掉,只留下真正的手掌。
3. 邊緣羽化去鋸齒 cv2.GaussianBlur(hand_mask, (3, 3), 0.7) Alpha 透明通道低通濾波抗鋸齒(Anti-Aliasing) 把手部剪貼邊緣微微模糊柔化,讓手掌疊回背景時邊緣自然融合、沒有狗牙鋸齒。
4. 關節仿射旋轉 cv2.getRotationMatrix2D(wrist_pivot, ...)
cv2.warpAffine(...)
2D 剛體繞固定樞紐點之仿射變換(Affine Transformation) 用一根圖釘釘住「手腕軸心」,只讓手掌零件左右擺動,袖口位置完全不動。
5. 色彩量化與抖動 composed.quantize(colors=256, method=MEDIANCUT, dither=FLOYDSTEINBERG) 色彩空間體積中位切分聚類與誤差擴散演算法 把數百萬種全彩顏色濃縮成 256 色,並用細微點陣擴散消除色階斷層。

四、 逐行解構與「順序反轉因果」反事實推導

  • 袖口切割線(wrist_cut_y = int(232 * sy); hand_mask[wrist_cut_y:, :] = 0):在手腕袖口交界處一刀切斷遮罩,確保粉紅色連帽衫袖子留在靜態背景圖層,不會跟著手掌一起歪斜旋轉。
  • 標準 Alpha 混色(rot_hand[:, :, :3] * alpha_f + bg_inpainted * (1.0 - alpha_f)):Porter-Duff 混色公式。透明通道為 1 的地方顯示旋轉後的手,為 0 的地方顯示補好頭髮的背景,介於中間的羽化邊緣則做線性平滑過渡。

⚠️ 順序反轉災難推演(Counterfactual Inversion):

1. 若省略 inpaint_mask = cv2.dilate(hand_mask, ...),直接用未膨脹遮罩修補:手部邊緣的半透明深色外框會殘留在原圖背景上,導致手揮動時,背景印著一圈「幽靈手掌殘影」。

2. 若先執行全身呼吸晃動,再把旋轉後的手貼上去:身體與手腕已經跟著呼吸位移,手部圖層卻還釘在舊的 wrist_pivot 座標上,會導致手掌與袖口當場脫節分離!因此必須「先合體、再呼吸」。

五、 電腦視覺注意事項與優化調校

  1. 色彩通道順序陷阱(OpenCV BGR vs PIL/NumPy RGB):Image.open().convert("RGB") 讀入的是 RGB,但 cv2.inpaint() 內部針對 BGR 優化,因此必須先轉 RGB2BGR 再轉回 BGR2RGB。漏掉轉換會讓角色膚色變成阿凡達藍色!
  2. 幾何變換插值法選擇(Interpolation):cv2.INTER_CUBIC(雙三次插值)參考周圍 4×4 個像素,比最近鄰(INTER_NEAREST)與雙線性(INTER_LINEAR)更能保留二次元動漫線條的銳利與平滑度。
  3. 形態學「閉運算(Closing)」vs「開運算(Opening)」:先膨脹後侵蝕 = 閉運算(MORPH_CLOSE),專治物體內部的小黑洞與斷裂;先侵蝕後膨脹 = 開運算(MORPH_OPEN),專治背景上的孤立小白點雜訊。
  4. 優化調校
  •  手部前景獨立去背(RGBA Sprite):僅擷取手掌、五指與外框黑線成為獨立透明前景圖層。
  • 手後背景髮絲修補(cv2.INPAINT_TELEA):將手掌原本遮擋處的棕色長髮自動補全為靜止背景層。
  • 獨立分層旋轉合成:每一幀僅旋轉手部前景圖層(以手腕為軸心±12°),再疊加回靜止的髮絲背景上,因此揮手時手背後的頭髮完全不會跟著拉扯或晃動,右耳亦完全不受影響。

六、 張量陣列維度演進

  • base_np:shape=(H, W, 3),dtype=uint8(3 通道 RGB 原始影像)。
  • hand_mask:shape=(H, W),dtype=uint8(單通道二值化遮罩,僅含 0 與 255)。
  • hand_rgba:shape=(H, W, 4),dtype=uint8(透過 np.dstack 堆疊為 4 通道 RGBA 精靈圖)。
  • alpha_f:shape=(H, W, 1),dtype=float32(切片 [:, :, 3:4] 保留維度並正規化至 [0.0, 1.0],觸發廣播機制)。
  • quantized:PIL.Image(模式 P,調色盤索引模式,每像素僅佔 1 Byte)。

💡 總結

  1. 生成式 AI(擴散管線 (Diffusers + FFmpeg)) 吃顯存且容易畫崩五官;本次作法採傳統視覺紙娃娃管線 (OpenCV + NumPy + PIL)拆解則是秒殺級運算且 100% 零變形。
  2. 拆圖兩手抓:前景抓膚色加閉運算剪出「透明手掌」,背景用 Telea 修補填平「頭髮破洞」。
  3. 先合體再呼吸:手掌先繞手腕旋轉並貼回身體,最後才用邊界鎖死的 remap 做全身呼吸起伏,保證手腕不斷裂。
  4. 內建壓縮術:無需外部工具,直接用 Pillow 的中位切分法搭配誤差擴散抖動輸出輕量無斷層 GIF。

"""
Generate an animated waving GIF from the chibi character image.
Uses true two-layer foreground/background separation:
  1. Segments the waving hand (palm + fingers + dark outline) into an RGBA sprite.
  2. Inpaints the static brown hair behind the hand (cv2.INPAINT_TELEA) so the hair
     NEVER wobbles or stretches with the waving hand.
  3. Rotates ONLY the foreground hand layer around the wrist pivot and alpha-composites
     it over the background, plus subtle breathing bob and twinkling sparkles.
"""

import math
import os
import shutil
import cv2
import numpy as np
from PIL import Image, ImageDraw


BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DEFAULT_UPLOADED = (
    r"C:\Users\username\.gemini\antigravity-cli\brain"
    r"\ff49392a-1ed7-4e41-af72-a8663610fe5d\.user_uploaded"
    r"\uploaded_media_1795435385706.jpg"
)
SOURCE_IMAGE = os.path.join(BASE_DIR, "chibi_wave_source.jpg")
OUTPUT_GIF = os.path.join(BASE_DIR, "chibi_wave.gif")


def ensure_source_image() -> str:
    if not os.path.exists(SOURCE_IMAGE):
        if os.path.exists(DEFAULT_UPLOADED):
            shutil.copy2(DEFAULT_UPLOADED, SOURCE_IMAGE)
        else:
            raise FileNotFoundError(f"Source image not found: {SOURCE_IMAGE}")
    return SOURCE_IMAGE


def separate_hand_and_background(img_rgb: np.ndarray):
    """
    Separate the waving hand into a crisp RGBA sprite and inpaint the hair behind it.
    Returns (bg_inpainted_rgb, hand_rgba, wrist_pivot_xy).
    """
    h, w = img_rgb.shape[:2]
    sx, sy = w / 296.0, h / 297.0

    # 1. Restrict search strictly to the hand region (well below the right ear y <= 158)
    roi = np.zeros((h, w), dtype=np.uint8)
    roi[int(172 * sy) : int(236 * sy), int(24 * sx) : int(92 * sx)] = 255

    # 2. Segment warm peach skin pixels inside ROI (excludes white bg, brown hair, pink hoodie)
    r = img_rgb[:, :, 0].astype(np.int16)
    g = img_rgb[:, :, 1].astype(np.int16)
    b = img_rgb[:, :, 2].astype(np.int16)
    skin = (
        (r > 205)
        & (g > 165)
        & (b > 130)
        & ((r - b) > 18)
        & ((r - g) < 55)
    ).astype(np.uint8) * 255
    skin = cv2.bitwise_and(skin, roi)

    # Keep only meaningful skin components (hand palm + fingers)
    num_labels, labels, stats, _ = cv2.connectedComponentsWithStats(skin, connectivity=8)
    hand_skin = np.zeros((h, w), dtype=np.uint8)
    for lbl in range(1, num_labels):
        if stats[lbl, cv2.CC_STAT_AREA] >= int(35 * sx * sy):
            hand_skin[labels == lbl] = 255

    # Fill tiny interior holes and dilate tightly to capture the dark brown finger outline
    hand_skin = cv2.morphologyEx(
        hand_skin,
        cv2.MORPH_CLOSE,
        cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)),
    )
    hand_mask = cv2.dilate(
        hand_skin,
        cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)),
        iterations=1,
    )

    # Trim cleanly at the wrist cuff line so the pink sleeve stays anchored
    wrist_cut_y = int(232 * sy)
    hand_mask[wrist_cut_y:, :] = 0

    # 3. Inpaint the background hair behind the hand
    inpaint_mask = cv2.dilate(
        hand_mask,
        cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)),
        iterations=1,
    )
    bg_bgr = cv2.inpaint(
        cv2.cvtColor(img_rgb, cv2.COLOR_RGB2BGR),
        inpaint_mask,
        inpaintRadius=7,
        flags=cv2.INPAINT_TELEA,
    )
    bg_inpainted = cv2.cvtColor(bg_bgr, cv2.COLOR_BGR2RGB)

    # 4. Anti-aliased alpha channel for the hand sprite
    alpha = cv2.GaussianBlur(hand_mask.astype(np.float32), (3, 3), 0.7)
    alpha = np.clip(alpha, 0.0, 255.0).astype(np.uint8)
    hand_rgba = np.dstack([img_rgb, alpha])

    wrist_pivot = (62.0 * sx, 231.0 * sy)
    return bg_inpainted, hand_rgba, wrist_pivot


def apply_gentle_bob(img_rgb: np.ndarray, bob_y: float, sway_deg: float) -> np.ndarray:
    """Apply subtle whole-character breathing bob while keeping outer border static."""
    h, w = img_rgb.shape[:2]
    yy, xx = np.mgrid[0:h, 0:w].astype(np.float32)

    cx_g, cy_g = w * 0.50, h * 0.94
    rad_g = math.radians(-sway_deg)
    cos_g, sin_g = math.cos(rad_g), math.sin(rad_g)
    dx_g = xx - cx_g
    dy_g = (yy - bob_y) - cy_g
    map_x = cx_g + dx_g * cos_g - dy_g * sin_g
    map_y = cy_g + dx_g * sin_g + dy_g * cos_g

    border = 7.0
    mask_x = np.clip(np.minimum(xx - border, (w - 1 - border) - xx) / 10.0, 0.0, 1.0)
    mask_y = np.clip(np.minimum(yy - border, (h - 1 - border) - yy) / 10.0, 0.0, 1.0)
    interior = mask_x * mask_y

    map_x = xx + (map_x - xx) * interior
    map_y = yy + (map_y - yy) * interior

    return cv2.remap(
        img_rgb,
        map_x.astype(np.float32),
        map_y.astype(np.float32),
        interpolation=cv2.INTER_CUBIC,
        borderMode=cv2.BORDER_REPLICATE,
    )


def draw_sparkle(draw: ImageDraw.ImageDraw, cx: float, cy: float, size: float, color: tuple):
    """Draw a cute 4-point star sparkle."""
    if size <= 1.0:
        return
    r_outer = size
    r_inner = size * 0.28
    pts = []
    for i in range(8):
        angle = i * math.pi / 4.0
        r = r_outer if i % 2 == 0 else r_inner
        pts.append((cx + r * math.cos(angle), cy + r * math.sin(angle)))
    draw.polygon(pts, fill=color)


def generate_gif(num_frames: int = 24, duration_ms: int = 65) -> str:
    src_path = ensure_source_image()
    base_pil = Image.open(src_path).convert("RGB")
    base_np = np.array(base_pil)
    w, h = base_pil.size

    bg_inpainted, hand_rgba, wrist_pivot = separate_hand_and_background(base_np)

    frames = []
    sparkles = [
        (w * 0.11, h * 0.36, 0.0, (255, 165, 185, 220)),
        (w * 0.13, h * 0.55, 0.33, (255, 205, 110, 220)),
        (w * 0.87, h * 0.16, 0.55, (255, 190, 120, 220)),
        (w * 0.89, h * 0.34, 0.78, (255, 155, 175, 200)),
    ]

    for i in range(num_frames):
        t = i / num_frames
        # Double wave per loop for lively greeting feel
        wave_deg = 12.0 * math.sin(2.0 * math.pi * 2.0 * t)
        # Subtle breathing bob & tiny head sway (applied cleanly to whole character)
        bob_y = -1.8 * math.sin(2.0 * math.pi * t)
        sway_deg = 1.0 * math.sin(2.0 * math.pi * t)

        # Rotate ONLY the isolated hand sprite around the wrist pivot
        rot_mat = cv2.getRotationMatrix2D(wrist_pivot, wave_deg, 1.0)
        rot_hand = cv2.warpAffine(
            hand_rgba,
            rot_mat,
            (w, h),
            flags=cv2.INTER_CUBIC,
            borderMode=cv2.BORDER_CONSTANT,
            borderValue=(0, 0, 0, 0),
        )

        # Composite rotated hand onto static inpainted background (hair never wobbles!)
        alpha_f = (rot_hand[:, :, 3:4].astype(np.float32)) / 255.0
        comp_rgb = (
            rot_hand[:, :, :3].astype(np.float32) * alpha_f
            + bg_inpainted.astype(np.float32) * (1.0 - alpha_f)
        ).clip(0, 255).astype(np.uint8)

        # Apply subtle global breathing bob
        frame_rgb = apply_gentle_bob(comp_rgb, bob_y, sway_deg)
        frame_rgba = Image.fromarray(frame_rgb).convert("RGBA")

        # Overlay twinkling sparkles
        overlay = Image.new("RGBA", (w, h), (0, 0, 0, 0))
        draw = ImageDraw.Draw(overlay)
        for sx, sy, phase, rgba in sparkles:
            pulse = 0.5 + 0.5 * math.sin(2.0 * math.pi * (t + phase))
            star_size = 2.0 + 6.5 * (pulse ** 1.6)
            a = int(rgba[3] * (0.25 + 0.75 * pulse))
            draw_sparkle(draw, sx, sy + bob_y * 0.6, star_size, (rgba[0], rgba[1], rgba[2], a))

        composed = Image.alpha_composite(frame_rgba, overlay).convert("RGB")
        quantized = composed.quantize(
            colors=256,
            method=Image.Quantize.MEDIANCUT,
            dither=Image.Dither.FLOYDSTEINBERG,
        )
        frames.append(quantized)

    frames[0].save(
        OUTPUT_GIF,
        save_all=True,
        append_images=frames[1:],
        duration=duration_ms,
        loop=0,
        optimize=True,
    )
    return OUTPUT_GIF


if __name__ == "__main__":
    out = generate_gif()
    size_kb = os.path.getsize(out) / 1024.0
    print(f"GIF_GENERATED_OK: {out} ({size_kb:.1f} KB)")