我尝试获取 CVPixelBuffer 的平均亮度,但该函数在处理几行后崩溃并显示 EXC_BAD_ACCESS 消息。
我想我不明白如何使用Apple的YpCbCr8BiPlanar格式。
这是我的功能。知道我做错了什么吗?
func averageLuminance(pixelBuffer: CVPixelBuffer) -> Float? {
guard CVPixelBufferGetPixelFormatType(pixelBuffer) == kCVPixelFormatType_Lossy_420YpCbCr8BiPlanarFullRange else {
print("Pixel buffer format mismatch.")
return nil
}
CVPixelBufferLockBaseAddress(pixelBuffer, .readOnly)
defer { CVPixelBufferUnlockBaseAddress(pixelBuffer, .readOnly) }
guard let baseAddress = CVPixelBufferGetBaseAddressOfPlane(pixelBuffer, 0) else {
print("Unable to get base address.")
return nil
}
let lumaWidth = CVPixelBufferGetWidthOfPlane(pixelBuffer, 0)
let lumaHeight = CVPixelBufferGetHeightOfPlane(pixelBuffer, 0)
let lumaRowBytes = CVPixelBufferGetBytesPerRowOfPlane(pixelBuffer, 0)
var totalLuminance: Float = 0.0
for row in 0..<lumaHeight {
let rowBaseAddress = baseAddress.advanced(by: row * lumaRowBytes)
let rowPointer = rowBaseAddress.assumingMemoryBound(to: UInt8.self)
var rowSum: Float = 0.0
for col in 0..<lumaWidth {
rowSum += Float(rowPointer[col])
}
let rowAverageLuminance = rowSum / Float(lumaWidth)
totalLuminance += rowAverageLuminance
}
let averageLuminance = totalLuminance / Float(lumaHeight)
return averageLuminance
}
有损类型使用小于8bit来描述一个像素,所以我使用非压缩类型来避免这个问题