package com.example.myapplication import ImageCaptioner import…
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
package com.example.myapplication
import ImageCaptioner import ai.onnxruntime.OrtEnvironment import ai.onnxruntime.OrtSession import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.graphics.BitmapFactory import android.os.Bundle import android.util.Log import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.ui.Modifier import com.example.myapplication.ui.theme.MyApplicationTheme import android.graphics.ImageDecoder import android.media.Image import android.net.Uri import android.os.Build import android.provider.MediaStore import android.view.View import android.widget.Toast import androidx.activity.compose.rememberLauncherForActivityResult import androidx.annotation.RequiresApi import androidx.camera.core.CameraSelector import androidx.camera.core.ImageAnalysis import androidx.camera.core.ImageCapture import androidx.camera.core.ImageCaptureException import androidx.camera.view.LifecycleCameraController import androidx.camera.view.PreviewView import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.material3.Button import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.graphics.decodeToImageBitmap import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.compose.ui.unit.dp import androidx.compose.ui.viewinterop.AndroidView import androidx.lifecycle.lifecycleScope import com.example.blipcaptioning.BLIPInference import com.example.myapplication.SimpleTokenizer.Companion import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.asCoroutineDispatcher import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.io.BufferedReader import java.io.ByteArrayOutputStream import java.io.File import java.io.InputStream import java.io.InputStreamReader import java.util.concurrent.ExecutorService import java.util.concurrent.Executors import java.util.concurrent.atomic.AtomicBoolean
class MainActivity : ComponentActivity() {
private lateinit var context: Context
private lateinit var modelFile: File
private val TAG = "TAG"
private lateinit var imageCaptioner: ImageCaptioner
private lateinit var cameraExecutor: ExecutorService
private val processing = AtomicBoolean(false)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
context = applicationContext
cameraExecutor = Executors.newFixedThreadPool(1)
val cameraController = LifecycleCameraController(this)
cameraController.bindToLifecycle(this)
cameraController.cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
initialize()
cameraController.setImageAnalysisBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
cameraController.setImageAnalysisAnalyzer(
cameraExecutor
) { imageProxy ->
Log.d("debug", "trying to enter at ${System.currentTimeMillis()}")
if (!processing.compareAndSet(false,true)) {
Log.d("Debug", "processing.......")
imageProxy.close()
return@setImageAnalysisAnalyzer
}
Log.d("debug", processing.toString())
var bitmap = imageProxy.toBitmap()
val maxDimension = 1024
bitmap = resizeBitmap(bitmap,
minOf(bitmap.width, maxDimension),
minOf(bitmap.height, maxDimension))
imageProxy.close()
val bef = System.currentTimeMillis()
Log.d("debug", "Entered at $bef")
val caption = imageCaptioner.generateCaption(bitmap)
val time = System.currentTimeMillis() - bef
Log.d("time", (time).toString())
runOnUiThread {
Toast.makeText(this@MainActivity, "$caption $time", Toast.LENGTH_SHORT).show()
}
Log.d("Generated Caption", caption)
Log.d("debug", processing.toString())
processing.set(false)
Log.d("debug", processing.toString())
Log.d("debug", "Exited at ${System.currentTimeMillis()}")
}
setContent {
MyApplicationTheme {
Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(innerPadding),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Button(
onClick = {
galleryLauncher.launch("image/*")
}
) {
Text("Choose Image")
}
CameraPreview(cameraController)
}
}
}
}
}
fun initialize() {
var reverseVocab: MutableMap<Int, String> = mutableMapOf()
val inputStream = context.resources.openRawResource(R.raw.blip_vocab)
val reader = BufferedReader(InputStreamReader(inputStream))
var tokenId = 0
reader.forEachLine { line ->
val trimmedLine = line.trim()
if( trimmedLine.isNotEmpty() ){
when{
trimmedLine.contains('\t') -> {
val parts = trimmedLine.split('\t', limit = 2)
if(parts.size ==2 ){
val id = parts[0].toIntOrNull()
val token = parts[1]
if( id!=null) {
reverseVocab[id] = token
}
}
}
trimmedLine.contains(' ') -> {
val parts = trimmedLine.split(' ', limit = 2 )
val firstPartAsInt = parts[0].toIntOrNull()
if( firstPartAsInt != null && parts.size == 2 ){
val id = firstPartAsInt
val token = parts[1]
reverseVocab[id] = token
}
else{
// reverseVocab[id] = token tokenId++ } } else -> { // reverseVocab[id] = token tokenId++ } } }
}
reader.close()
Log.d(TAG, "Vocabulary loaded: tokens")
val ortEnvironment = OrtEnvironment.getEnvironment()
// Load vision encoder
val visionModelBytes = context.resources.openRawResource(R.raw.blip_vision_encoder_quantized).readBytes()
val visionSession = ortEnvironment!!.createSession(visionModelBytes)
Log.d(TAG, "Vision encoder loaded successfully")
// Load text decoder
val textModelBytes = context.resources.openRawResource(R.raw.blip_text_decoder_quantized).readBytes()
val textSession = ortEnvironment.createSession(textModelBytes)
Log.d(TAG, "Text decoder loaded successfully")
imageCaptioner = ImageCaptioner(
ortEnvironment,
visionSession,
textSession,
reverseVocab
)
}
private fun loadBitmapFromUri(uri: Uri): Bitmap? {
return try {
val inputStream = contentResolver.openInputStream(uri)
val bitmap = BitmapFactory.decodeStream(inputStream)
inputStream?.close()
// Fix: Use min instead of modulo operator
val maxDimension = 1024
resizeBitmap(bitmap,
minOf(bitmap.width, maxDimension),
minOf(bitmap.height, maxDimension))
} catch (e: Exception) {
Log.e(TAG, "Error loading bitmap from URI", e)
null
}
}
private fun resizeBitmap(bitmap: Bitmap, maxWidth: Int, maxHeight: Int): Bitmap {
val width = bitmap.width
val height = bitmap.height
if (width <= maxWidth && height <= maxHeight) {
return bitmap
}
val scaleWidth = maxWidth.toFloat() / width
val scaleHeight = maxHeight.toFloat() / height
val scale = minOf(scaleWidth, scaleHeight)
val newWidth = (width * scale).toInt()
val newHeight = (height * scale).toInt()
return Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true)
}
private val galleryLauncher = registerForActivityResult(ActivityResultContracts.GetContent()) {
val uri = it
if (it != null) {
val bitmap = try {
loadBitmapFromUri(it)
} catch (e: Exception) {
e.printStackTrace()
null
}
if(bitmap != null) {
val bef = System.currentTimeMillis()
lifecycleScope.launch{
// Add debugging
Log.d("Original", "Bitmap size: ${bitmap.width}x${bitmap.height}")
val caption = imageCaptioner.generateCaption(bitmap)
val time = System.currentTimeMillis() - bef
Log.d("time", time.toString())
Toast.makeText(context, caption+time.toString(), Toast.LENGTH_LONG).show()
Log.d("Generated Caption", caption)
}
}
Log.d(TAG, uri.toString())
}
else{
Log.i(TAG, "failed to fetch uri")
}
}
}
@Composable fun CameraPreview( cameraController: LifecycleCameraController) {
// Key Point: Displaying the Camera Preview
AndroidView(
modifier = Modifier.fillMaxSize(),
factory = { ctx ->
// Initialize the PreviewView and configure it
PreviewView(ctx).apply {
scaleType = PreviewView.ScaleType.FILL_START
implementationMode = PreviewView.ImplementationMode.COMPATIBLE
controller = cameraController // Set the controller to manage the camera lifecycle
}
},
onRelease = {
// Release the camera controller when the composable is removed from the screen
cameraController.unbind()
}
)
} I want to process a frame only after previous one processed, but
Okay, let's break down how to ensure you're processing camera frames sequentially, waiting for one to finish before starting the next, within your Android CameraX setup in Compose. The core idea is using a flag (like your processing AtomicBoolean) to prevent re-entry into the image analysis block until the previous analysis is complete. I will provide code and explanation for you.
Explanation of the Issue
The ImageAnalysis.Analyzer interface in CameraX is designed for asynchronous frame processing. It delivers frames as quickly as possible. If your image captioning process takes a significant amount of time, you can easily overwhelm the system by queuing up many analysis tasks before the previous ones finish. This can lead to performance problems and potentially incorrect results.
Core Idea: Mutual Exclusion
We use an AtomicBoolean called processing to act as a simple lock. The analyzer checks if processing is currently true. If it is, it means a previous frame is still being processed, so the analyzer immediately discards the current frame and returns. Only when processing is false does it attempt to acquire the lock, set processing to true, and begin processing the frame. Once done, it sets processing back to false, allowing the next frame to be processed.
Revised Code
write code for camera2api in kotlin android, where it should produce preview and analyzer gets every frame , where i can call my ml model such that it runs processing on only one image at atime, that too on latest ignoring thr frames genrated in between
package com.example.myapplication
import ImageCaptioner
import ai.onnxruntime.OrtEnvironment
import ai.onnxruntime.OrtSession
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.ui.Modifier
import com.example.myapplication.ui.theme.MyApplicationTheme
import android.graphics.ImageDecoder
import android.media.Image
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import android.view.View
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.annotation.RequiresApi
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCaptureException
import androidx.camera.view.LifecycleCameraController
import androidx.camera.view.PreviewView
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.material3.Button
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.decodeToImageBitmap
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.lifecycle.lifecycleScope
import com.example.blipcaptioning.BLIPInference
import com.example.myapplication.SimpleTokenizer.Companion
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.BufferedReader
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.InputStream
import java.io.InputStreamReader
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicBoolean
class MainActivity : ComponentActivity() {
private lateinit var context: Context
private lateinit var modelFile: File
private val TAG = "TAG"
private lateinit var imageCaptioner: ImageCaptioner
private lateinit var cameraExecutor: ExecutorService
private val processing = AtomicBoolean(false)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
context = applicationContext
cameraExecutor = Executors.newFixedThreadPool(1)
val cameraController = LifecycleCameraController(this)
cameraController.bindToLifecycle(this)
cameraController.cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
initialize()
cameraController.setImageAnalysisBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
cameraController.setImageAnalysisAnalyzer(
cameraExecutor
) { imageProxy ->
if (!processing.compareAndSet(false, true)) {
imageProxy.close()
return@setImageAnalysisAnalyzer
}
val bitmap = imageProxy.toBitmap()
imageProxy.close()
val maxDimension = 1024
val resizedBitmap = resizeBitmap(
bitmap,
minOf(bitmap.width, maxDimension),
minOf(bitmap.height, maxDimension)
)
lifecycleScope.launch(Dispatchers.IO) { // Use IO dispatcher for potentially blocking tasks
try {
val bef = System.currentTimeMillis()
val caption = imageCaptioner.generateCaption(resizedBitmap)
val time = System.currentTimeMillis() - bef
withContext(Dispatchers.Main) { // Switch back to Main dispatcher for UI updates
Toast.makeText(this@MainActivity, "$caption $time", Toast.LENGTH_SHORT).show()
Log.d("Generated Caption", caption)
}
} finally {
processing.set(false) // Release the lock in all cases
}
}
}
setContent {
MyApplicationTheme {
Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(innerPadding),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Button(
onClick = {
galleryLauncher.launch("image/*")
}
) {
Text("Choose Image")
}
CameraPreview(cameraController)
}
}
}
}
}
fun initialize() {
var reverseVocab: MutableMap<Int, String> = mutableMapOf()
val inputStream = context.resources.openRawResource(R.raw.blip_vocab)
val reader = BufferedReader(InputStreamReader(inputStream))
var tokenId = 0
reader.forEachLine { line ->
val trimmedLine = line.trim()
if( trimmedLine.isNotEmpty() ){
when{
trimmedLine.contains('\t') -> {
val parts = trimmedLine.split('\t', limit = 2)
if(parts.size ==2 ){
val id = parts[0].toIntOrNull()
val token = parts[1]
if( id!=null) {
reverseVocab[id] = token
}
}
}
trimmedLine.contains(' ') -> {
val parts = trimmedLine.split(' ', limit = 2 )
val firstPartAsInt = parts[0].toIntOrNull()
if( firstPartAsInt != null && parts.size == 2 ){
val id = firstPartAsInt
val token = parts[1]
reverseVocab[id] = token
}
else{
// reverseVocab[id] = token
tokenId++
}
}
else -> {
// reverseVocab[id] = token
tokenId++
}
}
}
}
reader.close()
Log.d(TAG, "Vocabulary loaded: tokens")
val ortEnvironment = OrtEnvironment.getEnvironment()
// Load vision encoder
val visionModelBytes = context.resources.openRawResource(R.raw.blip_vision_encoder_quantized).readBytes()
val visionSession = ortEnvironment!!.createSession(visionModelBytes)
Log.d(TAG, "Vision encoder loaded successfully")
// Load text decoder
val textModelBytes = context.resources.openRawResource(R.raw.blip_text_decoder_quantized).readBytes()
val textSession = ortEnvironment.createSession(textModelBytes)
Log.d(TAG, "Text decoder loaded successfully")
imageCaptioner = ImageCaptioner(
ortEnvironment,
visionSession,
textSession,
reverseVocab
)
}
private fun loadBitmapFromUri(uri: Uri): Bitmap? {
return try {
val inputStream = contentResolver.openInputStream(uri)
val bitmap = BitmapFactory.decodeStream(inputStream)
inputStream?.close()
// Fix: Use min instead of modulo operator
val maxDimension = 1024
resizeBitmap(bitmap,
minOf(bitmap.width, maxDimension),
minOf(bitmap.height, maxDimension))
} catch (e: Exception) {
Log.e(TAG, "Error loading bitmap from URI", e)
null
}
}
private fun resizeBitmap(bitmap: Bitmap, maxWidth: Int, maxHeight: Int): Bitmap {
val width = bitmap.width
val height = bitmap.height
if (width <= maxWidth && height <= maxHeight) {
return bitmap
}
val scaleWidth = maxWidth.toFloat() / width
val scaleHeight = maxHeight.toFloat() / height
val scale = minOf(scaleWidth, scaleHeight)
val newWidth = (width * scale).toInt()
val newHeight = (height * scale).toInt()
return Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true)
}
private val galleryLauncher = registerForActivityResult(ActivityResultContracts.GetContent()) {
val uri = it
if (it != null) {
val bitmap = try {
loadBitmapFromUri(it)
} catch (e: Exception) {
e.printStackTrace()
null
}
if(bitmap != null) {
val bef = System.currentTimeMillis()
lifecycleScope.launch{
// Add debugging
Log.d("Original", "Bitmap size: ${bitmap.width}x${bitmap.height}")
val caption = imageCaptioner.generateCaption(bitmap)
val time = System.currentTimeMillis() - bef
Log.d("time", time.toString())
Toast.makeText(context, caption+time.toString(), Toast.LENGTH_LONG).show()
Log.d("Generated Caption", caption)
}
}
Log.d(TAG, uri.toString())
}
else{
Log.i(TAG, "failed to fetch uri")
}
}
}
@Composable
fun CameraPreview( cameraController: LifecycleCameraController) {
// Key Point: Displaying the Camera Preview
AndroidView(
modifier = Modifier.fillMaxSize(),
factory = { ctx ->
// Initialize the PreviewView and configure it
PreviewView(ctx).apply {
scaleType = PreviewView.ScaleType.FILL_START
implementationMode = PreviewView.ImplementationMode.COMPATIBLE
controller = cameraController // Set the controller to manage the camera lifecycle
}
},
onRelease = {
// Release the camera controller when the composable is removed from the screen
cameraController.unbind()
}
)
}
Key Improvements and Explanation
compareAndSet for AtomicBoolean: The line if (!processing.compareAndSet(false, true)) is the heart of the mutual exclusion. compareAndSet atomically checks if the value of processing is currently false. If it is, it sets it to true and returns true. If it's already true, it does not change the value and returns false. This ensures that only one thread can transition processing from false to true at a time.compareAndSet returns false (meaning another frame is already being processed), the analyzer immediately calls imageProxy.close() and returns. This is crucial: you must close the ImageProxy when you're done with it. Failing to do so will quickly exhaust the available image buffers and cause the camera to stall.lifecycleScope.launch(Dispatchers.IO) { ... } block. This launches a coroutine on the Dispatchers.IO dispatcher, which is designed for performing blocking I/O operations (like your ONNX runtime calls) without blocking the main thread.finally Block for Releasing the Lock: I've added a finally block to ensure that processing.set(false) is always called, even if an exception occurs during the image captioning process. This prevents the application from getting stuck in a permanently "processing" state.withContext(Dispatchers.Main): The UI updates (showing the Toast and logging the caption) are done inside withContext(Dispatchers.Main). This ensures that these operations are performed on the main thread, which is required for updating the UI.How to Use
MainActivity.kt file, replacing your existing onCreate method.build.gradle.kts file (as shown in the original code).Important Considerations
ImageCaptioner class and ONNX model inference for speed.ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST. This is a good starting point, but experiment with other strategies (like STRATEGY_BLOCK_PRODUCER) to see if they offer better performance or responsiveness for your use case.This revised approach should give you a solid foundation for handling camera frames sequentially and efficiently in your Android app. Remember to monitor performance and adjust the code as needed to meet the specific requirements of your image captioning application.
package com.example.camera2ml
import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.PackageManager
import android.graphics.ImageFormat
import android.graphics.SurfaceTexture
import android.hardware.camera2.*
import android.media.ImageReader
import android.os.Bundle
import android.os.Handler
import android.os.HandlerThread
import android.util.Log
import android.util.Size
import android.view.Surface
import android.view.TextureView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import java.util.concurrent.Semaphore
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.math.min
class Camera2MLActivity : AppCompatActivity() {
private lateinit var textureView: TextureView
private lateinit var cameraId: String
private var cameraDevice: CameraDevice? = null
private var captureSession: CameraCaptureSession? = null
private lateinit var imageReader: ImageReader
private lateinit var previewSize: Size
private lateinit var backgroundThread: HandlerThread
private lateinit var backgroundHandler: Handler
private val cameraOpenCloseLock = Semaphore(1)
private val processing = AtomicBoolean(false)
// Replace with your ML model class/implementation
private lateinit var mlModel: MyMLModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_camera2_ml)
textureView = findViewById(R.id.textureView)
mlModel = MyMLModel(this) // Initialize your ML model
if (allPermissionsGranted()) {
textureView.surfaceTextureListener = surfaceTextureListener
} else {
ActivityCompat.requestPermissions(
this,
REQUIRED_PERMISSIONS,
REQUEST_CODE_PERMISSIONS
)
}
}
override fun onResume() {
super.onResume()
startBackgroundThread()
if (textureView.isAvailable) {
openCamera()
} else {
textureView.surfaceTextureListener = surfaceTextureListener
}
}
override fun onPause() {
closeCamera()
stopBackgroundThread()
super.onPause()
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == REQUEST_CODE_PERMISSIONS) {
if (allPermissionsGranted()) {
textureView.surfaceTextureListener = surfaceTextureListener
} else {
Toast.makeText(
this,
"Permissions not granted by the user.",
Toast.LENGTH_SHORT
).show()
finish()
}
}
}
private val surfaceTextureListener = object : TextureView.SurfaceTextureListener {
override fun onSurfaceTextureAvailable(texture: SurfaceTexture, width: Int, height: Int) {
openCamera()
}
override fun onSurfaceTextureSizeChanged(texture: SurfaceTexture, width: Int, height: Int) {
// Handle surface size changes if needed
}
override fun onSurfaceTextureDestroyed(texture: SurfaceTexture): Boolean {
return true
}
override fun onSurfaceTextureUpdated(texture: SurfaceTexture) {
// Called for every frame
}
}
@SuppressLint("MissingPermission")
private fun openCamera() {
val manager = getSystemService(Context.CAMERA_SERVICE) as CameraManager
try {
cameraOpenCloseLock.acquire()
cameraId = manager.cameraIdList[0] // Assuming back camera
val characteristics = manager.getCameraCharacteristics(cameraId)
val map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)!!
previewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture::class.java), textureView.width, textureView.height)
imageReader = ImageReader.newInstance(
previewSize.width, previewSize.height,
ImageFormat.YUV_420_888, 2 // Reduced maxImages to 2.
).apply {
setOnImageAvailableListener(imageAvailableListener, backgroundHandler)
}
manager.openCamera(cameraId, stateCallback, backgroundHandler)
} catch (e: CameraAccessException) {
Log.e(TAG, "Camera Access Exception: ${e.message}")
} catch (e: InterruptedException) {
throw RuntimeException("Interrupted while trying to lock camera opening.", e)
} finally {
cameraOpenCloseLock.release()
}
}
private val stateCallback = object : CameraDevice.StateCallback() {
override fun onOpened(camera: CameraDevice) {
cameraOpenCloseLock.release()
cameraDevice = camera
createCameraPreviewSession()
}
override fun onDisconnected(camera: CameraDevice) {
cameraOpenCloseLock.release()
cameraDevice?.close()
cameraDevice = null
}
override fun onError(camera: CameraDevice, error: Int) {
cameraOpenCloseLock.release()
cameraDevice?.close()
cameraDevice = null
finish()
}
}
private fun createCameraPreviewSession() {
try {
val texture = textureView.surfaceTexture.apply {
setDefaultBufferSize(previewSize.width, previewSize.height)
}
val surface = Surface(texture)
val captureRequestBuilder = cameraDevice!!.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW).apply {
addTarget(surface)
addTarget(imageReader.surface) // Add ImageReader surface
}
cameraDevice?.createCaptureSession(
listOf(surface, imageReader.surface),
object : CameraCaptureSession.StateCallback() {
override fun onConfigured(session: CameraCaptureSession) {
captureSession = session
captureRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE)
try {
captureSession?.setRepeatingRequest(captureRequestBuilder.build(), null, backgroundHandler)
} catch (e: CameraAccessException) {
Log.e(TAG, "Capture Session Exception: ${e.message}")
}
}
override fun onConfigureFailed(session: CameraCaptureSession) {
Toast.makeText(this@Camera2MLActivity, "Configuration failed", Toast.LENGTH_SHORT).show()
}
},
null
)
} catch (e: CameraAccessException) {
Log.e(TAG, "Capture Session creation exception: ${e.message}")
}
}
private val imageAvailableListener = ImageReader.OnImageAvailableListener { reader ->
val image = reader.acquireLatestImage() ?: return@OnImageAvailableListener // get the latest image
if (!processing.compareAndSet(false, true)) {
image.close()
return@OnImageAvailableListener
}
backgroundHandler.post {
try {
//Process the image
mlModel.processImage(image) { result ->
runOnUiThread {
Toast.makeText(this@Camera2MLActivity, result, Toast.LENGTH_SHORT).show()
}
}
} finally {
image.close()
processing.set(false)
}
}
}
private fun closeCamera() {
try {
cameraOpenCloseLock.acquire()
captureSession?.close()
captureSession = null
cameraDevice?.close()
cameraDevice = null
imageReader.close()
} catch (e: InterruptedException) {
throw RuntimeException("Interrupted while trying to lock camera closing.", e)
} finally {
cameraOpenCloseLock.release()
}
}
private fun startBackgroundThread() {
backgroundThread = HandlerThread("CameraBackground").also { it.start() }
backgroundHandler = Handler(backgroundThread.looper)
}
private fun stopBackgroundThread() {
backgroundThread.quitSafely()
try {
backgroundThread.join()
} catch (e: InterruptedException) {
Log.e(TAG, "Error stopping background thread: ${e.message}")
}
}
private fun allPermissionsGranted() = REQUIRED_PERMISSIONS.all {
ContextCompat.checkSelfPermission(baseContext, it) == PackageManager.PERMISSION_GRANTED
}
// Helper function to choose optimal size
private fun chooseOptimalSize(choices: Array<Size>, textureViewWidth: Int, textureViewHeight: Int): Size {
val bigEnough = choices.filter {
it.height == it.width * textureViewHeight / textureViewWidth &&
it.width >= textureViewWidth && it.height >= textureViewHeight
}
return if (bigEnough.isNotEmpty()) {
min(bigEnough.minOf { it.width }, bigEnough.minOf { it.height }).let { w -> bigEnough.first { it.width == w } }
} else {
choices[0] // If not big enough, fallback to the first choice
}
}
companion object {
private const val TAG = "Camera2ML"
private const val REQUEST_CODE_PERMISSIONS = 10
private val REQUIRED_PERMISSIONS = arrayOf(Manifest.permission.CAMERA)
}
}
// Placeholder for your ML Model implementation
class MyMLModel(private val context: Context) {
fun processImage(image: android.media.Image, callback: (String) -> Unit) {
//Convert media.image to bitmap
val buffer = image.planes[0].buffer
val bytes = ByteArray(buffer.capacity())
buffer.get(bytes)
val pixels = bytesToPixels(bytes, image.width, image.height)
Thread {
// Simulate ML processing (replace with your actual model call)
Thread.sleep(200)
val result = "Processed image: ${image.width}x${image.height}"
callback(result)
}.start()
}
fun bytesToPixels(data: ByteArray, width: Int, height: Int): IntArray {
val pixels = IntArray(width * height)
for (y in 0 until height) {
for (x in 0 until width) {
val index = y * width + x
val yValue = data[index and 0xff].toInt()
pixels[index] = -0x1000000 or (yValue shl 16) or (yValue shl 8) or yValue
}
}
return pixels
}
}
Explanation and Key Improvements:
activity_camera2_ml.xml Layout: Make sure you have a layout file (activity_camera2_ml.xml) containing a TextureView with the ID textureView.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Camera2MLActivity">
<TextureView
android:id="@+id/textureView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Permissions Handling: The code includes explicit permission checks and requests for the camera. This is critical.
Background Thread: The code sets up a background thread with a Handler to perform camera operations and ML processing off the main thread.
TextureView: Uses TextureView for displaying the camera preview. The surfaceTextureListener handles the lifecycle of the SurfaceTexture.
Camera Initialization and Setup:
openCamera(): Opens the camera, configures ImageReader, and sets up the necessary CaptureRequest.createCameraPreviewSession(): Creates a CameraCaptureSession to stream the preview and receive image data. Critically, it adds imageReader.surface as a target to receive frames.stateCallback: Handles the state changes of the CameraDevice.ImageReader and OnImageAvailableListener:
ImageReader: Is configured to acquire image frames in YUV_420_888 format. You can adjust this format if your ML model requires a different input. The maxImages is set to 2 to provide some buffering but prevent excessive queueing.onImageAvailableListener: This is the core of the frame processing logic. It's triggered whenever a new image is available from the camera.Frame Dropping with AtomicBoolean:
processing AtomicBoolean ensures that only one frame is processed at a time. If a frame arrives while the previous one is still being processed, it's immediately dropped (image.close(); return@OnImageAvailableListener).image.close() is essential to release the image buffer and prevent the camera from stalling.ML Model Integration:
MyMLModel class is provided. You must replace this with your actual ML model loading and inference code. The processImage function should take the Image object, perform the necessary preprocessing (convert it to a Bitmap or the required format), run the inference, and return the result.processImage function is thread-safe.Switching to other thread using Handler
AcquireLatestImage instead of AcquireNextImage
AcquireLatestImage gives the latest image instead of queueing up all the imagesTo integrate your ML Model:
MyMLModel: Replace the MyMLModel class with your actual ML model class.MyMLModel.processImage, you'll need to convert the android.media.Image to a format suitable for your ML model (e.g., Bitmap, ByteBuffer). This might involve:
image.planes).Bitmap from the byte array.callback function.Key points:
This complete example should give you a very solid base to integrate your ML model with the Camera2 API. Remember to adapt the image preprocessing and model inference code to the specific requirements of your ML model. Good luck!