The RGBA Histogram for a UIImage in Swift 5

import Accelerate
import UIKit


/// Get histograms for R, G, B, A channels of UIImage
/// https://stackoverflow.com/questions/37818720/swift-2-2-count-black-pixels-in-uiimage
/// https://stackoverflow.com/questions/40562889/drawing-histogram-of-cgimage-in-swift-3
/// https://developer.apple.com/documentation/accelerate/specifying_histograms_with_vimage
func histogram(image: UIImage) -> (red: [UInt], green: [UInt], blue: [UInt], alpha: [UInt]) {
let img: CGImage = CIImage(image: image)!.cgImage!

let imgProvider: CGDataProvider = img.dataProvider!
let imgBitmapData: CFData = imgProvider.data!
var imgBuffer = vImage_Buffer(
data: UnsafeMutableRawPointer(mutating: CFDataGetBytePtr(imgBitmapData)),
height: vImagePixelCount(img.height),
width: vImagePixelCount(img.width),
rowBytes: img.bytesPerRow)

// bins: zero = red, green = one, blue = two, alpha = three
var binZero = [vImagePixelCount](repeating: 0, count: 256)
var binOne = [vImagePixelCount](repeating: 0, count: 256)
var binTwo = [vImagePixelCount](repeating: 0, count: 256)
var binThree = [vImagePixelCount](repeating: 0, count: 256)

binZero.withUnsafeMutableBufferPointer { zeroPtr in
binOne.withUnsafeMutableBufferPointer { onePtr in
binTwo.withUnsafeMutableBufferPointer { twoPtr in
binThree.withUnsafeMutableBufferPointer { threePtr in

var histogramBins = [zeroPtr.baseAddress, onePtr.baseAddress,
twoPtr.baseAddress, threePtr.baseAddress]

histogramBins.withUnsafeMutableBufferPointer {
histogramBinsPtr in
let error = vImageHistogramCalculation_ARGB8888(
&imgBuffer,
histogramBinsPtr.baseAddress!,
vImage_Flags(kvImageNoFlags))

guard error == kvImageNoError else {
fatalError("Error calculating histogram: \(error)")
}
}
}
}
}
}

return (binZero, binOne, binTwo, binThree)
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Gary Bartos

Gary Bartos

Founder of Echobatix, developing assistive technology for the blind. echobatix@gmail.com