Debian Codegraph @

vendor/github.com/lucasb-eyer/go-colorful/soft_palettegen.go

raw
1 // Largely inspired by the descriptions in http://lab.medialab.sciences-po.fr/iwanthue/
2 // but written from scratch.
3
4 package colorful
5
6 import (
7 "fmt"
8 "math"
9 )
10
11 // The algorithm works in L*a*b* color space and converts to RGB in the end.
12 // L* in [0..1], a* and b* in [-1..1]
13 type lab_t struct {
14 L, A, B float64
15 }
16
17 type SoftPaletteSettings struct {
18 // A function which can be used to restrict the allowed color-space.
19 CheckColor func(l, a, b float64) bool
20
21 // The higher, the better quality but the slower. Usually two figures.
22 Iterations int
23
24 // Use up to 160000 or 8000 samples of the L*a*b* space (and thus calls to CheckColor).
25 // Set this to true only if your CheckColor shapes the Lab space weirdly.
26 ManySamples bool
27 }
28
29 // Yeah, windows-stype Foo, FooEx, screw you golang...
30 // Uses K-means to cluster the color-space and return the means of the clusters
31 // as a new palette of distinctive colors. Falls back to K-medoid if the mean
32 // happens to fall outside of the color-space, which can only happen if you
33 // specify a CheckColor function.
34 func SoftPaletteExWithRand(colorsCount int, settings SoftPaletteSettings, rand RandInterface) ([]Color, error) {
35
36 // Checks whether it's a valid RGB and also fulfills the potentially provided constraint.
37 check := func(col lab_t) bool {
38 c := Lab(col.L, col.A, col.B)
39 return c.IsValid() && (settings.CheckColor == nil || settings.CheckColor(col.L, col.A, col.B))
40 }
41
42 // Sample the color space. These will be the points k-means is run on.
43 dl := 0.05
44 dab := 0.1
45 if settings.ManySamples {
46 dl = 0.01
47 dab = 0.05
48 }
49
50 samples := make([]lab_t, 0, int(1.0/dl*2.0/dab*2.0/dab))
51 for l := 0.0; l <= 1.0; l += dl {
52 for a := -1.0; a <= 1.0; a += dab {
53 for b := -1.0; b <= 1.0; b += dab {
54 if check(lab_t{l, a, b}) {
55 samples = append(samples, lab_t{l, a, b})
56 }
57 }
58 }
59 }
60
61 // That would cause some infinite loops down there...
62 if len(samples) < colorsCount {
63 return nil, fmt.Errorf("palettegen: more colors requested (%v) than samples available (%v). Your requested color count may be wrong, you might want to use many samples or your constraint function makes the valid color space too small", colorsCount, len(samples))
64 } else if len(samples) == colorsCount {
65 return labs2cols(samples), nil // Oops?
66 }
67
68 // We take the initial means out of the samples, so they are in fact medoids.
69 // This helps us avoid infinite loops or arbitrary cutoffs with too restrictive constraints.
70 means := make([]lab_t, colorsCount)
71 for i := 0; i < colorsCount; i++ {
72 for means[i] = samples[rand.Intn(len(samples))]; in(means, i, means[i]); means[i] = samples[rand.Intn(len(samples))] {
73 }
74 }
75
76 clusters := make([]int, len(samples))
77 samples_used := make([]bool, len(samples))
78
79 // The actual k-means/medoid iterations
80 for i := 0; i < settings.Iterations; i++ {
81 // Reassigning the samples to clusters, i.e. to their closest mean.
82 // By the way, also check if any sample is used as a medoid and if so, mark that.
83 for isample, sample := range samples {
84 samples_used[isample] = false
85 mindist := math.Inf(+1)
86 for imean, mean := range means {
87 dist := lab_dist(sample, mean)
88 if dist < mindist {
89 mindist = dist
90 clusters[isample] = imean
91 }
92
93 // Mark samples which are used as a medoid.
94 if lab_eq(sample, mean) {
95 samples_used[isample] = true
96 }
97 }
98 }
99
100 // Compute new means according to the samples.
101 for imean := range means {
102 // The new mean is the average of all samples belonging to it.
103 nsamples := 0
104 newmean := lab_t{0.0, 0.0, 0.0}
105 for isample, sample := range samples {
106 if clusters[isample] == imean {
107 nsamples++
108 newmean.L += sample.L
109 newmean.A += sample.A
110 newmean.B += sample.B
111 }
112 }
113 if nsamples > 0 {
114 newmean.L /= float64(nsamples)
115 newmean.A /= float64(nsamples)
116 newmean.B /= float64(nsamples)
117 } else {
118 // That mean doesn't have any samples? Get a new mean from the sample list!
119 var inewmean int
120 for inewmean = rand.Intn(len(samples_used)); samples_used[inewmean]; inewmean = rand.Intn(len(samples_used)) {
121 }
122 newmean = samples[inewmean]
123 samples_used[inewmean] = true
124 }
125
126 // But now we still need to check whether the new mean is an allowed color.
127 if nsamples > 0 && check(newmean) {
128 // It does, life's good (TM)
129 means[imean] = newmean
130 } else {
131 // New mean isn't an allowed color or doesn't have any samples!
132 // Switch to medoid mode and pick the closest (unused) sample.
133 // This should always find something thanks to len(samples) >= colorsCount
134 mindist := math.Inf(+1)
135 for isample, sample := range samples {
136 if !samples_used[isample] {
137 dist := lab_dist(sample, newmean)
138 if dist < mindist {
139 mindist = dist
140 newmean = sample
141 }
142 }
143 }
144 }
145 }
146 }
147 return labs2cols(means), nil
148 }
149
150 func SoftPaletteEx(colorsCount int, settings SoftPaletteSettings) ([]Color, error) {
151 return SoftPaletteExWithRand(colorsCount, settings, getDefaultGlobalRand())
152 }
153
154 // A wrapper which uses common parameters.
155 func SoftPaletteWithRand(colorsCount int, rand RandInterface) ([]Color, error) {
156 return SoftPaletteExWithRand(colorsCount, SoftPaletteSettings{nil, 50, false}, rand)
157 }
158
159 func SoftPalette(colorsCount int) ([]Color, error) {
160 return SoftPaletteWithRand(colorsCount, getDefaultGlobalRand())
161 }
162
163 func in(haystack []lab_t, upto int, needle lab_t) bool {
164 for i := 0; i < upto && i < len(haystack); i++ {
165 if haystack[i] == needle {
166 return true
167 }
168 }
169 return false
170 }
171
172 const LAB_DELTA = 1e-6
173
174 func lab_eq(lab1, lab2 lab_t) bool {
175 return math.Abs(lab1.L-lab2.L) < LAB_DELTA &&
176 math.Abs(lab1.A-lab2.A) < LAB_DELTA &&
177 math.Abs(lab1.B-lab2.B) < LAB_DELTA
178 }
179
180 // That's faster than using colorful's DistanceLab since we would have to
181 // convert back and forth for that. Here is no conversion.
182 func lab_dist(lab1, lab2 lab_t) float64 {
183 return math.Sqrt(sq(lab1.L-lab2.L) + sq(lab1.A-lab2.A) + sq(lab1.B-lab2.B))
184 }
185
186 func labs2cols(labs []lab_t) (cols []Color) {
187 cols = make([]Color, len(labs))
188 for k, v := range labs {
189 cols[k] = Lab(v.L, v.A, v.B)
190 }
191 return cols
192 }