I want to build an app that lets the user select an image and it outputs the "average color".
For example, this image:
The average color would be a greenish/yellowish color.
At the moment, I got this code:
// In a UIColor extension
public static func fromImage(image: UIImage) -> UIColor {
var totalR: CGFloat = 0
var totalG: CGFloat = 0
var totalB: CGFloat = 0
var count: CGFloat = 0
for x in 0..<Int(image.size.width) {
for y in 0..<Int(image.size.height) {
count += 1
var rF: CGFloat = 0,
gF: CGFloat = 0,
bF: CGFloat = 0,
aF: CGFloat = 0
image.getPixelColor(CGPoint(x: x, y: y)).getRed(&rF, green: &gF, blue: &bF, alpha: &aF)
totalR += rF
totalG += gF
totalB += bF
}
}
let averageR = totalR / count
let averageG = totalG / count
let averageB = totalB / count
return UIColor(red: averageR, green: averageG, blue: averageB, alpha: 1.0)
}
Where getPixelColor
is defined as:
extension UIImage {
func getPixelColor(pos: CGPoint) -> UIColor {
let pixelData = CGDataProviderCopyData(CGImageGetDataProvider(self.CGImage))
let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)
let pixelInfo: Int = ((Int(self.size.width) * Int(pos.y)) + Int(pos.x)) * 4
let r = CGFloat(data[pixelInfo]) / CGFloat(255.0)
let g = CGFloat(data[pixelInfo+1]) / CGFloat(255.0)
let b = CGFloat(data[pixelInfo+2]) / CGFloat(255.0)
let a = CGFloat(data[pixelInfo+3]) / CGFloat(255.0)
return UIColor(red: r, green: g, blue: b, alpha: a)
}
}
As you can see, what I did here is pretty naive: I loop through all the pixels in the image, add their RGBs up, and divide by the count.
When I run the app and selects the image, the app freezes. I know that this is because the image is too large and the two nested for loops are executed too many times.
I want to find a way to efficiently get the average color of an image. How do I do that?