How to calculate the average color of a UIImage?

前端 未结 6 1733
花落未央
花落未央 2021-02-01 07:55

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 gr

6条回答
  •  闹比i
    闹比i (楼主)
    2021-02-01 08:26

    You'll need to use the Accelerate Library, Apple has a manual with some sample code, it'll work in Swift or ObjC

    Here is a sample to get you going, I use this to calculate a person's heart rate and heart rate variability using the change in colors of a finger over the camera lens.

    Full code here: https://github.com/timestocome/SwiftHeartRate/blob/master/Swift%20Pulse%20Reader/ViewController.swift

    It's in an older version of Swift but I think you'll get the idea. I was doing this at 240 fps, but with a cropped smaller section of the image.

    Relevant code here:

    // compute the brightness for reg, green, blue and total
        // pull out color values from pixels ---  image is BGRA
        var greenVector:[Float] = Array(count: numberOfPixels, repeatedValue: 0.0)
        var blueVector:[Float] = Array(count: numberOfPixels, repeatedValue: 0.0)
        var redVector:[Float] = Array(count: numberOfPixels, repeatedValue: 0.0)
    
        vDSP_vfltu8(dataBuffer, 4, &blueVector, 1, vDSP_Length(numberOfPixels))
        vDSP_vfltu8(dataBuffer+1, 4, &greenVector, 1, vDSP_Length(numberOfPixels))
        vDSP_vfltu8(dataBuffer+2, 4, &redVector, 1, vDSP_Length(numberOfPixels))
    
    
    
        // compute average per color
        var redAverage:Float = 0.0
        var blueAverage:Float = 0.0
        var greenAverage:Float = 0.0
    
        vDSP_meamgv(&redVector, 1, &redAverage, vDSP_Length(numberOfPixels))
        vDSP_meamgv(&greenVector, 1, &greenAverage, vDSP_Length(numberOfPixels))
        vDSP_meamgv(&blueVector, 1, &blueAverage, vDSP_Length(numberOfPixels))
    
    
    
        // convert to HSV ( hue, saturation, value )
        // this gives faster, more accurate answer
        var hue: CGFloat = 0.0
        var saturation: CGFloat = 0.0
        var brightness: CGFloat = 0.0
        var alpha: CGFloat = 1.0
    
        var color: UIColor = UIColor(red: CGFloat(redAverage/255.0), green: CGFloat(greenAverage/255.0), blue: CGFloat(blueAverage/255.0), alpha: alpha)
        color.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha)
    
    
    
    
        // 5 count rolling average
        let currentHueAverage = hue/movingAverageCount
        movingAverageArray.removeAtIndex(0)
        movingAverageArray.append(currentHueAverage)
    
        let movingAverage = movingAverageArray[0] + movingAverageArray[1] + movingAverageArray[2] + movingAverageArray[3] + movingAverageArray[4]
    

提交回复
热议问题