-
Notifications
You must be signed in to change notification settings - Fork 1
/
extractor.go
72 lines (61 loc) · 1.9 KB
/
extractor.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Package extractor extracts the dominant color or a representative color palette
// from an image.
package extractor
import (
"fmt"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"os"
)
// Extractor represents the color palette extractor instance associated with a single image.
type Extractor struct {
filename string
quality int
pixels []pixel
}
// NewExtractor returns a new instance of an Extractor.
// The provider filename parameter can contain a path, and must include the file extension.
// The provided quality parameter behaves in the following manner:
// the bigger the number, the faster a color will be returned but the greater the likelihood
// that it will not be the visually most dominant color. 1 then refers the highest quality.
func NewExtractor(filename string, quality int) *Extractor {
extractor := &Extractor{}
reader, err := os.Open(filename)
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
}
defer reader.Close()
pixels, err := getPixels(reader, quality)
if err != nil {
fmt.Fprintf(os.Stderr, "%s", err)
os.Exit(1)
}
extractor.filename = filename
extractor.quality = quality
extractor.pixels = pixels
return extractor
}
// GetPalette builds a color palette.
// We are using the median cut algorithm to cluster similar colors.
// The provided count parameter defines how many colors should be extracted.
// Each color is returned as [r g b].
func (extractor *Extractor) GetPalette(count int) [][]int {
ret := make([][]int, count)
for i := range ret {
ret[i] = make([]int, 3)
}
pixels := quantize(extractor.pixels, count).getPalette()
for i := 0; i < count; i++ {
ret[i][0] = pixels[i].R
ret[i][1] = pixels[i].G
ret[i][2] = pixels[i].B
}
return ret
}
// GetColor selects the dominant color.
// It corresponds to the first color in the palette.
// The color is returned as [r g b].
func (extractor *Extractor) GetColor() []int {
return extractor.GetPalette(5)[0]
}