Skip to content
imaged

Image classification

Run an image model and read its highest-scoring classes.

Use your own .slab model and a runtime license. Model files carry their input sizes, preprocessing, labels, and backend preferences.

Classify.kt

Kotlin setup →

Run inference off the main thread.

// Classify an image and return the five most likely classes.
//
// The model file carries its own preprocessing (input size, color order,
// normalization) and labels, so the app only passes an image.
// Run it off the main thread.

import android.content.Context
import dev.slab.Slab
import dev.slab.SlabConfig
import dev.slab.SlabFrame
import dev.slab.SlabInput
import dev.slab.SlabOutput
import dev.slab.SlabSession

fun classify(context: Context, modelPath: String, imagePath: String, license: String): List<SlabOutput.Classification> {
    Slab.bind(context)   // once per process, before the license
    SlabConfig().use { config ->
        config.setCacheDir(context.cacheDir.path).setRuntimeLicense(license)
        SlabSession(config, modelPath).setWarmup(true).use { session ->
            SlabFrame.fromFile(imagePath).use { frame ->
                SlabInput().setFrame(frame).use { input ->
                    session.run(input).use { output ->
                        println("${Slab.backendName(output.backendUsed())}, ${output.latencyMs()} ms")
                        return output.topK(5)   // label is "" when the model has no labels
                    }
                }
            }
        }
    }
}