An idea for a more basic solution:
split each color axis (0 to 255) in segments with width of 4:
0-3; 4-7; 8-11 …
You will have 64 segments.
Then you create an array to count how many pixels in each of the 64 * 64 * 64 = 262144 items (if you split by 8, you can reduce to 323232 = 32768
var theCube : [Int] = Array(repeating: 0, count: 646464)
a function to compute the position of a color in the array:
func colorIndex(for color: UIColor) -> Int {
// we return 64*64*r/4 + 64*g/4 + b/4, with r, g, b between 0 and 255
var index = 0
if let components = color.cgColor.components {
if components.count < 3 { // We are grayscale, r, g, b will be equal
let grayValue = Int(255*components[0] / 4) // We bring grayValue between 0 and 63
index = (64*64 + 64 + 1) * grayValue
} else { // components are between 0 and 1, convert to 0...255 first
index = 64*64*Int(255*components[0] / 4)
index = index + 64 * Int(255*components[1] / 4)
index = index + Int(255*components[2] / 4)
}
}
return index
}
test:
print(colorIndex(for: UIColor.red)) // 258048
print(colorIndex(for: UIColor.green)) // 4032
print(colorIndex(for: UIColor.blue)) // 63
print(colorIndex(for: UIColor.white)) // 262143 last item in cube
print(colorIndex(for: UIColor.black)) // 0 first item in cube
you then test for each pixel, computing the colorIndex and increment the cube[index] accordingly
max value in the array is the dominant color: its index is dominantColorIndex.
Once you have defined this dominant color search for points which color fall in this max, by computing its colorIndex and find if equal to dominantColorIndex
Hope that helps.
Topic:
Programming Languages
SubTopic:
Swift
Tags: