Load the model asset

Android assets are read-only and are not exposed as ordinary filesystem paths. ExecuTorchSegmenter uses AssetUtils to copy the .pte asset into app-private storage before loading it:

    

        
        
File modelFile = AssetUtils.copyAssetToFiles(context, MODEL_ASSET);
module = Module.load(modelFile.getAbsolutePath());

    
ExecuTorch API Highlight

Module.load() creates an ExecuTorch Java Module backed by the native runtime and loads the .pte program from a filesystem path.

Module owns the native runtime state for the loaded program. Labels and preprocessing settings are application data loaded separately. They are not interpreted by the ExecuTorch runtime.

Select and decode an image

The Android document picker returns a content URI, an Android reference to a file supplied by another application or storage provider. MainActivity opens the URI through ContentResolver, the Android API for accessing content URIs, and decodes the image into a Bitmap:

    

        
        
Uri uri = data.getData();
try (InputStream stream = getContentResolver().openInputStream(uri)) {
    selectedBitmap = BitmapFactory.decodeStream(stream);
}

    

A production application should also account for image orientation, large source images, and additional color formats.

Prepare the input tensor

ImagePreprocessor preserves the source aspect ratio, centers the resized image on a black 520×520 bitmap, and writes normalized RGB values in NCHW order:

    

        
        
float scale = Math.min(
        spec.inputWidth / (float) sourceWidth,
        spec.inputHeight / (float) sourceHeight
);

tensor[index] = (red - spec.mean[0]) / spec.std[0];
tensor[pixelsPerChannel + index] = (green - spec.mean[1]) / spec.std[1];
tensor[2 * pixelsPerChannel + index] = (blue - spec.mean[2]) / spec.std[2];

    

The channel indexing matches the Python preprocessing used for calibration and validation.

Previous page Complete and continue