| 1 |
package palgen |
| 2 |
|
| 3 |
import ( |
| 4 |
"errors" |
| 5 |
"image" |
| 6 |
"image/color" |
| 7 |
"math" |
| 8 |
"sort" |
| 9 |
) |
| 10 |
|
| 11 |
// SortablePalette is a slice of color.Color that can be sorted with sort.Sort, by euclidian distance for R, G and B |
| 12 |
type SortablePalette []color.Color |
| 13 |
|
| 14 |
// Length from RGB (0, 0, 0) |
| 15 |
func colorLength(c color.Color) float64 { |
| 16 |
r := c.(color.RGBA) |
| 17 |
ri, gi, bi := uint32(r.R), uint32(r.G), uint32(r.B) |
| 18 |
return math.Sqrt(float64(ri*ri + gi*gi + bi*bi)) |
| 19 |
} |
| 20 |
|
| 21 |
func (a SortablePalette) Len() int { return len(a) } |
| 22 |
func (a SortablePalette) Swap(i, j int) { a[i], a[j] = a[j], a[i] } |
| 23 |
func (a SortablePalette) Less(i, j int) bool { return colorLength(a[i]) < colorLength(a[j]) } |
| 24 |
|
| 25 |
// Median finds not the average but the median color |
| 26 |
func Median(colors []color.Color) (color.Color, error) { |
| 27 |
length := len(colors) |
| 28 |
if length == 0 { |
| 29 |
return nil, errors.New("can't find the median of an empty slice of colors") |
| 30 |
} |
| 31 |
if len(colors) == 1 { |
| 32 |
return colors[0], nil |
| 33 |
} |
| 34 |
|
| 35 |
// 1. Sort the colors |
| 36 |
sp := SortablePalette(colors) |
| 37 |
sort.Sort(sp) |
| 38 |
|
| 39 |
// 2. Select the center one, if odd |
| 40 |
if length%2 != 0 { |
| 41 |
centerPos := length / 2 |
| 42 |
return sp[centerPos], nil |
| 43 |
} |
| 44 |
// 3. If the numbers are even, select the two center one and take the average of those |
| 45 |
centerPos1 := (length / 2) - 1 |
| 46 |
centerPos2 := length / 2 |
| 47 |
c1 := sp[centerPos1].(color.RGBA) |
| 48 |
c2 := sp[centerPos2].(color.RGBA) |
| 49 |
r := uint8((uint16(c1.R) + uint16(c2.R)) / 2) |
| 50 |
g := uint8((uint16(c1.G) + uint16(c2.G)) / 2) |
| 51 |
b := uint8((uint16(c1.B) + uint16(c2.B)) / 2) |
| 52 |
a := uint8((uint16(c1.A) + uint16(c2.A)) / 2) |
| 53 |
// return the new color |
| 54 |
return color.RGBA{r, g, b, a}, nil |
| 55 |
} |
| 56 |
|
| 57 |
// Median3 finds not the average but the median color. Returns three colors if the number of colors is even (average, first and second color in the center). |
| 58 |
func Median3(colors []color.Color) (color.Color, color.Color, color.Color, error) { |
| 59 |
length := len(colors) |
| 60 |
if length == 0 { |
| 61 |
return nil, nil, nil, errors.New("can't find the median of an empty slice of colors") |
| 62 |
} |
| 63 |
if len(colors) == 1 { |
| 64 |
return colors[0], colors[0], colors[0], nil |
| 65 |
} |
| 66 |
|
| 67 |
// 1. Sort the colors |
| 68 |
sp := SortablePalette(colors) |
| 69 |
sort.Sort(sp) |
| 70 |
|
| 71 |
// 2. Select the center one, if odd |
| 72 |
if length%2 != 0 { |
| 73 |
centerPos := length / 2 |
| 74 |
// Return the center color, thrice |
| 75 |
return sp[centerPos], sp[centerPos], sp[centerPos], nil |
| 76 |
} |
| 77 |
// 3. If the numbers are even, select the two center one and take the average of those |
| 78 |
centerPos1 := (length / 2) - 1 |
| 79 |
centerPos2 := length / 2 |
| 80 |
c1 := sp[centerPos1].(color.RGBA) |
| 81 |
c2 := sp[centerPos2].(color.RGBA) |
| 82 |
r := uint8((uint16(c1.R) + uint16(c2.R)) / 2) |
| 83 |
g := uint8((uint16(c1.G) + uint16(c2.G)) / 2) |
| 84 |
b := uint8((uint16(c1.B) + uint16(c2.B)) / 2) |
| 85 |
a := uint8((uint16(c1.A) + uint16(c2.A)) / 2) |
| 86 |
averageColor := color.RGBA{r, g, b, a} |
| 87 |
|
| 88 |
// Also return the two center colors |
| 89 |
return averageColor, sp[centerPos2], sp[centerPos1], nil |
| 90 |
} |
| 91 |
|
| 92 |
// Generate can generate a palette with N colors, given an image |
| 93 |
func Generate(img image.Image, N int) (color.Palette, error) { |
| 94 |
groups := make(map[int][]color.Color) |
| 95 |
already := make(map[color.Color]bool) |
| 96 |
|
| 97 |
numberOfPixels := (img.Bounds().Max.Y - img.Bounds().Min.Y) * (img.Bounds().Max.X - img.Bounds().Min.X) |
| 98 |
levelCounter := make(map[int]float64, numberOfPixels) |
| 99 |
colorCounter := make(map[color.RGBA]float64, numberOfPixels) |
| 100 |
|
| 101 |
// Pick out the colors from the image, per intensity level, and store them in the groups map |
| 102 |
for y := img.Bounds().Min.Y; y < img.Bounds().Max.Y; y++ { |
| 103 |
for x := img.Bounds().Min.X; x < img.Bounds().Max.X; x++ { |
| 104 |
c := img.At(x, y) |
| 105 |
gc := color.GrayModel.Convert(c).(color.Gray) |
| 106 |
rgba := color.RGBAModel.Convert(c).(color.RGBA) |
| 107 |
level := int(float64(gc.Y) / (255.0 / float64(N-1))) |
| 108 |
alreadyColor, ok := already[rgba] |
| 109 |
if !alreadyColor || !ok { |
| 110 |
groups[level] = append(groups[level], rgba) |
| 111 |
already[rgba] = true |
| 112 |
} |
| 113 |
// Count the different levels used |
| 114 |
if counter, ok := levelCounter[level]; ok { |
| 115 |
levelCounter[level] = counter + 1.0 |
| 116 |
} else { |
| 117 |
levelCounter[level] = 1.0 |
| 118 |
} |
| 119 |
// Count the different colors used |
| 120 |
if counter, ok := colorCounter[rgba]; ok { |
| 121 |
colorCounter[rgba] = counter + 1.0 |
| 122 |
} else { |
| 123 |
colorCounter[rgba] = 1.0 |
| 124 |
} |
| 125 |
|
| 126 |
} |
| 127 |
} |
| 128 |
|
| 129 |
// If the image has fewer unique colors than requested, just return them all |
| 130 |
if len(already) <= N { |
| 131 |
var pal color.Palette |
| 132 |
for c := range already { |
| 133 |
pal = append(pal, c) |
| 134 |
} |
| 135 |
return pal, nil |
| 136 |
} |
| 137 |
|
| 138 |
// Reset the map for if colors are already appended to a slice |
| 139 |
already = make(map[color.Color]bool) |
| 140 |
already2 := make(map[color.Color]bool) |
| 141 |
var extrapal color.Palette |
| 142 |
|
| 143 |
// Remove the group of colors with the least used intensity level |
| 144 |
minCoverage := 1.0 |
| 145 |
minCoverageKey := 0 |
| 146 |
found := false |
| 147 |
for intensityLevelKey := range groups { |
| 148 |
coverage := levelCounter[intensityLevelKey] / float64(numberOfPixels) |
| 149 |
if coverage < minCoverage { |
| 150 |
minCoverage = coverage |
| 151 |
minCoverageKey = intensityLevelKey |
| 152 |
found = true |
| 153 |
} |
| 154 |
} |
| 155 |
if found { |
| 156 |
delete(groups, minCoverageKey) |
| 157 |
} |
| 158 |
|
| 159 |
// Find the median color for each intensity level |
| 160 |
var pal color.Palette |
| 161 |
for _, colors := range groups { |
| 162 |
// Find the median color of a group of colors of a certain intensity |
| 163 |
//medianColor, err := Median(colors) |
| 164 |
medianColor1, medianColor2, medianColor3, err := Median3(colors) |
| 165 |
if err != nil { |
| 166 |
return nil, err |
| 167 |
} |
| 168 |
// Add the medianColor1 to the palette, if it's not already there |
| 169 |
alreadyColor, ok := already[medianColor1] |
| 170 |
if !alreadyColor || !ok { |
| 171 |
pal = append(pal, medianColor1) |
| 172 |
already[medianColor1] = true |
| 173 |
} |
| 174 |
// Add medianColor2 and medianColor3 to the extra palette, if they are not already in it |
| 175 |
alreadyColor2, ok := already2[medianColor2] |
| 176 |
if !alreadyColor2 || !ok { |
| 177 |
extrapal = append(extrapal, medianColor2) |
| 178 |
already2[medianColor2] = true |
| 179 |
} |
| 180 |
alreadyColor2, ok = already2[medianColor3] |
| 181 |
if !alreadyColor2 || !ok { |
| 182 |
extrapal = append(extrapal, medianColor3) |
| 183 |
already2[medianColor3] = true |
| 184 |
} |
| 185 |
} |
| 186 |
|
| 187 |
// If there are not enough colors in the generated palette (N+1, because we will remove one), add colors from extrapal |
| 188 |
for (len(pal) < N) && (len(extrapal) > 0) { |
| 189 |
var ( |
| 190 |
maxUsage = -1.0 |
| 191 |
mostFrequentIndex = -1 |
| 192 |
) |
| 193 |
|
| 194 |
// Loop through extrapal to find the most frequently used color |
| 195 |
for i, extraColor := range extrapal { |
| 196 |
rgbaExtra := color.RGBAModel.Convert(extraColor).(color.RGBA) |
| 197 |
if usage, ok := colorCounter[rgbaExtra]; ok { |
| 198 |
if usage > maxUsage { |
| 199 |
maxUsage = usage |
| 200 |
mostFrequentIndex = i |
| 201 |
} |
| 202 |
} |
| 203 |
} |
| 204 |
if mostFrequentIndex == -1 { // not found |
| 205 |
break |
| 206 |
} |
| 207 |
|
| 208 |
// Use the most frequently used color from the palette of extra colors |
| 209 |
c := extrapal[mostFrequentIndex] |
| 210 |
|
| 211 |
// Add the color to the palette, if it's not already there |
| 212 |
alreadyColor, ok := already[c] |
| 213 |
if !alreadyColor || !ok { |
| 214 |
pal = append(pal, c) |
| 215 |
already[c] = true |
| 216 |
} |
| 217 |
|
| 218 |
// Remove this color from extrapal |
| 219 |
extrapal = append(extrapal[:mostFrequentIndex], extrapal[mostFrequentIndex+1:]...) |
| 220 |
} |
| 221 |
|
| 222 |
// Now remove the one extra color that covers the least amount of pixels of the image that has been converted to the current palette |
| 223 |
if len(pal) > N { |
| 224 |
minCoverage := 1.0 |
| 225 |
minCoverageIndex := -1 |
| 226 |
for i := 0; i < len(pal); i++ { |
| 227 |
c := color.RGBAModel.Convert(pal[i]).(color.RGBA) |
| 228 |
coverage := colorCounter[c] / float64(numberOfPixels) |
| 229 |
if coverage < minCoverage { |
| 230 |
minCoverage = coverage |
| 231 |
minCoverageIndex = i |
| 232 |
} |
| 233 |
} |
| 234 |
if minCoverageIndex != -1 { |
| 235 |
// Replace i with the last element |
| 236 |
pal[minCoverageIndex] = pal[len(pal)-1] |
| 237 |
// Remove the last element |
| 238 |
pal = pal[:len(pal)-1] |
| 239 |
} |
| 240 |
} |
| 241 |
|
| 242 |
// Remove near-duplicate dark colors. Look at the darkest 10% of the |
| 243 |
// palette (by lightness) and remove entries that are within 5% lightness |
| 244 |
// of another dark color, keeping the most frequently used one. |
| 245 |
darkCount := len(pal) / 10 |
| 246 |
if darkCount >= 2 { |
| 247 |
const lightnessThreshold = 255.0 * 0.05 // 5% of full range |
| 248 |
|
| 249 |
// Find lightness for each palette entry |
| 250 |
type palEntry struct { |
| 251 |
index int |
| 252 |
lightness float64 |
| 253 |
} |
| 254 |
entries := make([]palEntry, len(pal)) |
| 255 |
for i, c := range pal { |
| 256 |
gc := color.GrayModel.Convert(c).(color.Gray) |
| 257 |
entries[i] = palEntry{i, float64(gc.Y)} |
| 258 |
} |
| 259 |
|
| 260 |
// Sort by lightness to find the darkest entries |
| 261 |
sort.Slice(entries, func(i, j int) bool { |
| 262 |
return entries[i].lightness < entries[j].lightness |
| 263 |
}) |
| 264 |
|
| 265 |
// Among the darkest entries, mark near-duplicates for removal |
| 266 |
darkEntries := entries[:darkCount] |
| 267 |
removeSet := make(map[int]bool) |
| 268 |
for i := range darkEntries { |
| 269 |
if removeSet[darkEntries[i].index] { |
| 270 |
continue |
| 271 |
} |
| 272 |
for j := i + 1; j < len(darkEntries); j++ { |
| 273 |
if removeSet[darkEntries[j].index] { |
| 274 |
continue |
| 275 |
} |
| 276 |
if darkEntries[j].lightness-darkEntries[i].lightness > lightnessThreshold { |
| 277 |
break // sorted, so no more matches |
| 278 |
} |
| 279 |
// These two are near-duplicates; remove the less used one |
| 280 |
ci := color.RGBAModel.Convert(pal[darkEntries[i].index]).(color.RGBA) |
| 281 |
cj := color.RGBAModel.Convert(pal[darkEntries[j].index]).(color.RGBA) |
| 282 |
if colorCounter[ci] >= colorCounter[cj] { |
| 283 |
removeSet[darkEntries[j].index] = true |
| 284 |
} else { |
| 285 |
removeSet[darkEntries[i].index] = true |
| 286 |
break // i is removed, stop comparing from it |
| 287 |
} |
| 288 |
} |
| 289 |
} |
| 290 |
|
| 291 |
// Rebuild palette without the removed entries |
| 292 |
if len(removeSet) > 0 { |
| 293 |
var trimmed color.Palette |
| 294 |
for i, c := range pal { |
| 295 |
if !removeSet[i] { |
| 296 |
trimmed = append(trimmed, c) |
| 297 |
} |
| 298 |
} |
| 299 |
pal = trimmed |
| 300 |
|
| 301 |
// Backfill freed slots from extrapal |
| 302 |
for (len(pal) < N) && (len(extrapal) > 0) { |
| 303 |
var ( |
| 304 |
maxUsage = -1.0 |
| 305 |
mostFrequentIndex = -1 |
| 306 |
) |
| 307 |
for i, extraColor := range extrapal { |
| 308 |
rgbaExtra := color.RGBAModel.Convert(extraColor).(color.RGBA) |
| 309 |
if usage, ok := colorCounter[rgbaExtra]; ok { |
| 310 |
if usage > maxUsage { |
| 311 |
maxUsage = usage |
| 312 |
mostFrequentIndex = i |
| 313 |
} |
| 314 |
} |
| 315 |
} |
| 316 |
if mostFrequentIndex == -1 { |
| 317 |
break |
| 318 |
} |
| 319 |
c := extrapal[mostFrequentIndex] |
| 320 |
alreadyColor, ok := already[c] |
| 321 |
if !alreadyColor || !ok { |
| 322 |
pal = append(pal, c) |
| 323 |
already[c] = true |
| 324 |
} |
| 325 |
extrapal = append(extrapal[:mostFrequentIndex], extrapal[mostFrequentIndex+1:]...) |
| 326 |
} |
| 327 |
} |
| 328 |
} |
| 329 |
|
| 330 |
// Return the generated palette |
| 331 |
return pal, nil |
| 332 |
} |
| 333 |
|
| 334 |
// GenerateUpTo can generate a palette with up to N colors, given an image |
| 335 |
func GenerateUpTo(img image.Image, N int) (color.Palette, error) { |
| 336 |
groups := make(map[int][]color.Color) |
| 337 |
already := make(map[color.Color]bool) |
| 338 |
|
| 339 |
numberOfPixels := (img.Bounds().Max.Y - img.Bounds().Min.Y) * (img.Bounds().Max.X - img.Bounds().Min.X) |
| 340 |
levelCounter := make(map[int]float64, numberOfPixels) |
| 341 |
colorCounter := make(map[color.RGBA]float64, numberOfPixels) |
| 342 |
|
| 343 |
// Pick out the colors from the image, per intensity level, and store them in the groups map |
| 344 |
for y := img.Bounds().Min.Y; y < img.Bounds().Max.Y; y++ { |
| 345 |
for x := img.Bounds().Min.X; x < img.Bounds().Max.X; x++ { |
| 346 |
c := img.At(x, y) |
| 347 |
gc := color.GrayModel.Convert(c).(color.Gray) |
| 348 |
rgba := color.RGBAModel.Convert(c).(color.RGBA) |
| 349 |
level := int(float64(gc.Y) / (255.0 / float64(N-1))) |
| 350 |
alreadyColor, ok := already[rgba] |
| 351 |
if !alreadyColor || !ok { |
| 352 |
groups[level] = append(groups[level], rgba) |
| 353 |
already[rgba] = true |
| 354 |
} |
| 355 |
// Count the different levels used |
| 356 |
if counter, ok := levelCounter[level]; ok { |
| 357 |
levelCounter[level] = counter + 1.0 |
| 358 |
} else { |
| 359 |
levelCounter[level] = 1.0 |
| 360 |
} |
| 361 |
// Count the different colors used |
| 362 |
if counter, ok := colorCounter[rgba]; ok { |
| 363 |
colorCounter[rgba] = counter + 1.0 |
| 364 |
} else { |
| 365 |
colorCounter[rgba] = 1.0 |
| 366 |
} |
| 367 |
} |
| 368 |
} |
| 369 |
|
| 370 |
// Remove the group of colors with the least used intensity level, |
| 371 |
// but only if there are more groups than requested colors. |
| 372 |
if len(groups) > N { |
| 373 |
minCoverage := 1.0 |
| 374 |
minCoverageKey := 0 |
| 375 |
found := false |
| 376 |
for intensityLevelKey := range groups { |
| 377 |
coverage := levelCounter[intensityLevelKey] / float64(numberOfPixels) |
| 378 |
if coverage < minCoverage { |
| 379 |
minCoverage = coverage |
| 380 |
minCoverageKey = intensityLevelKey |
| 381 |
found = true |
| 382 |
} |
| 383 |
} |
| 384 |
if found { |
| 385 |
delete(groups, minCoverageKey) |
| 386 |
} |
| 387 |
} |
| 388 |
|
| 389 |
// Reset the map for if colors are already appended to a slice |
| 390 |
already = make(map[color.Color]bool) |
| 391 |
|
| 392 |
// Find the median color for each intensity level |
| 393 |
var pal color.Palette |
| 394 |
for _, colors := range groups { |
| 395 |
// Find the median color of a group of colors of a certain intensity |
| 396 |
//medianColor, err := Median(colors) |
| 397 |
medianColor1, _, _, err := Median3(colors) |
| 398 |
if err != nil { |
| 399 |
return nil, err |
| 400 |
} |
| 401 |
// Add the medianColor1 to the palette, if it's not already there |
| 402 |
alreadyColor, ok := already[medianColor1] |
| 403 |
if !alreadyColor || !ok { |
| 404 |
pal = append(pal, medianColor1) |
| 405 |
already[medianColor1] = true |
| 406 |
} |
| 407 |
} |
| 408 |
|
| 409 |
// Return the generated palette |
| 410 |
return pal, nil |
| 411 |
} |