// TestMean tests the mean quantizer on png files found in the source // directory. Output files are prefixed with _mean_. Files begining with // _ are skipped when scanning for input files. Note nothing is tested // with a fresh source tree--drop a png or two in the source directory // before testing to give the test something to work on. Png files in the // parent directory are similarly used for testing. Put files there // to compare results of the different quantizers. func TestMean(t *testing.T) { for _, p := range glob(t) { f, err := os.Open(p) if err != nil { t.Log(err) // skip files that can't be opened continue } img, err := png.Decode(f) f.Close() if err != nil { t.Log(err) // skip files that can't be decoded continue } pDir, pFile := filepath.Split(p) for _, n := range []int{16, 256} { // prefix _ on file name marks this as a result fq, err := os.Create(fmt.Sprintf("%s_mean_%d_%s", pDir, n, pFile)) if err != nil { t.Fatal(err) // probably can't create any others } var q quant.Quantizer = mean.Quantizer(n) if err = png.Encode(fq, q.Image(img)); err != nil { t.Fatal(err) // any problem is probably a problem for all } } } }
func main() { mode := flag.String("mode", "median", "'median' or 'mean' (default 'median')") size := flag.Int("size", 16, "Palette size (default 16)") flag.Parse() paths := flag.Args() if len(paths) == 0 { log.Fatal("No images specified") } var wg sync.WaitGroup wg.Add(len(paths)) for _, path := range paths { go func(path string) { defer wg.Done() var buff bytes.Buffer buff.WriteString(fmt.Sprintf("\n%s\n", path)) reader, err := os.Open(path) if err != nil { log.Fatal(err) } defer reader.Close() img, _, err := image.Decode(reader) if err != nil { log.Fatal(err) } var q quant.Quantizer if *mode == "median" { q = median.Quantizer(*size) } else { q = mean.Quantizer(*size) } pal := q.Palette(img) for _, c := range pal.ColorPalette() { r, g, b, _ := c.RGBA() buff.WriteString(fmt.Sprintf("#%02x%02x%02x\n", uint8(r>>8), uint8(g>>8), uint8(b>>8))) } fmt.Print(buff.String()) }(path) } wg.Wait() }
func BenchmarkPalette(b *testing.B) { var img image.Image for _, p := range glob(b) { f, err := os.Open(p) if err != nil { b.Log(err) // skip files that can't be opened continue } img, err = png.Decode(f) f.Close() if err != nil { b.Log(err) // skip files that can't be decoded continue } break } var q quant.Quantizer = mean.Quantizer(256) b.ResetTimer() for i := 0; i < b.N; i++ { q.Palette(img) } }