MNN Python Binding

3.5.0 · active · verified Thu Apr 16

MNN (Mobile Neural Network) is a blazing-fast, lightweight deep learning inference engine developed by Alibaba. It supports inference and training of deep learning models, offering high performance on various devices, including mobile and embedded systems. The Python package `mnn` provides APIs for inference, training, image processing, and numerical computation, allowing ML engineers to use MNN without dipping their toes in C++ code. It is currently at version 3.5.0 and maintains an active development and release cadence.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates loading an MNN model, preprocessing an image using `MNN.cv` and `MNN.numpy`, performing inference with the `Module API`, and post-processing the output. Replace `mobilenet_v1.mnn` and `cat.jpg` with your actual model and input data. The code includes creation of dummy files for runnable demonstration purposes if actual files are not present.

import MNN.nn as nn
import MNN.cv as cv
import MNN.numpy as np
import MNN.expr as expr
import os

# Assuming 'mobilenet_v1.mnn' and 'cat.jpg' exist in the current directory
# In a real scenario, you'd download these or replace with your model/image.
# For demonstration, we'll create dummy files if they don't exist.

# Create a dummy MNN model file if it doesn't exist (for runnable example)
if not os.path.exists('mobilenet_v1.mnn'):
    print("Creating dummy mobilenet_v1.mnn for quickstart. This won't run a real model.")
    with open('mobilenet_v1.mnn', 'w') as f:
        f.write('dummy_model_content')

# Create a dummy image file if it doesn't exist (for runnable example)
if not os.path.exists('cat.jpg'):
    print("Creating dummy cat.jpg for quickstart. This won't process a real image.")
    # Using PIL to create a simple dummy image
    try:
        from PIL import Image
        img = Image.new('RGB', (224, 224), color = 'red')
        img.save('cat.jpg')
    except ImportError:
        print("Pillow not installed. Skipping dummy image creation.")
        print("Please install Pillow (pip install Pillow) or provide a 'cat.jpg'.")

# Configure runtime (e.g., backend, threads, precision)
# Backend 0 typically refers to CPU. 'low' precision might enable FP16 if hardware supports.
config = {
    'precision': 'low', 
    'backend': 0,      
    'numThread': 4     
}
runtime_manager = nn.create_runtime_manager((config,))

# Load model using the Module API
# 'data' and 'prob' are example input/output names, adapt to your model
try:
    net = nn.load_module_from_file('mobilenet_v1.mnn', ['data'], ['prob'], runtime_manager=runtime_manager)
except Exception as e:
    print(f"Could not load dummy model: {e}. Please ensure 'mobilenet_v1.mnn' is a valid MNN model.")
    exit()

# Read and preprocess image using MNN.cv and MNN.numpy
# Mean and norm values are typical for MobileNet preprocessing
image = cv.imread('cat.jpg')
if image is not None:
    image = cv.resize(image, (224, 224), mean=[103.94, 116.78, 123.68], norm=[0.017, 0.017, 0.017])
    input_var = np.expand_dims(image, 0) # Add batch dimension (HWC to NHWC)
    input_var = expr.convert(input_var, expr.NC4HW4) # NHWC to NC4HW4 for MNN

    # Perform inference
    output_var = net.forward(input_var)

    # Post-process output
    output_var = expr.convert(output_var, expr.NHWC) # NC4HW4 to NHWC
    # For a real classification model, you would interpret 'output_var' here
    print(f"Inference output shape: {output_var.shape}")
    # Example: print top-1 class if it's a classification model
    # print(f"Output belongs to class: {np.argmax(output_var)}")
else:
    print("Could not read image. Ensure 'cat.jpg' exists and is a valid image.")

view raw JSON →