How to get the luminosity/light intensity of CVBuffer in swift iOS

41 Views Asked by At

I am working on an iOS application which fetches the light intensity of CVBuffer in swift.

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)

        // Calculate light intensity in the range of 0 to 100
        let rangeIntensity = (averageIntensity * 100) / 255

        // Store light intensity in the global variable
        lightIntensity = rangeIntensity
        print("Light Intensity : \(self.lightIntensity)")
    }

    CVPixelBufferUnlockBaseAddress(pixelBuffer, .readOnly)
}`
0

There are 0 best solutions below