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
To ensure that frames are processed sequentially (only processing a new frame after the previous one has finished processing), you need to properly manage the processing flag and the camera analysis callback. Here's how you can modify your code to achieve this:
processing flag - Ensure it's only set to false after all processing is complete.// In your MainActivity class
private val cameraExecutor: ExecutorService = Executors.newSingleThreadExecutor()
private val processing = AtomicBoolean(false)
// Inside your onCreate method where you set up the camera analysis:
cameraController.setImageAnalysisAnalyzer(cameraExecutor) { imageProxy ->
try {
if (processing.compareAndSet(false, true)) {
Log.d("debug", "Starting processing at ${System.currentTimeMillis()}")
// Convert to bitmap and resize
val bitmap = imageProxy.toBitmap()
val maxDimension = 1024
val resizedBitmap = resizeBitmap(
bitmap,
minOf(bitmap.width, maxDimension),
minOf(bitmap.height, maxDimension)
)
imageProxy.close() // Close the image proxy as soon as we're done with it
// Process the image
val startTime = System.currentTimeMillis()
val caption = imageCaptioner.generateCaption(resizedBitmap)
val processingTime = System.currentTimeMillis() - startTime
Log.d("debug", "Processing completed in $processingTime ms")
// Update UI
runOnUiThread {
Toast.makeText(
this@MainActivity,
"Caption: $caption (${processingTime}ms)",
Toast.LENGTH_SHORT
).show()
}
} else {
Log.d("debug", "Skipping frame - still processing previous one")
imageProxy.close() // Always close the image proxy
}
} catch (e: Exception) {
Log.e("debug", "Error processing image", e)
processing.set(false)
imageProxy.close()
} finally {
processing.set(false)
Log.d("debug", "Processing flag set to false")
}
}
Single Thread Executor: Using Executors.newSingleThreadExecutor() ensures all analysis happens on the same thread sequentially.
:
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
Here's a complete implementation using Camera2 API in Kotlin that provides a camera preview and processes frames one at a time, always using the latest frame and ignoring intermediate ones:
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.ImageFormat
import android.graphics.SurfaceTexture
import android.hardware.camera2.*
import android.media.Image
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
class Camera2Activity : AppCompatActivity() {
private lateinit var textureView: TextureView
private lateinit var cameraManager: CameraManager
private lateinit var cameraId: String
private lateinit var cameraDevice: CameraDevice
private lateinit var captureSession: CameraCaptureSession
private lateinit var imageReader: ImageReader
private lateinit var backgroundHandler: Handler
private lateinit var backgroundThread: HandlerThread
private val processing = AtomicBoolean(false)
private val cameraOpenCloseLock = Semaphore(1)
private var previewSize: Size? = null
private val TAG = "Camera2Activity"
private val REQUEST_CAMERA_PERMISSION = 1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_camera2)
textureView = findViewById(R.id.textureView)
cameraManager = getSystemService(Context.CAMERA_SERVICE) as CameraManager
// Check and request camera permission
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.CAMERA),
REQUEST_CAMERA_PERMISSION
)
} else {
startBackgroundThread()
setupCamera()
}
}
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)
}
}
private fun setupCamera() {
try {
cameraId = cameraManager.cameraIdList[0] // Use the first back-facing camera
val characteristics = cameraManager.getCameraCharacteristics(cameraId)
// Get the best preview size
val map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)
previewSize = map?.getOutputSizes(SurfaceTexture::class.java)?.maxByOrNull {
it.width * it.height
}
// Configure the texture view
textureView.surfaceTextureListener = object : TextureView.SurfaceTextureListener {
override fun onSurfaceTextureAvailable(surface: SurfaceTexture, width: Int, height: Int) {
openCamera()
}
override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture, width: Int, height: Int) {}
override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean = false
override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {}
}
// Create ImageReader for frame analysis
val imageReaderSize = Size(640, 480) // Adjust size as needed for your ML model
imageReader = ImageReader.newInstance(
imageReaderSize.width,
imageReaderSize.height,
ImageFormat.YUV_420_888,
2 // Max images to buffer
).apply {
setOnImageAvailableListener(onImageAvailableListener, backgroundHandler)
}
} catch (e: CameraAccessException) {
Log.e(TAG, "Camera access exception", e)
} catch (e: Exception) {
Log.e(TAG, "Error setting up camera", e)
}
}
private val onImageAvailableListener = ImageReader.OnImageAvailableListener { reader ->
try {
// Only process if we're not already processing
if (processing.compareAndSet(false, true)) {
val image = reader.acquireLatestImage() ?: return@OnImageAvailableListener
// Convert to Bitmap and process
val bitmap = image.toBitmap()
image.close()
// Process the frame (this will run on background thread)
processFrame(bitmap)
} else {
// Skip this frame since we're still processing the previous one
reader.acquireLatestImage()?.close()
}
} catch (e: Exception) {
Log.e(TAG, "Error processing image", e)
processing.set(false)
}
}
private fun processFrame(bitmap: Bitmap) {
try {
// Your ML model processing here
val startTime = System.currentTimeMillis()
// Example: Call your image captioner
// val caption = imageCaptioner.generateCaption(bitmap)
// Simulate processing time
Thread.sleep(500) // Remove this in your actual implementation
val processingTime = System.currentTimeMillis() - startTime
Log.d(TAG, "Processed frame in $processingTime ms")
runOnUiThread {
Toast.makeText(
this,
"Processed frame in $processingTime ms",
Toast.LENGTH_SHORT
).show()
}
} catch (e: Exception) {
Log.e(TAG, "Error processing frame", e)
} finally {
processing.set(false)
}
}
private fun openCamera() {
try {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
return
}
cameraOpenCloseLock.acquire()
cameraManager.openCamera(cameraId, object : CameraDevice.StateCallback() {
override fun onOpened(camera: CameraDevice) {
cameraOpenCloseLock.release()
cameraDevice = camera
createCameraPreviewSession()
}
override fun onDisconnected(camera: CameraDevice) {
cameraOpenCloseLock.release()
cameraDevice.close()
}
override fun onError(camera: CameraDevice, error: Int) {
cameraOpenCloseLock.release()
cameraDevice.close()
Log.e(TAG, "Camera error: $error")
}
}, backgroundHandler)
} catch (e: CameraAccessException) {
Log.e(TAG, "Cannot access camera", e)
} catch (e: InterruptedException) {
Log.e(TAG, "Interrupted while trying to lock camera opening", e)
}
}
private fun createCameraPreviewSession() {
try {
val texture = textureView.surfaceTexture
texture?.setDefaultBufferSize(previewSize?.width ?: 1080, previewSize?.height ?: 1920)
val surface = Surface(texture)
val previewRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW)
previewRequestBuilder.addTarget(surface)
previewRequestBuilder.addTarget(imageReader.surface)
cameraDevice.createCaptureSession(
listOf(surface, imageReader.surface),
object : CameraCaptureSession.StateCallback() {
override fun onConfigured(session: CameraCaptureSession) {
if (cameraDevice == null) return
captureSession = session
try {
previewRequestBuilder.set(
CaptureRequest.CONTROL_AF_MODE,
CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE
)
previewRequestBuilder.set(
CaptureRequest.CONTROL_AE_MODE,
CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH
)
captureSession.setRepeatingRequest(
previewRequestBuilder.build(),
null,
backgroundHandler
)
} catch (e: CameraAccessException) {
Log.e(TAG, "Failed to start camera preview", e)
}
}
override fun onConfigureFailed(session: CameraCaptureSession) {
Log.e(TAG, "Failed to configure camera")
}
},
backgroundHandler
)
} catch (e: CameraAccessException) {
Log.e(TAG, "Failed to create camera preview session", e)
}
}
private fun Image.toBitmap(): Bitmap {
val yBuffer = planes[0].buffer
val uBuffer = planes[1].buffer
val vBuffer = planes[2].buffer
val ySize = yBuffer.remaining()
val uSize = uBuffer.remaining()
val vSize = vBuffer.remaining()
val nv21 = ByteArray(ySize + uSize + vSize)
yBuffer.get(nv21, 0, ySize)
vBuffer.get(nv21, ySize, vSize)
uBuffer.get(nv21, ySize + vSize, uSize)
val yuvImage = android.graphics.YuvImage(
nv21, ImageFormat.NV21,
this.width, this.height, null
)
val out = ByteArrayOutputStream()
yuvImage.compressToJpeg(
Rect(0, 0, yuvImage.width, yuvImage.height),
100, out
)
val imageBytes = out.toByteArray()
return BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size)
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == REQUEST_CAMERA_PERMISSION) {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startBackgroundThread()
setupCamera()
} else {
Toast.makeText(this, "Camera permission is required", Toast.LENGTH_SHORT).show()
finish()
}
}
}
override fun onResume() {
super.onResume()
if (textureView.isAvailable) {
openCamera()
} else {
textureView.surfaceTextureListener = object : TextureView.SurfaceTextureListener {
override fun onSurfaceTextureAvailable(surface: SurfaceTexture, width: Int, height: Int) {
openCamera()
}
override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture, width: Int, height: Int) {}
override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean = false
override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {}
}
}
}
override fun onPause() {
super.onPause()
try {
cameraOpenCloseLock.acquire()
captureSession?.close()
cameraDevice?.close()
} catch (e: InterruptedException) {
Log.e(TAG, "Interrupted while trying to lock camera closing", e)
} finally {
cameraOpenCloseLock.release()
}
}
override fun onDestroy() {
super.onDestroy()
stopBackgroundThread()
}
}
true at the start of processingfalse only after all processing is complete (in the finally block)ImageProxy Handling:
ImageProxy in all code pathsError Handling:
finally block ensures the flag is always resetPerformance Considerations:
If you need more control over frame processing, you could implement a queue system:
private val frameQueue = LinkedBlockingQueue<Bitmap>(1) // Queue with capacity 1
// In your camera analysis callback:
if (frameQueue.offer(bitmap)) { // Returns true if added to queue
// Process the frame
}
// Then have a separate processing thread that takes from the queue
This would give you more control over frame processing and could help with frame management in more complex scenarios.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextureView
android:id="@+id/textureView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
AtomicBoolean to ensure only one frame is processed at a timeacquireLatestImage() to always get the most recent frame and discard intermediate onesprocessFrame method with your actual ML model processing codeimageReaderSize to match your model's input requirementsThis implementation ensures that your ML model will only process one frame at a time, always using the latest available frame while ignoring intermediate ones.