I try to understand the "Getting Started with CameraX" tutorial in particular the image analysis.
typealias LumaListener = (luma: Double) -> Unit
class LuminosityAnalyzer(private val listener: LumaListener) : ImageAnalysis.Analyzer {
private fun ByteBuffer.toByteArray(): ByteArray {
rewind() // Rewind the buffer to zero
val data = ByteArray(remaining())
get(data) // Copy the buffer into a byte array
return data // Return the byte array
}
override fun analyze(image: ImageProxy) {
val buffer = image.planes[0].buffer
val data = buffer.toByteArray()
val pixels = data.map { it.toInt() and 0xFF }
val luma = pixels.average()
listener(luma)
image.close()
}
}
I have compiled the example from step "6. Implement ImageAnalysis use case" and I think it works as expected.
This is some of my log data:
19:26:08.152 D Average luminosity: 105.57404947916666
19:26:08.190 D Average luminosity: 105.57047526041667
19:26:08.240 D Average luminosity: 105.60593424479167
19:26:08.273 D Average luminosity: 105.60776041666666
19:26:08.305 D Average luminosity: 105.60956380208333
19:26:08.346 D Average luminosity: 105.60956380208333
19:26:08.388 D Average luminosity: 105.61209635416667
19:26:08.431 D Average luminosity: 105.61344075520833
Every 30 to 50 ms a frame gets analyzed. It works fine but eats up all CPU time.
How to put back-pressure on the camera to slow down the analyzing?
Update: It is possible to configure the back-pressure strategy, but this is not sufficient. The function seems to be a misnomer, because the pressure never reaches the camera. The back-pressure strategy specifies, what happens, if the camera produces frames faster than the analyzer can analyze them. In this case you have two options: queue the overflow frames or throw them away, which is the default. But this has no impact on the camera, because the camera still produces too many frames. The CPU is still highly utilized with the task to generate frames, which are just thrown away. This will happen, if I call sleep
at the end of the analyze function.
I am looking for a way to tell the camera to produce fewer frames.