Created
May 2, 2023 21:34
-
-
Save igooor-bb/1a4c62670730e533f83be2dae85c78ee to your computer and use it in GitHub Desktop.
Calculating Histograms in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Accelerate | |
func calculateHistogram(image: CGImage) -> [[vImagePixelCount]] { | |
let format = vImage_CGImageFormat( | |
bitsPerComponent: 8, | |
bitsPerPixel: 32, | |
colorSpace: CGColorSpaceCreateDeviceRGB(), | |
bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.first.rawValue), | |
renderingIntent: .defaultIntent | |
)! | |
let histogramSourceCGImage = image | |
guard var histogramSourceBuffer = try? vImage_Buffer( | |
cgImage: histogramSourceCGImage, | |
format: format | |
) else { | |
return [] | |
} | |
defer { histogramSourceBuffer.free() } | |
var histogramRed = [vImagePixelCount](repeating: 0, count: 256) | |
var histogramGreen = [vImagePixelCount](repeating: 0, count: 256) | |
var histogramBlue = [vImagePixelCount](repeating: 0, count: 256) | |
var histogramAlpha = [vImagePixelCount](repeating: 0, count: 256) | |
histogramRed.withUnsafeMutableBufferPointer { red in | |
histogramGreen.withUnsafeMutableBufferPointer { green in | |
histogramBlue.withUnsafeMutableBufferPointer { blue in | |
histogramAlpha.withUnsafeMutableBufferPointer { alpha in | |
var histogramBins = [alpha.baseAddress, red.baseAddress, green.baseAddress, blue.baseAddress] | |
histogramBins.withUnsafeMutableBufferPointer { bins in | |
let error = vImageHistogramCalculation_ARGB8888( | |
&histogramSourceBuffer, | |
bins.baseAddress!, | |
vImage_Flags(kvImageNoFlags) | |
) | |
guard error == kvImageNoError else { | |
print("Failed to calculate histogram!") | |
return | |
} | |
} | |
} | |
} | |
} | |
} | |
let channels = [histogramRed, histogramGreen, histogramBlue, histogramAlpha] | |
return channels | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment