feat: 投影法波谷检测+白底硬切断+帧底部对齐+gifmaker透明GIF
- prompt_agent: 精灵表/瓦片集间隙从2-4px放宽到8-16px纯白 - splitsprite removeWhiteBg: dist<threshold/2直接A=0,消除半透明残留 - splitsprite findCuts: 波峰-波谷检测替代死阈值,归并原阈值回退 - splitsprite alignCenter: 全局画布底部对齐替代独立居中,人物不跳帧 - splitsprite MinFillRatio 调至0.14,MinGapWidth调至2 - 新增 pkg/gifmaker: 统一画布+透明索引0+DisposalBackground - test_prompt_to_gif 改用gifmaker包
This commit is contained in:
@@ -0,0 +1,128 @@
|
||||
// Package gifmaker encodes sprite animation frames into a GIF preview.
|
||||
//
|
||||
// Features:
|
||||
// - Unified canvas: all frames normalized to the same dimensions
|
||||
// - Transparent background: palette index 0 = fully transparent
|
||||
// - DisposalBackground: each frame clears the previous one, no ghosting
|
||||
//
|
||||
// Pipeline integration:
|
||||
//
|
||||
// frames, _ := splitsprite.Process(img, splitsprite.DefaultOptions())
|
||||
// gifmaker.Save("preview.gif", frames, nil)
|
||||
package gifmaker
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/gif"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
// Options configures GIF generation.
|
||||
type Options struct {
|
||||
// Delay is the frame delay in 1/100s (default 10).
|
||||
Delay int
|
||||
// MaxColors is the maximum palette size (default 256).
|
||||
MaxColors int
|
||||
}
|
||||
|
||||
// DefaultOptions returns sensible defaults.
|
||||
func DefaultOptions() *Options {
|
||||
return &Options{
|
||||
Delay: 10,
|
||||
MaxColors: 256,
|
||||
}
|
||||
}
|
||||
|
||||
// Save is a convenience wrapper that writes frames to a GIF file.
|
||||
func Save(path string, frames []image.Image, opts *Options) error {
|
||||
f, err := os.Create(path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create gif file: %w", err)
|
||||
}
|
||||
defer f.Close()
|
||||
return Encode(f, frames, opts)
|
||||
}
|
||||
|
||||
// Encode writes an animated GIF to w. All frames are normalized to a unified
|
||||
// canvas (max width/height across frames), the palette starts with a
|
||||
// transparent color, and DisposalBackground prevents inter-frame ghosting.
|
||||
func Encode(w io.Writer, frames []image.Image, opts *Options) error {
|
||||
if len(frames) == 0 {
|
||||
return fmt.Errorf("no frames to encode")
|
||||
}
|
||||
if opts == nil {
|
||||
opts = DefaultOptions()
|
||||
}
|
||||
delay := opts.Delay
|
||||
if delay <= 0 {
|
||||
delay = 10
|
||||
}
|
||||
maxColors := opts.MaxColors
|
||||
if maxColors <= 0 || maxColors > 256 {
|
||||
maxColors = 256
|
||||
}
|
||||
|
||||
// Unified canvas
|
||||
maxW, maxH := 0, 0
|
||||
for _, f := range frames {
|
||||
b := f.Bounds()
|
||||
if b.Dx() > maxW {
|
||||
maxW = b.Dx()
|
||||
}
|
||||
if b.Dy() > maxH {
|
||||
maxH = b.Dy()
|
||||
}
|
||||
}
|
||||
|
||||
// Palette with transparent at index 0
|
||||
pal := color.Palette{color.RGBA{0, 0, 0, 0}}
|
||||
seen := make(map[color.RGBA]bool)
|
||||
for _, fr := range frames {
|
||||
b := fr.Bounds()
|
||||
for y := b.Min.Y; y < b.Max.Y; y += 3 {
|
||||
for x := b.Min.X; x < b.Max.X; x += 3 {
|
||||
r, g, bl, a := fr.At(x, y).RGBA()
|
||||
c := color.RGBA{uint8(r >> 8), uint8(g >> 8), uint8(bl >> 8), uint8(a >> 8)}
|
||||
if !seen[c] && len(pal) < maxColors-1 {
|
||||
seen[c] = true
|
||||
pal = append(pal, c)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
anim := &gif.GIF{
|
||||
Config: image.Config{Width: maxW, Height: maxH},
|
||||
}
|
||||
|
||||
for _, frame := range frames {
|
||||
pl := image.NewPaletted(image.Rect(0, 0, maxW, maxH), pal)
|
||||
// Manually map pixels: transparent → index 0, colored → nearest palette
|
||||
b := frame.Bounds()
|
||||
for y := 0; y < maxH; y++ {
|
||||
for x := 0; x < maxW; x++ {
|
||||
sx := x + b.Min.X
|
||||
sy := y + b.Min.Y
|
||||
if sx < b.Max.X && sy < b.Max.Y {
|
||||
r, g, bl, a := frame.At(sx, sy).RGBA()
|
||||
if a > 0 {
|
||||
c := color.RGBA{uint8(r >> 8), uint8(g >> 8), uint8(bl >> 8), uint8(a >> 8)}
|
||||
pl.Set(x, y, c)
|
||||
}
|
||||
// else: stays at index 0 (transparent)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
anim.Image = append(anim.Image, pl)
|
||||
anim.Delay = append(anim.Delay, delay)
|
||||
anim.Disposal = append(anim.Disposal, gif.DisposalBackground)
|
||||
}
|
||||
|
||||
anim.LoopCount = 0
|
||||
anim.BackgroundIndex = 0
|
||||
return gif.EncodeAll(w, anim)
|
||||
}
|
||||
@@ -58,8 +58,9 @@ func DefaultOptions() *Options {
|
||||
WhiteThreshold: 40,
|
||||
GapThreshold: 0.03,
|
||||
MinGapWidth: 2,
|
||||
MinFillRatio: 0.3,
|
||||
MinFillRatio: 0.14,
|
||||
Trim: true,
|
||||
CenterAlign: true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,8 +71,9 @@ func DefaultGreenOptions() *Options {
|
||||
GreenTolerance: 0.2,
|
||||
GapThreshold: 0.03,
|
||||
MinGapWidth: 2,
|
||||
MinFillRatio: 0.3,
|
||||
MinFillRatio: 0.14,
|
||||
Trim: true,
|
||||
CenterAlign: true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -133,14 +135,15 @@ func CenterFrames(frames []image.Image) []image.Image {
|
||||
return alignCenter(frames)
|
||||
}
|
||||
|
||||
// alignCenter finds the content bounding box per frame, computes the max
|
||||
// dimensions, then pads each frame so content is centered uniformly.
|
||||
// alignCenter aligns all frames to a uniform canvas with a fixed reference point.
|
||||
// Uses bottom-center alignment so characters share a common ground plane across frames,
|
||||
// preventing drift/jitter in animation playback.
|
||||
func alignCenter(frames []image.Image) []image.Image {
|
||||
type contentBox struct {
|
||||
minX, minY, maxX, maxY int
|
||||
}
|
||||
boxes := make([]contentBox, len(frames))
|
||||
maxW, maxH := 0, 0
|
||||
maxCW, maxCH := 0, 0
|
||||
|
||||
for i, f := range frames {
|
||||
b := f.Bounds()
|
||||
@@ -172,29 +175,32 @@ func alignCenter(frames []image.Image) []image.Image {
|
||||
} else {
|
||||
boxes[i] = contentBox{minX, minY, maxX, maxY}
|
||||
}
|
||||
w := boxes[i].maxX - boxes[i].minX + 1
|
||||
h := boxes[i].maxY - boxes[i].minY + 1
|
||||
if w > maxW {
|
||||
maxW = w
|
||||
cw := boxes[i].maxX - boxes[i].minX + 1
|
||||
ch := boxes[i].maxY - boxes[i].minY + 1
|
||||
if cw > maxCW {
|
||||
maxCW = cw
|
||||
}
|
||||
if h > maxH {
|
||||
maxH = h
|
||||
if ch > maxCH {
|
||||
maxCH = ch
|
||||
}
|
||||
}
|
||||
|
||||
// Pad by 10% to avoid edge cropping
|
||||
maxW = maxW * 11 / 10
|
||||
maxH = maxH * 11 / 10
|
||||
// Uniform canvas with 10% padding
|
||||
canvasW := maxCW * 11 / 10
|
||||
canvasH := maxCH * 11 / 10
|
||||
// Fixed X center reference: anchor all frames to the same horizontal center
|
||||
fixedCenterX := canvasW / 2
|
||||
|
||||
out := make([]image.Image, len(frames))
|
||||
for i, f := range frames {
|
||||
cb := boxes[i]
|
||||
cw := cb.maxX - cb.minX + 1
|
||||
ch := cb.maxY - cb.minY + 1
|
||||
ox := (maxW - cw) / 2
|
||||
oy := (maxH - ch) / 2
|
||||
// All frames share the same center-X and bottom-Y anchor
|
||||
ox := fixedCenterX - cw/2 // consistent horizontal center
|
||||
oy := canvasH - ch // bottom-align: feet planted at same Y
|
||||
|
||||
canvas := image.NewRGBA(image.Rect(0, 0, maxW, maxH))
|
||||
canvas := image.NewRGBA(image.Rect(0, 0, canvasW, canvasH))
|
||||
draw.Draw(canvas,
|
||||
image.Rect(ox, oy, ox+cw, oy+ch),
|
||||
f,
|
||||
@@ -229,7 +235,7 @@ type tile struct {
|
||||
x, y, w, h int
|
||||
}
|
||||
|
||||
// removeWhiteBg removes pixels close to pure white (R,G,B all above threshold).
|
||||
// removeWhiteBg removes pixels close to pure white (R,G,B all within threshold of 255).
|
||||
func removeWhiteBg(rgba *image.RGBA, threshold uint8) *image.RGBA {
|
||||
if threshold == 0 {
|
||||
threshold = 40
|
||||
@@ -245,11 +251,14 @@ func removeWhiteBg(rgba *image.RGBA, threshold uint8) *image.RGBA {
|
||||
continue
|
||||
}
|
||||
r8, g8, b8 := uint8(r>>8), uint8(g>>8), uint8(bl>>8)
|
||||
// Pixel is "white" when all channels are near 255
|
||||
if int(255-r8) < int(threshold) && int(255-g8) < int(threshold) && int(255-b8) < int(threshold) {
|
||||
// Calculate alpha: closer to white = more transparent
|
||||
dist := max(int(255-r8), max(int(255-g8), int(255-b8)))
|
||||
alpha := float64(dist) / float64(threshold)
|
||||
// Distance from pure white
|
||||
dist := max(int(255-r8), max(int(255-g8), int(255-b8)))
|
||||
if dist < int(threshold)/2 {
|
||||
// Very close to white — fully transparent
|
||||
dst.SetRGBA(x, y, color.RGBA{R: r8, G: g8, B: b8, A: 0})
|
||||
} else if dist < int(threshold) {
|
||||
// Semi-white — fade alpha
|
||||
alpha := float64(dist-int(threshold)/2) / float64(int(threshold)/2)
|
||||
dst.SetRGBA(x, y, color.RGBA{R: r8, G: g8, B: b8, A: uint8(alpha * 255)})
|
||||
}
|
||||
}
|
||||
@@ -378,6 +387,90 @@ func tileFillRatio(rgba *image.RGBA, x0, y0, w, h int) float64 {
|
||||
}
|
||||
|
||||
func findCuts(ratios []float64, threshold float64, minGap int) []int {
|
||||
n := len(ratios)
|
||||
if n == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Smooth the ratio curve with a moving average (kernel size = minGap)
|
||||
smoothed := make([]float64, n)
|
||||
kernel := max(minGap, 3)
|
||||
for i := 0; i < n; i++ {
|
||||
sum := 0.0
|
||||
count := 0
|
||||
for j := max(0, i-kernel/2); j < min(n, i+kernel/2+1); j++ {
|
||||
sum += ratios[j]
|
||||
count++
|
||||
}
|
||||
if count > 0 {
|
||||
smoothed[i] = sum / float64(count)
|
||||
}
|
||||
}
|
||||
|
||||
// Compute mean to use as reference
|
||||
mean := 0.0
|
||||
for _, r := range smoothed {
|
||||
mean += r
|
||||
}
|
||||
mean /= float64(n)
|
||||
|
||||
// Find peaks: contiguous regions where smoothed ratio > mean*1.2
|
||||
type segment struct{ start, end int }
|
||||
var peaks []segment
|
||||
i := 0
|
||||
for i < n {
|
||||
if smoothed[i] > mean*1.2 {
|
||||
start := i
|
||||
for i < n && smoothed[i] > mean*0.8 {
|
||||
i++
|
||||
}
|
||||
peaks = append(peaks, segment{start, i})
|
||||
} else {
|
||||
i++
|
||||
}
|
||||
}
|
||||
|
||||
if len(peaks) < 2 {
|
||||
// Fallback: use threshold-based gap detection
|
||||
return findCutsByGap(ratios, threshold, minGap)
|
||||
}
|
||||
|
||||
// Find valleys between adjacent peaks (minimum smoothed ratio between them)
|
||||
cuts := []int{0}
|
||||
for p := 0; p < len(peaks)-1; p++ {
|
||||
valleyStart := peaks[p].end
|
||||
valleyEnd := peaks[p+1].start
|
||||
if valleyStart >= valleyEnd {
|
||||
// Peaks adjacent — cut at midpoint
|
||||
cuts = append(cuts, (peaks[p].end+peaks[p+1].start)/2)
|
||||
continue
|
||||
}
|
||||
// Find minimum in the valley region
|
||||
minIdx := valleyStart
|
||||
minVal := smoothed[valleyStart]
|
||||
for j := valleyStart + 1; j < valleyEnd; j++ {
|
||||
if smoothed[j] < minVal {
|
||||
minVal = smoothed[j]
|
||||
minIdx = j
|
||||
}
|
||||
}
|
||||
cuts = append(cuts, minIdx)
|
||||
}
|
||||
cuts = append(cuts, n)
|
||||
sort.Ints(cuts)
|
||||
|
||||
// Deduplicate
|
||||
dedup := cuts[:1]
|
||||
for j := 1; j < len(cuts); j++ {
|
||||
if cuts[j] != dedup[len(dedup)-1] {
|
||||
dedup = append(dedup, cuts[j])
|
||||
}
|
||||
}
|
||||
return dedup
|
||||
}
|
||||
|
||||
// findCutsByGap is the original threshold-based fallback.
|
||||
func findCutsByGap(ratios []float64, threshold float64, minGap int) []int {
|
||||
n := len(ratios)
|
||||
isGap := make([]bool, n)
|
||||
for i, r := range ratios {
|
||||
|
||||
Reference in New Issue
Block a user