-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathcolorhistogram.go
68 lines (59 loc) · 1.49 KB
/
colorhistogram.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
package vibrant
import (
"image/color"
"sort"
)
// Colors and ColorCounts are transformed into a map[int]int by colorCutQuantizer
// where key is the 24-bit color and value is the count
type colorHistogram struct {
Colors []int // 24-bit packed int colors
ColorCounts []int // index refers to above color
NumberColors int
}
// See colorCutQuantizer source for how this is used.
func newColorHistogram(colorPixels []color.Color) *colorHistogram {
// Transform []color.Color into array of 24-bit ints
pixels := make([]int, len(colorPixels))
for _, px := range colorPixels {
pixels = append(pixels, packColor(colorToRgb(px)))
}
// Sort the pixels to enable counting
sort.Ints(pixels)
numColors := countDistinctColors(pixels)
colors := make([]int, numColors)
colorCounts := make([]int, numColors)
if numColors > 0 {
curIndex := 0
curColor := pixels[0]
colors[0] = curColor
colorCounts[0] = 1
for _, px := range pixels {
if px == curColor {
// same color, increase population
colorCounts[curIndex]++
} else {
// new color, increase index
curColor = px
curIndex++
colors[curIndex] = curColor
colorCounts[curIndex] = 1
}
}
}
return &colorHistogram{colors, colorCounts, numColors}
}
func countDistinctColors(pixels []int) int {
if len(pixels) < 2 {
return len(pixels)
}
count := 1
current := pixels[0]
for _, px := range pixels {
if px != current {
// new color, increase population
current = px
count++
}
}
return count
}