| 1 |
package sixel |
| 2 |
|
| 3 |
import ( |
| 4 |
"container/heap" |
| 5 |
"image" |
| 6 |
"image/color" |
| 7 |
"math" |
| 8 |
) |
| 9 |
|
| 10 |
// sixelPalette is a palette of up to 256 colors that lists the colors that will be used by |
| 11 |
// a SixelImage. Most images, especially jpegs, have more than 256 colors, so creating a sixelPalette |
| 12 |
// requires the use of color quantization. For this we use the Median Cut algorithm. |
| 13 |
// |
| 14 |
// Median cut requires all pixels in an image to be positioned in a 4D color cube, with one axis per channel. |
| 15 |
// The cube is sliced in half along its longest axis such that half the pixels in the cube end up in one of |
| 16 |
// the sub-cubes and half end up in the other. We continue slicing the cube with the longest axis in half |
| 17 |
// along that axis until there are 256 sub-cubes. Then, the average of all pixels in each subcube is used |
| 18 |
// as that cube's color. |
| 19 |
// |
| 20 |
// Colors are converted to palette colors based on which they are closest to (it's not |
| 21 |
// always their cube's color). |
| 22 |
// |
| 23 |
// This implementation has a few minor (but seemingly very common) differences from the Official algorithm: |
| 24 |
// - When determining the longest axis, the number of pixels in the cube are multiplied against axis length |
| 25 |
// This improves color selection by quite a bit in cases where an image has a lot of space taken up by different |
| 26 |
// shades of the same color. |
| 27 |
// - If a single color sits on a cut line, all pixels of that color are assigned to one of the subcubes |
| 28 |
// rather than try to split them up between the subcubes. This allows us to use a slice of unique colors |
| 29 |
// and a map of pixel counts rather than try to represent each pixel individually. |
| 30 |
type sixelPalette struct { |
| 31 |
// Map used to convert colors from the image to palette colors |
| 32 |
colorConvert map[sixelColor]sixelColor |
| 33 |
// Lookup to get palette index from image color |
| 34 |
paletteIndexes map[sixelColor]int |
| 35 |
PaletteColors []sixelColor |
| 36 |
} |
| 37 |
|
| 38 |
// quantizationChannel is an enum type which indicates an axis in the color cube. Used to indicate which |
| 39 |
// axis in a cube is the longest. |
| 40 |
type quantizationChannel int |
| 41 |
|
| 42 |
const ( |
| 43 |
// MaxColors is the maximum number of colors a sixelPalette can contain. |
| 44 |
MaxColors int = 256 |
| 45 |
|
| 46 |
quantizationRed quantizationChannel = iota |
| 47 |
quantizationGreen |
| 48 |
quantizationBlue |
| 49 |
quantizationAlpha |
| 50 |
) |
| 51 |
|
| 52 |
// quantizationCube represents a single cube in the median cut algorithm. |
| 53 |
type quantizationCube struct { |
| 54 |
// startIndex is the index in the uniqueColors slice where this cube starts |
| 55 |
startIndex int |
| 56 |
// length is the number of elements in the uniqueColors slice this cube occupies |
| 57 |
length int |
| 58 |
// sliceChannel is the axis that will be cut if this cube is cut in half |
| 59 |
sliceChannel quantizationChannel |
| 60 |
// score is a heuristic value: higher means this cube is more likely to be cut |
| 61 |
score uint64 |
| 62 |
// pixelCount is how many pixels are contained in this cube |
| 63 |
pixelCount uint64 |
| 64 |
} |
| 65 |
|
| 66 |
// cubePriorityQueue is a heap used to sort quantizationCube objects in order to select the correct |
| 67 |
// one to cut next. Pop will remove the queue with the highest score. |
| 68 |
type cubePriorityQueue []any |
| 69 |
|
| 70 |
func (p *cubePriorityQueue) Push(x any) { |
| 71 |
*p = append(*p, x) |
| 72 |
} |
| 73 |
|
| 74 |
func (p *cubePriorityQueue) Pop() any { |
| 75 |
popped := (*p)[len(*p)-1] |
| 76 |
*p = (*p)[:len(*p)-1] |
| 77 |
return popped |
| 78 |
} |
| 79 |
|
| 80 |
func (p *cubePriorityQueue) Len() int { |
| 81 |
return len(*p) |
| 82 |
} |
| 83 |
|
| 84 |
func (p *cubePriorityQueue) Less(i, j int) bool { |
| 85 |
left := (*p)[i].(quantizationCube) |
| 86 |
right := (*p)[j].(quantizationCube) |
| 87 |
|
| 88 |
// We want the largest channel variance |
| 89 |
return left.score > right.score |
| 90 |
} |
| 91 |
|
| 92 |
func (p *cubePriorityQueue) Swap(i, j int) { |
| 93 |
(*p)[i], (*p)[j] = (*p)[j], (*p)[i] |
| 94 |
} |
| 95 |
|
| 96 |
// createCube is used to initialize a new quantizationCube containing a region of the uniqueColors slice. |
| 97 |
func (p *sixelPalette) createCube(uniqueColors []sixelColor, pixelCounts map[sixelColor]uint64, startIndex, bucketLength int) quantizationCube { |
| 98 |
minRed, minGreen, minBlue, minAlpha := uint32(0xffff), uint32(0xffff), uint32(0xffff), uint32(0xffff) |
| 99 |
maxRed, maxGreen, maxBlue, maxAlpha := uint32(0), uint32(0), uint32(0), uint32(0) |
| 100 |
totalWeight := uint64(0) |
| 101 |
|
| 102 |
// Figure out which channel has the greatest variance |
| 103 |
for i := startIndex; i < startIndex+bucketLength; i++ { |
| 104 |
r, g, b, a := uniqueColors[i].Red, uniqueColors[i].Green, uniqueColors[i].Blue, uniqueColors[i].Alpha |
| 105 |
totalWeight += pixelCounts[uniqueColors[i]] |
| 106 |
|
| 107 |
if r < minRed { |
| 108 |
minRed = r |
| 109 |
} |
| 110 |
if r > maxRed { |
| 111 |
maxRed = r |
| 112 |
} |
| 113 |
if g < minGreen { |
| 114 |
minGreen = g |
| 115 |
} |
| 116 |
if g > maxGreen { |
| 117 |
maxGreen = g |
| 118 |
} |
| 119 |
if b < minBlue { |
| 120 |
minBlue = b |
| 121 |
} |
| 122 |
if b > maxBlue { |
| 123 |
maxBlue = b |
| 124 |
} |
| 125 |
if a < minAlpha { |
| 126 |
minAlpha = a |
| 127 |
} |
| 128 |
if a > maxAlpha { |
| 129 |
maxAlpha = a |
| 130 |
} |
| 131 |
} |
| 132 |
|
| 133 |
dRed := maxRed - minRed |
| 134 |
dGreen := maxGreen - minGreen |
| 135 |
dBlue := maxBlue - minBlue |
| 136 |
dAlpha := maxAlpha - minAlpha |
| 137 |
|
| 138 |
cube := quantizationCube{ |
| 139 |
startIndex: startIndex, |
| 140 |
length: bucketLength, |
| 141 |
pixelCount: totalWeight, |
| 142 |
} |
| 143 |
|
| 144 |
if dRed >= dGreen && dRed >= dBlue && dRed >= dAlpha { |
| 145 |
cube.sliceChannel = quantizationRed |
| 146 |
cube.score = uint64(dRed) |
| 147 |
} else if dGreen >= dBlue && dGreen >= dAlpha { |
| 148 |
cube.sliceChannel = quantizationGreen |
| 149 |
cube.score = uint64(dGreen) |
| 150 |
} else if dBlue >= dAlpha { |
| 151 |
cube.sliceChannel = quantizationBlue |
| 152 |
cube.score = uint64(dBlue) |
| 153 |
} else { |
| 154 |
cube.sliceChannel = quantizationAlpha |
| 155 |
cube.score = uint64(dAlpha) |
| 156 |
} |
| 157 |
|
| 158 |
// Boost the score of cubes with more pixels in them |
| 159 |
cube.score *= totalWeight |
| 160 |
|
| 161 |
return cube |
| 162 |
} |
| 163 |
|
| 164 |
// quantize is a method that will initialize the palette's colors and lookups, provided a set |
| 165 |
// of unique colors and a map containing pixel counts for those colors. |
| 166 |
func (p *sixelPalette) quantize(uniqueColors []sixelColor, pixelCounts map[sixelColor]uint64, maxColors int) { |
| 167 |
p.colorConvert = make(map[sixelColor]sixelColor) |
| 168 |
p.paletteIndexes = make(map[sixelColor]int) |
| 169 |
|
| 170 |
// We don't need to quantize if we don't even have more than the maximum colors, and in fact, this code will explode |
| 171 |
// if we have fewer than maximum colors |
| 172 |
if len(uniqueColors) <= maxColors { |
| 173 |
p.PaletteColors = uniqueColors |
| 174 |
return |
| 175 |
} |
| 176 |
|
| 177 |
cubeHeap := make(cubePriorityQueue, 0, maxColors) |
| 178 |
|
| 179 |
// Start with a cube that contains all colors |
| 180 |
heap.Init(&cubeHeap) |
| 181 |
heap.Push(&cubeHeap, p.createCube(uniqueColors, pixelCounts, 0, len(uniqueColors))) |
| 182 |
|
| 183 |
// Slice the best cube into two cubes until we have max colors, then we have our palette |
| 184 |
for cubeHeap.Len() < maxColors { |
| 185 |
cubeToSplit := heap.Pop(&cubeHeap).(quantizationCube) |
| 186 |
|
| 187 |
//nolint:godox |
| 188 |
// TODO: Use slices.SortFunc and cmp.Compare in the future (>=1.24) |
| 189 |
// Then can delete palette_sort.go |
| 190 |
sortFunc(uniqueColors[cubeToSplit.startIndex:cubeToSplit.startIndex+cubeToSplit.length], |
| 191 |
func(left sixelColor, right sixelColor) int { |
| 192 |
switch cubeToSplit.sliceChannel { //nolint:exhaustive // alpha channel not used |
| 193 |
case quantizationRed: |
| 194 |
return compare(left.Red, right.Red) |
| 195 |
case quantizationGreen: |
| 196 |
return compare(left.Green, right.Green) |
| 197 |
case quantizationBlue: |
| 198 |
return compare(left.Blue, right.Blue) |
| 199 |
default: |
| 200 |
return compare(left.Alpha, right.Alpha) |
| 201 |
} |
| 202 |
}) |
| 203 |
|
| 204 |
// We need to split up the colors in this cube so that the pixels are evenly split between the two, |
| 205 |
// or at least as close as we can reasonably get. What we do is count up the pixels as we go through |
| 206 |
// and place the cut point where around half of the pixels are on the left side |
| 207 |
countSoFar := pixelCounts[uniqueColors[cubeToSplit.startIndex]] |
| 208 |
targetCount := cubeToSplit.pixelCount / 2 |
| 209 |
leftLength := 1 |
| 210 |
|
| 211 |
for i := cubeToSplit.startIndex + 1; i < cubeToSplit.startIndex+cubeToSplit.length; i++ { |
| 212 |
c := uniqueColors[i] |
| 213 |
weight := pixelCounts[c] |
| 214 |
if countSoFar+weight > targetCount { |
| 215 |
break |
| 216 |
} |
| 217 |
leftLength++ |
| 218 |
countSoFar += weight |
| 219 |
} |
| 220 |
|
| 221 |
rightLength := cubeToSplit.length - leftLength |
| 222 |
rightIndex := cubeToSplit.startIndex + leftLength |
| 223 |
heap.Push(&cubeHeap, p.createCube(uniqueColors, pixelCounts, cubeToSplit.startIndex, leftLength)) |
| 224 |
heap.Push(&cubeHeap, p.createCube(uniqueColors, pixelCounts, rightIndex, rightLength)) |
| 225 |
} |
| 226 |
|
| 227 |
// Once we've got max cubes in the heap, pull them all out and load them into the palette |
| 228 |
for cubeHeap.Len() > 0 { |
| 229 |
bucketToLoad := heap.Pop(&cubeHeap).(quantizationCube) |
| 230 |
p.loadColor(uniqueColors, pixelCounts, bucketToLoad.startIndex, bucketToLoad.length) |
| 231 |
} |
| 232 |
} |
| 233 |
|
| 234 |
// ColorIndex accepts a raw image color (NOT a palette color) and provides the palette index of that color. |
| 235 |
func (p *sixelPalette) ColorIndex(c sixelColor) int { |
| 236 |
return p.paletteIndexes[c] |
| 237 |
} |
| 238 |
|
| 239 |
// loadColor accepts a range of colors representing a single median cut cube. It calculates the |
| 240 |
// average color in the cube and adds it to the palette. |
| 241 |
func (p *sixelPalette) loadColor(uniqueColors []sixelColor, pixelCounts map[sixelColor]uint64, startIndex, cubeLen int) { |
| 242 |
totalRed, totalGreen, totalBlue, totalAlpha := uint64(0), uint64(0), uint64(0), uint64(0) |
| 243 |
totalCount := uint64(0) |
| 244 |
for i := startIndex; i < startIndex+cubeLen; i++ { |
| 245 |
count := pixelCounts[uniqueColors[i]] |
| 246 |
totalRed += uint64(uniqueColors[i].Red) * count |
| 247 |
totalGreen += uint64(uniqueColors[i].Green) * count |
| 248 |
totalBlue += uint64(uniqueColors[i].Blue) * count |
| 249 |
totalAlpha += uint64(uniqueColors[i].Alpha) * count |
| 250 |
totalCount += count |
| 251 |
} |
| 252 |
|
| 253 |
averageColor := sixelColor{ |
| 254 |
Red: uint32(totalRed / totalCount), //nolint:gosec |
| 255 |
Green: uint32(totalGreen / totalCount), //nolint:gosec |
| 256 |
Blue: uint32(totalBlue / totalCount), //nolint:gosec |
| 257 |
Alpha: uint32(totalAlpha / totalCount), //nolint:gosec |
| 258 |
} |
| 259 |
|
| 260 |
p.PaletteColors = append(p.PaletteColors, averageColor) |
| 261 |
} |
| 262 |
|
| 263 |
// sixelColor is a flat struct that contains a single color: all channels are 0-100 |
| 264 |
// instead of anything sensible. |
| 265 |
type sixelColor struct { |
| 266 |
Red uint32 |
| 267 |
Green uint32 |
| 268 |
Blue uint32 |
| 269 |
Alpha uint32 |
| 270 |
} |
| 271 |
|
| 272 |
// sixelConvertColor accepts an ordinary Go color and converts it to a sixelColor, which |
| 273 |
// has channels ranging from 0-100. |
| 274 |
func sixelConvertColor(c color.Color) sixelColor { |
| 275 |
r, g, b, a := c.RGBA() |
| 276 |
return sixelColor{ |
| 277 |
Red: sixelConvertChannel(r), |
| 278 |
Green: sixelConvertChannel(g), |
| 279 |
Blue: sixelConvertChannel(b), |
| 280 |
Alpha: sixelConvertChannel(a), |
| 281 |
} |
| 282 |
} |
| 283 |
|
| 284 |
// sixelConvertChannel converts a single color channel from go's standard 0-0xffff range to |
| 285 |
// sixel's 0-100 range. |
| 286 |
func sixelConvertChannel(channel uint32) uint32 { |
| 287 |
// We add 328 because that is about 0.5 in the sixel 0-100 color range, we're trying to |
| 288 |
// round to the nearest value |
| 289 |
return (channel + 328) * 100 / 0xffff |
| 290 |
} |
| 291 |
|
| 292 |
// newSixelPalette accepts an image and produces an N-color quantized color palette using the median cut |
| 293 |
// algorithm. The produced sixelPalette can convert colors from the image to the quantized palette |
| 294 |
// in O(1) time. |
| 295 |
func newSixelPalette(image image.Image, maxColors int) sixelPalette { |
| 296 |
pixelCounts := make(map[sixelColor]uint64) |
| 297 |
|
| 298 |
height := image.Bounds().Dy() |
| 299 |
width := image.Bounds().Dx() |
| 300 |
|
| 301 |
// Record pixel counts for every color while also getting a set of all unique colors in the image |
| 302 |
for y := range height { |
| 303 |
for x := range width { |
| 304 |
c := sixelConvertColor(image.At(x, y)) |
| 305 |
count := pixelCounts[c] |
| 306 |
count++ |
| 307 |
|
| 308 |
pixelCounts[c] = count |
| 309 |
} |
| 310 |
} |
| 311 |
|
| 312 |
p := sixelPalette{} |
| 313 |
uniqueColors := make([]sixelColor, 0, len(pixelCounts)) |
| 314 |
for c := range pixelCounts { |
| 315 |
uniqueColors = append(uniqueColors, c) |
| 316 |
} |
| 317 |
|
| 318 |
// Build up p.PaletteColors using the median cut algorithm |
| 319 |
p.quantize(uniqueColors, pixelCounts, maxColors) |
| 320 |
|
| 321 |
// The average color for a cube a color occupies is not always the closest palette color. As a result, |
| 322 |
// we need to use this very upsetting double loop to find the lookup palette color for each |
| 323 |
// unique color in the image. |
| 324 |
for _, c := range uniqueColors { |
| 325 |
var bestColor sixelColor |
| 326 |
var bestColorIndex int |
| 327 |
bestScore := uint32(math.MaxUint32) |
| 328 |
|
| 329 |
for paletteIndex, paletteColor := range p.PaletteColors { |
| 330 |
redDiff := c.Red - paletteColor.Red |
| 331 |
greenDiff := c.Green - paletteColor.Green |
| 332 |
blueDiff := c.Blue - paletteColor.Blue |
| 333 |
alphaDiff := c.Alpha - paletteColor.Alpha |
| 334 |
|
| 335 |
score := (redDiff * redDiff) + (greenDiff * greenDiff) + (blueDiff * blueDiff) + (alphaDiff * alphaDiff) |
| 336 |
if score < bestScore { |
| 337 |
bestColor = paletteColor |
| 338 |
bestColorIndex = paletteIndex |
| 339 |
bestScore = score |
| 340 |
} |
| 341 |
} |
| 342 |
|
| 343 |
p.paletteIndexes[c] = bestColorIndex |
| 344 |
p.colorConvert[c] = bestColor |
| 345 |
} |
| 346 |
|
| 347 |
return p |
| 348 |
} |