iOS Swift中如何获取CVBuffer的亮度/光强度?
iOS中通过Swift获取CVBuffer的光强度
以下是实现从CVBuffer中提取光强度的Swift代码,适用于iOS应用开发:
func fetchLightIntensity(from pixelBuffer: CVPixelBuffer) { CVPixelBufferLockBaseAddress(pixelBuffer, .readOnly) if let baseAddress = CVPixelBufferGetBaseAddress(pixelBuffer) { let width = CVPixelBufferGetWidth(pixelBuffer) let height = CVPixelBufferGetHeight(pixelBuffer) let bytesPerRow = CVPixelBufferGetBytesPerRow(pixelBuffer) let buffer = baseAddress.assumingMemoryBound(to: UInt8.self) var totalIntensity: UInt32 = 0 for y in 0..<height { let row = buffer.advanced(by: y * bytesPerRow) for x in 0..<width { let pixel = row.advanced(by: x) let intensity = UInt32(pixel.pointee) totalIntensity += intensity } } let averageIntensity = totalIntensity / UInt32(width * height) // 转换为0-100范围的光强度值 let rangeIntensity = (averageIntensity * 100) / 255 // 将结果存入全局变量 lightIntensity = rangeIntensity print("Light Intensity : \(self.lightIntensity)") } CVPixelBufferUnlockBaseAddress(pixelBuffer, .readOnly) }
关键说明:
- 操作CVBuffer前必须调用
CVPixelBufferLockBaseAddress,操作完成后调用CVPixelBufferUnlockBaseAddress,保证缓冲区的访问安全 - 代码默认像素格式为单通道UInt8灰度图,如果你的CVBuffer是RGBA等多通道格式,需要修改像素读取逻辑(比如取RGB通道的平均值作为强度)
- 通过遍历所有像素计算总强度,再求平均值,最后转换为0-100的直观范围值
- 最终结果存入全局变量
lightIntensity,可根据需求调整存储方式
内容的提问来源于stack exchange,提问作者Suleman Tariq
相关产品推荐
相关产品推荐

