topfans/backend/services/laserCompositor/loader/alpha_extract.go
2026-06-03 22:19:22 +08:00

40 lines
954 B
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package loader
import (
"image"
"image/color"
)
// ExtractAlpha 将白色/浅灰背景转换为透明,保留非白色像素
// 用于处理 AI 生成的装饰图MiniMax 可能不输出透明 PNG
func ExtractAlpha(img image.Image) *image.NRGBA {
bounds := img.Bounds()
result := image.NewNRGBA(bounds)
for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
for x := bounds.Min.X; x < bounds.Max.X; x++ {
r, g, b, a := img.At(x, y).RGBA()
// 将 uint32 (0-65535) 归一化到 0-1
rf := float64(r) / 65535.0
gf := float64(g) / 65535.0
bf := float64(b) / 65535.0
// 亮度 > 90% 的视为白色/浅灰背景,设为透明
luminance := (rf + gf + bf) / 3.0
if luminance > 0.90 {
result.SetNRGBA(x, y, color.NRGBA{R: 0, G: 0, B: 0, A: 0})
} else {
result.SetNRGBA(x, y, color.NRGBA{
R: uint8(r >> 8),
G: uint8(g >> 8),
B: uint8(b >> 8),
A: uint8(a >> 8),
})
}
}
}
return result
}