"""
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)")