vision/vision_test.go

129 lines
2.7 KiB
Go
Raw Permalink Normal View History

package vision
import (
"image"
"os"
"testing"
)
func TestCanvas(t *testing.T) {
c := New(200, 200, "#FFFFFF")
c.SetColor("#FF0000")
c.Rect(10, 10, 100, 100, &DrawStyle{
FillColor: "#00FF00",
StrokeColor: "#0000FF",
StrokeWidth: 2,
})
err := Save(c, "test.png")
if err != nil {
t.Fatalf("save failed: %v", err)
}
defer os.Remove("test.png")
}
func TestCaptcha(t *testing.T) {
c := GenerateCaptcha(&CaptchaOption{
Length: 6,
Width: 200,
Height: 60,
})
err := Save(c, "captcha.png")
if err != nil {
t.Fatalf("save captcha failed: %v", err)
}
defer os.Remove("captcha.png")
}
func TestColorPalette(t *testing.T) {
c := New(100, 100, "#FF0000")
c.Rect(0, 0, 50, 100, &DrawStyle{FillColor: "#00FF00"})
palette := c.ExtractPalette(5)
if len(palette) < 2 {
t.Errorf("expected at least 2 colors, got %d", len(palette))
}
t.Logf("palette: %+v", palette)
}
func TestPHash(t *testing.T) {
c1 := New(100, 100, "#FFFFFF")
c1.Circle(50, 50, 30, &DrawStyle{FillColor: "#000000"})
c2 := New(100, 100, "#FFFFFF")
c2.Circle(52, 52, 30, &DrawStyle{FillColor: "#000000"}) // 稍微偏移
h1 := PHash(c1.Image())
h2 := PHash(c2.Image())
dist := Distance(h1, h2)
if dist > 5 {
t.Errorf("expected small distance for similar images, got %d", dist)
}
t.Logf("pHash distance: %d", dist)
}
func TestQRCode(t *testing.T) {
content := "https://apigo.cc"
c, err := GenerateQRCode(content, 200)
if err != nil {
t.Fatalf("generate qrcode failed: %v", err)
}
decoded, err := c.DecodeQRCode()
if err != nil {
t.Fatalf("decode qrcode failed: %v", err)
}
if decoded != content {
t.Errorf("expected %s, got %s", content, decoded)
}
}
func TestBarcode(t *testing.T) {
content := "12345678"
c, err := GenerateBarcode(content, 200, 50)
if err != nil {
t.Fatalf("generate barcode failed: %v", err)
}
decoded, err := c.DecodeBarcode()
if err != nil {
t.Fatalf("decode barcode failed: %v", err)
}
if decoded != content {
t.Errorf("expected %s, got %s", content, decoded)
}
}
func BenchmarkWarpPerspective(b *testing.B) {
c := New(1000, 1000, "#FFFFFF")
c.Circle(500, 500, 300, &DrawStyle{FillColor: "#FF0000"})
srcPoints := [4]image.Point{
{100, 100}, {900, 150}, {850, 850}, {150, 800},
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
c.WarpPerspective(srcPoints, 500, 500)
}
}
func BenchmarkPHash(b *testing.B) {
c := New(500, 500, "#FFFFFF")
c.Circle(250, 250, 100, &DrawStyle{FillColor: "#000000"})
img := c.Image()
b.ResetTimer()
for i := 0; i < b.N; i++ {
PHash(img)
}
}
func BenchmarkExtractPalette(b *testing.B) {
c := New(500, 500, "#FFFFFF")
c.RandBG(5)
b.ResetTimer()
for i := 0; i < b.N; i++ {
c.ExtractPalette(10)
}
}