CameraX for camera operations and ML Kit for on-device machine learning.
CameraX Overview
# Dependencies
implementation("androidx.camera:camera-core:1.3.3")
implementation("androidx.camera:camera-camera2:1.3.3")
implementation("androidx.camera:camera-lifecycle:1.3.3")
implementation("androidx.camera:camera-view:1.3.3")
implementation("androidx.camera:camera-video:1.3.3")
implementation("androidx.camera:camera-mlkit-vision:1.3.3")Camera Setup
class CameraRepository @Inject constructor(
@ApplicationContext private val context: Context
) {
// Camera provider
suspend fun getCameraProvider(): ProcessCameraProvider = withContext(Dispatchers.IO) {
ProcessCameraProvider.getInstance(context).await()
}
// Preview use case
fun createPreview(surfaceProvider: Preview.SurfaceProvider): Preview {
return Preview.Builder()
.setTargetAspectRatio(AspectRatio.RATIO_4_3)
.setTargetRotation(surfaceProvider.getRotation())
.build()
.also { it.setSurfaceProvider(surfaceProvider) }
}
// Image capture use case
fun createImageCapture(): ImageCapture {
return ImageCapture.Builder()
.setTargetRotation(viewFinder.display.rotation)
.setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY)
.setFlashMode(ImageCapture.FLASH_MODE_AUTO)
.build()
}
// Video capture use case
fun createVideoCapture(): VideoCapture<Recorder> {
val recorder = Recorder.Builder()
.setQualitySelector(QualitySelector.from(Quality.HIGHEST))
.build()
return VideoCapture.Builder(recorder)
.setTargetRotation(viewFinder.display.rotation)
.build()
}
// Image analysis use case (for ML Kit)
fun createImageAnalysis(
analyzer: ImageAnalysis.Analyzer
): ImageAnalysis {
return ImageAnalysis.Builder()
.setTargetRotation(viewFinder.display.rotation)
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
.build()
.also { it.setAnalyzer(cameraExecutor, analyzer) }
}
private val cameraExecutor = Executors.newSingleThreadExecutor()
}CameraX in Compose
@Composable
fun CameraPreview(
modifier: Modifier = Modifier,
onImageCaptured: (ImageProxy) -> Unit
) {
val context = LocalContext.current
val lifecycle = LocalLifecycleOwner.current.lifecycle
val viewFinder = remember { PreviewView(context).apply {
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
}}
var imageCapture by remember { mutableStateOf<ImageCapture?>(null) }
var camera by remember { mutableStateOf<Camera?>(null) }
// Bind to lifecycle
LaunchedEffect(lifecycle) {
val cameraProvider = ProcessCameraProvider.getInstance(context).await()
val preview = Preview.Builder()
.setTargetAspectRatio(AspectRatio.RATIO_4_3)
.build()
.also { it.setSurfaceProvider(viewFinder.surfaceProvider) }
imageCapture = ImageCapture.Builder()
.setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY)
.build()
val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
try {
cameraProvider.unbindAll()
camera = cameraProvider.bindToLifecycle(
lifecycle, cameraSelector, preview, imageCapture
)
} catch (e: Exception) {
// Handle error
}
}
// Cleanup
DisposableEffect(lifecycle) {
onDispose {
camera?.let { cameraProvider.unbind(it) }
}
}
AndroidView(
modifier = modifier,
factory = { viewFinder },
update = { it.updateLayoutParams() }
)
}
// Capture photo
fun capturePhoto(imageCapture: ImageCapture, outputFile: File) {
val outputOptions = ImageCapture.OutputFileOptions.Builder(outputFile).build()
imageCapture.takePicture(
outputOptions,
Executors.mainThreadExecutor(),
object : ImageCapture.OnImageSavedCallback {
override fun onError(exc: ImageCaptureException) { }
override fun onImageSaved(output: ImageCapture.OutputFileResults) { }
}
)
}ML Kit Integration
# ML Kit dependencies
implementation("com.google.mlkit:barcode-scanning:17.2.0")
implementation("com.google.mlkit:text-recognition:19.0.0")
implementation("com.google.mlkit:face-detection:17.1.0")
implementation("com.google.mlkit:image-labeling:17.0.8")
implementation("com.google.mlkit:object-detection-custom:17.0.1")
implementation("com.google.mlkit:pose-detection:17.0.0")
implementation("com.google.mlkit:subject-segmentation:17.0.0")Barcode Scanning
class BarcodeAnalyzer @Inject constructor(
private val barcodeScanner: BarcodeScanner
) : ImageAnalysis.Analyzer {
override fun analyze(imageProxy: ImageProxy) {
val mediaImage = imageProxy.image ?: return
val rotation = imageProxy.imageInfo.rotationDegrees
val inputImage = InputImage.fromMediaImage(mediaImage, rotation)
barcodeScanner.process(inputImage)
.addOnSuccessListener { barcodes ->
for (barcode in barcodes) {
val bounds = barcode.boundingBox
val corners = barcode.cornerPoints
val rawValue = barcode.rawValue
val valueType = barcode.valueType
// Handle barcode
handleBarcode(barcode)
}
}
.addOnFailureListener { e ->
Log.e("BarcodeAnalyzer", "Error", e)
}
.addOnCompleteListener {
imageProxy.close()
}
}
private fun handleBarcode(barcode: Barcode) {
when (barcode.valueType) {
Barcode.TYPE_URL -> openUrl(barcode.rawValue!!)
Barcode.TYPE_CONTACT_INFO -> saveContact(barcode.contactInfo!!)
Barcode.TYPE_WIFI -> connectWifi(barcode.wifi!!)
else -> Log.d("Barcode", "Scanned: ${barcode.rawValue}")
}
}
}
// Setup
val options = BarcodeScannerOptions.Builder()
.setBarcodeFormats(
Barcode.FORMAT_QR_CODE,
Barcode.FORMAT_AZTEC,
Barcode.FORMAT_DATA_MATRIX
)
.build()
val barcodeScanner = BarcodeScanning.getClient(options)Text Recognition
class TextRecognizer @Inject constructor(
private val textRecognizer: TextRecognizer
) : ImageAnalysis.Analyzer {
override fun analyze(imageProxy: ImageProxy) {
val mediaImage = imageProxy.image ?: return
val rotation = imageProxy.imageInfo.rotationDegrees
val inputImage = InputImage.fromMediaImage(mediaImage, rotation)
textRecognizer.process(inputImage)
.addOnSuccessListener { text ->
val fullText = text.text
for (block in text.textBlocks) {
val blockText = block.text
val blockCornerPoints = block.cornerPoints
val blockFrame = block.boundingBox
for (line in block.lines) {
val lineText = line.text
val lineCornerPoints = line.cornerPoints
val lineFrame = line.boundingBox
for (element in line.elements) {
val elementText = element.text
// Process element
}
}
}
}
.addOnCompleteListener { imageProxy.close() }
}
}
// Cloud vs On-device
// On-device (fast, offline):
val textRecognizer = TextRecognition.getClient(TextRecognizerOptions.DEFAULT_OPTIONS)
// Cloud (more accurate, requires network):
val cloudTextRecognizer = TextRecognition.getClient(
CloudTextRecognizerOptions.Builder().build()
)Face Detection
class FaceAnalyzer @Inject constructor(
private val faceDetector: FaceDetector
) : ImageAnalysis.Analyzer {
override fun analyze(imageProxy: ImageProxy) {
val mediaImage = imageProxy.image ?: return
val rotation = imageProxy.imageInfo.rotationDegrees
val inputImage = InputImage.fromMediaImage(mediaImage, rotation)
faceDetector.process(inputImage)
.addOnSuccessListener { faces ->
for (face in faces) {
val bounds = face.boundingBox
val leftEye = face.getLandmark(FaceLandmark.LEFT_EYE)
val rightEye = face.getLandmark(FaceLandmark.RIGHT_EYE)
val nose = face.getLandmark(FaceLandmark.NOSE_BASE)
val mouth = face.getLandmark(FaceLandmark.MOUTH_BOTTOM)
val smileProb = face.smilingProbability
val leftEyeOpen = face.leftEyeOpenProbability
val rightEyeOpen = face.rightEyeOpenProbability
val headEulerAngleX = face.headEulerAngleX // Pitch
val headEulerAngleY = face.headEulerAngleY // Yaw
val headEulerAngleZ = face.headEulerAngleZ // Roll
// Track face
trackFace(face)
}
}
.addOnCompleteListener { imageProxy.close() }
}
}
val options = FaceDetectorOptions.Builder()
.setPerformanceMode(FaceDetectorOptions.PERFORMANCE_MODE_FAST)
.setLandmarkMode(FaceDetectorOptions.LANDMARK_MODE_ALL)
.setClassificationMode(FaceDetectorOptions.CLASSIFICATION_MODE_ALL)
.setContourMode(FaceDetectorOptions.CONTOUR_MODE_ALL)
.build()
val faceDetector = FaceDetection.getClient(options)Pose Detection
class PoseAnalyzer @Inject constructor(
private val poseDetector: PoseDetector
) : ImageAnalysis.Analyzer {
override fun analyze(imageProxy: ImageProxy) {
val mediaImage = imageProxy.image ?: return
val rotation = imageProxy.imageInfo.rotationDegrees
val inputImage = InputImage.fromMediaImage(mediaImage, rotation)
poseDetector.process(inputImage)
.addOnSuccessListener { pose ->
val landmarks = pose.getAllPoseLandmarks()
// Key landmarks
val nose = landmarks[PoseLandmark.NOSE]
val leftShoulder = landmarks[PoseLandmark.LEFT_SHOULDER]
val rightShoulder = landmarks[PoseLandmark.RIGHT_SHOULDER]
val leftHip = landmarks[PoseLandmark.LEFT_HIP]
val rightHip = landmarks[PoseLandmark.RIGHT_HIP]
val leftKnee = landmarks[PoseLandmark.LEFT_KNEE]
val rightKnee = landmarks[PoseLandmark.RIGHT_KNEE]
val leftAnkle = landmarks[PoseLandmark.LEFT_ANKLE]
val rightAnkle = landmarks[PoseLandmark.RIGHT_ANKLE]
// Calculate angles, detect poses
analyzePose(landmarks)
}
.addOnCompleteListener { imageProxy.close() }
}
}
val options = PoseDetectorOptions.Builder()
.setDetectorMode(PoseDetectorOptions.STREAM_MODE)
.build()
val poseDetector = PoseDetection.getClient(options)Object Detection & Segmentation
class ObjectAnalyzer @Inject constructor(
private val objectDetector: ObjectDetector
) : ImageAnalysis.Analyzer {
override fun analyze(imageProxy: ImageProxy) {
val mediaImage = imageProxy.image ?: return
val rotation = imageProxy.imageInfo.rotationDegrees
val inputImage = InputImage.fromMediaImage(mediaImage, rotation)
objectDetector.process(inputImage)
.addOnSuccessListener { objects ->
for (obj in objects) {
val bounds = obj.boundingBox
val trackingId = obj.trackingId
for (label in obj.labels) {
val text = label.text
val confidence = label.confidence
val index = label.index
if (confidence > 0.5) {
// Draw bounding box
drawBoundingBox(bounds, text, confidence)
}
}
}
}
.addOnCompleteListener { imageProxy.close() }
}
}
// Custom model (TensorFlow Lite)
val customOptions = CustomObjectDetectorOptions.Builder(localModel)
.setClassificationMode(
CustomObjectDetectorOptions.CLASSIFICATION_MODE_SINGLE
)
.setMaxPerObjectLabelCount(3)
.build()
// Segmentation
val segmenterOptions = SubjectSegmenterOptions.Builder()
.setOutputFormat(SubjectSegmenterOptions.OUTPUT_FORMAT_BITMAP)
.build()
val segmenter = SubjectSegmentation.getClient(segmenterOptions)
segmenter.process(inputImage)
.addOnSuccessListener { result ->
val mask = result.mask // Bitmap with alpha channel
val confidence = result.confidence
// Apply mask to image
}CameraX + ML Kit Pipeline
class CameraMLPipeline @Inject constructor(
@ApplicationContext context: Context
) {
fun startAnalysis(
lifecycle: LifecycleOwner,
viewFinder: PreviewView,
onResult: (MLResult) -> Unit
) {
val cameraProvider = ProcessCameraProvider.getInstance(context).await()
val preview = Preview.Builder().build().apply {
setSurfaceProvider(viewFinder.surfaceProvider)
}
val imageAnalysis = ImageAnalysis.Builder()
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
.build()
.also { it.setAnalyzer(cameraExecutor, CombinedAnalyzer(onResult)) }
cameraProvider.bindToLifecycle(
lifecycle,
CameraSelector.DEFAULT_BACK_CAMERA,
preview,
imageAnalysis
)
}
}
class CombinedAnalyzer(
private val onResult: (MLResult) -> Unit
) : ImageAnalysis.Analyzer {
private val barcodeScanner = BarcodeScanning.getClient()
private val textRecognizer = TextRecognition.getClient()
private val faceDetector = FaceDetection.getClient()
override fun analyze(imageProxy: ImageProxy) {
val mediaImage = imageProxy.image ?: return
val rotation = imageProxy.imageInfo.rotationDegrees
val inputImage = InputImage.fromMediaImage(mediaImage, rotation)
// Run all detectors in parallel
val barcodeTask = barcodeScanner.process(inputImage)
val textTask = textRecognizer.process(inputImage)
val faceTask = faceDetector.process(inputImage)
Tasks.whenAll(barcodeTask, textTask, faceTask)
.addOnSuccessListener { results ->
val barcodes = results[0] as List<Barcode>
val text = results[1] as Text
val faces = results[2] as List<Face>
onResult(MLResult(barcodes, text, faces))
}
.addOnCompleteListener { imageProxy.close() }
}
}
data class MLResult(
val barcodes: List<Barcode> = emptyList(),
val text: Text? = null,
val faces: List<Face> = emptyList()
)Permissions
// Manifest
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera.any" />
<uses-feature android:name="android.hardware.camera.autofocus" />
// Runtime permission
class CameraPermissionHandler(
private val activity: ComponentActivity
) {
private val cameraPermissionLauncher = activity.registerForActivityResult(
ActivityResultContracts.RequestPermission()
) { granted ->
if (granted) startCamera() else showPermissionRationale()
}
fun checkAndRequest() {
if (ContextCompat.checkSelfPermission(
activity, Manifest.permission.CAMERA
) == PackageManager.PERMISSION_GRANTED
) {
startCamera()
} else {
cameraPermissionLauncher.launch(Manifest.permission.CAMERA)
}
}
}Try It
Add CameraX and ML Kit dependencies. Create PreviewView. Bind camera to lifecycle. Add ImageAnalysis with ML Kit analyzer. Test barcode, text, face detection.
# Add to build.gradle.kts:
# implementation("androidx.camera:camera-view:1.3.3")
# implementation("com.google.mlkit:barcode-scanning:17.2.0")CameraX & ML Kit mastery
- Set up CameraX with Preview, ImageCapture, ImageAnalysis
- Implement barcode scanner with multiple formats
- Add text recognition (on-device and cloud)
- Detect faces with landmarks and classifications
- Detect poses for fitness/app features
- Custom object detection with TFLite model
- Subject segmentation for background removal
- Combine multiple analyzers efficiently
- Handle camera permissions and lifecycle
CameraX simplifies camera operations across devices. ML Kit provides on-device ML (barcode, text, face, pose, objects). Use ImageAnalysis.Analyzer for frame processing. Combine with CameraX for real-time ML. Handle lifecycle and permissions properly.
Resources
- CameraX: https://developer.android.com/training/camerax
- ML Kit: https://developers.google.com/ml-kit
- CameraX + ML Kit: https://developer.android.com/training/camerax/mlkit-analyzer
- TFLite Models: https://www.tensorflow.org/lite/models