Guides building an on-device mobile image processing pipeline in Kotlin using CameraX, ML Kit, and OpenCV. Covers capture, crop, rotation, enhancement, compression, OCR, and KYC validation.
Ships in claude-skills-collection. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
| Besoin | Recommandation | Raison |
|---|---|---|
| Capture + analyse temps réel | CameraX + ML Kit | Optimisé mobile, entretenu par Google |
| Détection bordures / homographie | OpenCV Android | findContours + warpPerspective non dispo dans ML Kit |
| OCR multi-langues (ar/fr/en) | ML Kit Text Recognition v2 | On-device, pas de quota, faible latence |
| Segmentation / fond | ML Kit Selfie / Subject Segmentation | GPU-accelerated, simple API |
| Opérations matricielles avancées | OpenCV (fastNlMeansDenoising, CLAHE) | ML Kit n'expose pas ces primitives |
| Traitement hors ligne (KMP) | Kotlin Multiplatform + CIImage (iOS) | expect/actual sur processImage(Bitmap) |
Règle : ML Kit d'abord, OpenCV en complément pour ce qui dépasse son périmètre.
val cameraProvider = ProcessCameraProvider.getInstance(context).await()
val preview = Preview.Builder().build()
val imageCapture = ImageCapture.Builder()
.setCaptureMode(ImageCapture.CAPTURE_MODE_MAXIMIZE_QUALITY)
.setTargetResolution(Size(1920, 1080))
.build()
val imageAnalysis = ImageAnalysis.Builder()
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
.build()
cameraProvider.bindToLifecycle(lifecycleOwner, cameraSelector, preview, imageCapture, imageAnalysis)
Correction EXIF obligatoire avant tout traitement :
val matrix = Matrix().apply { postRotate(exifOrientation.toFloat()) }
val rotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
Avec ML Kit Document Scanner (API 23+) :
val options = GmsDocumentScannerOptions.Builder()
.setGalleryImportAllowed(false)
.setResultFormats(RESULT_FORMAT_JPEG, RESULT_FORMAT_PDF)
.setScannerMode(SCANNER_MODE_FULL)
.build()
val scanner = GmsDocumentScanning.getClient(options)
scanner.getStartScanIntent(activity).addOnSuccessListener { intentSender ->
scannerLauncher.launch(IntentSenderRequest.Builder(intentSender).build())
}
Fallback OpenCV pour contrôle fin :
val gray = Mat(); Imgproc.cvtColor(src, gray, Imgproc.COLOR_BGR2GRAY)
Imgproc.GaussianBlur(gray, gray, Size(5.0, 5.0), 0.0)
Imgproc.Canny(gray, gray, 75.0, 200.0)
val contours = mutableListOf<MatOfPoint>()
Imgproc.findContours(gray, contours, Mat(), Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE)
// Trouver le plus grand quadrilatère -> warpPerspective
Ordre d'application recommandé :
Imgproc.fastNlMeansDenoisingColored(src, dst, 10f, 10f, 7, 21)val blurred = Mat(); Imgproc.GaussianBlur(src, blurred, Size(0.0, 0.0), 3.0)
Core.addWeighted(src, 1.5, blurred, -0.5, 0.0, dst)
val clahe = Imgproc.createCLAHE(2.0, Size(8.0, 8.0))
clahe.apply(grayChannel, grayChannel)
Imgproc.adaptiveThreshold(gray, binary, 255.0,
Imgproc.ADAPTIVE_THRESH_GAUSSIAN_C, Imgproc.THRESH_BINARY, 11, 2.0)
data class QualityScore(
val blur: Double, // Laplacian variance — seuil min : 100
val brightness: Double, // Histogram mean — plage : 80–180
val coverage: Double, // % frame couvert — seuil min : 0.80
val glare: Boolean // Pics saturation S > 200
)
// Extension utilitaire OpenCV — à définir une fois dans le projet
fun Bitmap.toMat(): Mat = Mat().also { org.opencv.android.Utils.bitmapToMat(this, it) }
fun computeBlur(bmp: Bitmap): Double {
val mat = bmp.toMat()
val laplacian = Mat()
Imgproc.Laplacian(mat, laplacian, CvType.CV_64F)
val stdDev = MatOfDouble(); Core.meanStdDev(laplacian, MatOfDouble(), stdDev)
return stdDev.get(0, 0)[0].pow(2)
}
Feedback utilisateur clair à chaque rejet :
fun compressImage(bitmap: Bitmap, maxSizeKb: Int = 800): ByteArray {
var quality = 90
var bytes: ByteArray
do {
val out = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.WEBP_LOSSY, quality, out)
bytes = out.toByteArray()
quality -= 5
} while (bytes.size / 1024 > maxSizeKb && quality > 50)
return bytes
}
WEBP_LOSSLESS ou JPEG 95 %WEBP_LOSSY 75 %, max 1 MPval recognizer = TextRecognition.getClient(TextRecognizerOptions.DEFAULT_OPTIONS)
val inputImage = InputImage.fromBitmap(enhancedBitmap, 0)
recognizer.process(inputImage)
.addOnSuccessListener { visionText ->
val cin = Regex("""[A-Z]\d{7}""").find(visionText.text)?.value
val rib = Regex("""\d{20}""").find(visionText.text)?.value
// Luhn check sur carte, MRZ parser pour passeport
}
Dépendance ML Kit Text Recognition (modèle latin bundled, OCR 100 % on-device) :
// app/build.gradle — bloc dependencies
implementation 'com.google.mlkit:text-recognition:16.0.1'
// Autres écritures via artefacts dédiés : text-recognition-chinese,
// -devanagari, -japanese, -korean (un par script à reconnaître).
// Fichier chiffré via EncryptedFile (Jetpack Security)
val encryptedFile = EncryptedFile.Builder(
context, File(context.cacheDir, "img_${uuid}.tmp"),
MasterKey.Builder(context).setKeyScheme(MasterKey.KeyScheme.AES256_GCM).build(),
EncryptedFile.FileEncryptionScheme.AES256_GCM_HASHED_FILENAME
).build()
encryptedFile.openFileOutput().use { it.write(imageBytes) }
// Purge automatique via WorkManager après upload ou 24 h
// Processing asynchrone — toujours sur IO
viewModelScope.launch(Dispatchers.IO) {
val result = processImage(bitmap) // timeout : 5 s max
withContext(Dispatchers.Main) { updateUI(result) }
}
// Libérer les Mat OpenCV explicitement
val mat = bitmap.toMat()
try { /* traitement */ } finally { mat.release() }
// Coil avec contrainte mémoire pour affichage
imageView.load(uri) { size(800, 600); allowHardware(false) }
| Anti-pattern | Conséquence | Correction |
|---|---|---|
| Traiter le Bitmap sur le thread principal | ANR / freeze UI | Dispatchers.IO obligatoire |
Ne pas appeler mat.release() | OOM natif non détecté par GC Java | Bloc try/finally systématique |
| Stocker images brutes non chiffrées dans le cache | Fuite données KYC | EncryptedFile + purge auto |
| Enhancement avant rectification perspective | Artefacts sur bords déformés | Toujours rectifier avant d'améliorer |
| Résolution 4K+ passée à ML Kit OCR | Lenteur sans gain qualité | Redimensionner à ≤ 2 MP avant OCR |
| Fallback silencieux en cas de qualité insuffisante | Données OCR corrompues | Rejet explicite + message utilisateur |
| Initialiser ML Kit dans le constructeur du ViewModel | Crash si contexte indisponible | Injection lazy ou Factory |
ara) ou un service cloud.ZoomState et TapToFocus via CameraControl plutôt que manipuler manuellement la mise au point.processImage(ImageData) -> ProcessedResult dans :shared ; CameraX (Android) et AVFoundation (iOS) restent dans les modules platform via expect/actual.What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
/claude-skills-collection:dev-image-processing-pipelinefrom claude-skills-collection
npx claudepluginhub vantaflow/claude-skills-collection --plugin claude-skills-collection348 skills in this plugin
/agent-a2a-protocol-guideGuide du protocole Agent-to-Agent (A2A) de Google pour l'interopérabilité entre agents IA — découverte, communication et collaboration inter-agents, avec exemples de code, critères de décision et pièges à éviter. Se déclenche avec "A2A", "agent-to-agent", "protocole A2A", "Google A2A", "interopérabilité agents". Also triggers on "agent-to-agent protocol", "agent interoperability", "connect two agents"./agent-agent-observabilityInstrumentation technique d'un agent IA — tracing distribué des appels LLM et outils, spans, métriques custom, corrélation de logs et dashboards de supervision. Pour les alertes et garde-fous de production, voir agent-monitoring-setup. Se déclenche avec "observabilité agent", "tracing agent", "LangSmith", "Langfuse", "OpenTelemetry agent", "spans LLM", "corréler les logs agent". Also triggers on "trace my agent", "LLM tracing", "agent spans"./agent-api-caller-subagentSous-agent spécialisé dans les appels API REST/GraphQL avec retry, auth et transformation de données. Se déclenche avec "sous-agent API", "API caller agent", "agent qui appelle une API", "REST agent", "HTTP agent", "API integration subagent", "external API agent". Also triggers on "subagent that calls an API", "API calling agent", "agent HTTP requests".Other plugins' skills for the same job