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.swift

Swift 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.

import Foundation
import SlabSwift

func classify(modelPath: String, imagePath: String, license: String) throws -> [SlabClassification] {
    let config = try SlabConfig(cacheDirectory: NSTemporaryDirectory(), license: license)
    let session = try SlabSession(config: config, path: modelPath, warmup: true)

    let output = try session.run(SlabInput(frame: try SlabFrame(contentsOf: imagePath)))
    print("\(output.backendUsed.map { "\($0)" } ?? "?"), \(output.latencyMs) ms")
    return output.topK(5)   // label is "" when the model has no labels
}