YOLO26 模型的 MNN 导出与部署#
MNN#
MNN 是一个高效且轻量级的深度学习框架。它支持深度学习模型的推理和训练,并在设备端推理和训练方面具备业界领先的性能。目前,MNN 已集成到阿里巴巴公司旗下的 30 多个应用中,例如淘宝、天猫、优酷、钉钉、闲鱼等,覆盖直播、短视频拍摄、搜索推荐、以图搜商品、互动营销、权益分配、安全风控等 70 多种使用场景。此外,MNN 还用于物联网等嵌入式设备。
Watch: How to Export Ultralytics YOLO26 to MNN Format | Speed up Inference on Mobile Devices📱
支持的任务#
MNN 导出支持 Ultralytics 的全部七项任务。语义分割和深度估计仅适用于 YOLO26,因为 YOLO26 是唯一提供这些检测头的系列。
导出到 MNN:转换你的 YOLO26 模型#
将 Ultralytics YOLO 模型转换为 MNN 格式,可以扩展模型兼容性和部署灵活性。这种转换会针对移动和嵌入式环境优化你的模型,确保其在资源受限设备上高效运行。
安装#
要安装所需的软件包,请运行:
# Install the required package for YOLO26 and MNN
pip install ultralytics
pip install MNN使用方法#
所有 Ultralytics YOLO26 模型 都支持开箱即用的导出,因此可以轻松将其集成到你首选的部署工作流中。你可以查看支持的导出格式和配置选项完整列表,为你的应用选择最佳配置。
MNN 格式支持 Export、Predict 和 Validate 模式。导出模型,然后加载导出的模型以运行推理或验证其准确性。
from ultralytics import YOLO
# Load a YOLO26 model
model = YOLO("yolo26n.pt")
# Export the model to MNN format
model.export(format="mnn") # creates 'yolo26n.mnn'from ultralytics import YOLO
# Load the exported MNN model
model = YOLO("yolo26n.mnn")
# Run inference
results = model("https://ultralytics.com/images/bus.jpg")from ultralytics import YOLO
# Load the exported MNN model
model = YOLO("yolo26n.mnn")
# Validate accuracy on the COCO8 dataset
metrics = model.val(data="coco8.yaml")导出参数#
| 参数 | 类型 | 默认值 | 描述 |
|---|---|---|---|
format | str | 'mnn' | 导出模型的目标格式,用于定义其与各种部署环境的兼容性。 |
imgsz | int 或 tuple | 640 | 模型输入所需的图像尺寸。可以使用表示正方形图像的整数,也可以使用元组 (height, width) 指定具体尺寸。 |
quantize | int 或 str | None | 量化精度:16(FP16)或 8(INT8)会缩减导出的权重;32/unset 导出 FP32 权重,但 MNN 的 CPU 运行时仍会以其默认的 low 精度进行计算,而不是使用 FP32。用于替代已弃用的 half/int8 标志。 |
simplify | bool | True | 使用 onnxslim 简化中间 ONNX 图。 |
opset | int | None | 指定中间 ONNX 图的 ONNX 算子集版本。如果未设置,则使用最新的受支持版本。 |
batch | int | 1 | 指定导出模型的批量推理大小,或指定导出模型在 predict 模式下并发处理的最大图像数量。 |
dynamic | bool | False | 启用动态输入图像尺寸。不能与 nms=True 结合使用。 |
nms | bool,可选 | None | 选择原始输出(None,默认)、嵌入式 NMS(True)或无 NMS 的检测头(False)。嵌入式 NMS 支持使用 dynamic=False 的检测和姿态估计。 |
device | str | None | 指定导出设备:GPU(device=0)、CPU(device=cpu)、Apple silicon 的 MPS(device=mps)。 |
如需详细了解导出流程,请访问 Ultralytics 导出文档页面。
仅使用 MNN 的推理#
现已实现一个完全依赖 MNN 进行 YOLO26 推理和预处理的函数,并提供 Python 和 C++ 版本,便于在任何场景中部署。
import argparse
import MNN
import MNN.cv as cv2
import MNN.numpy as np
def inference(model, img, precision, backend, thread):
config = {}
config["precision"] = precision
config["backend"] = backend
config["numThread"] = thread
rt = MNN.nn.create_runtime_manager((config,))
# net = MNN.nn.load_module_from_file(model, ['images'], ['output0'], runtime_manager=rt)
net = MNN.nn.load_module_from_file(model, [], [], runtime_manager=rt)
original_image = cv2.imread(img)
ih, iw, _ = original_image.shape
length = max((ih, iw))
scale = length / 640
image = np.pad(original_image, [[0, length - ih], [0, length - iw], [0, 0]], "constant")
image = cv2.resize(
image, (640, 640), 0.0, 0.0, cv2.INTER_LINEAR, -1, [0.0, 0.0, 0.0], [1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0]
)
image = image[..., ::-1] # BGR to RGB
input_var = image[None]
input_var = MNN.expr.convert(input_var, MNN.expr.NC4HW4)
output_var = net.forward(input_var)
output_var = MNN.expr.convert(output_var, MNN.expr.NCHW)
output_var = output_var.squeeze()
# output_var shape: [84, 8400]; 84 means: [cx, cy, w, h, prob * 80]
cx = output_var[0]
cy = output_var[1]
w = output_var[2]
h = output_var[3]
probs = output_var[4:]
# [cx, cy, w, h] -> [y0, x0, y1, x1]
x0 = cx - w * 0.5
y0 = cy - h * 0.5
x1 = cx + w * 0.5
y1 = cy + h * 0.5
boxes = np.stack([x0, y0, x1, y1], axis=1)
# ensure ratio is within the valid range [0.0, 1.0]
boxes = np.clip(boxes, 0, 1)
# get max prob and idx
scores = np.max(probs, 0)
class_ids = np.argmax(probs, 0)
result_ids = MNN.expr.nms(boxes, scores, 100, 0.45, 0.25)
print(result_ids.shape)
# nms result box, score, ids
result_boxes = boxes[result_ids]
result_scores = scores[result_ids]
result_class_ids = class_ids[result_ids]
for i in range(len(result_boxes)):
x0, y0, x1, y1 = result_boxes[i].read_as_tuple()
y0 = int(y0 * scale)
y1 = int(y1 * scale)
x0 = int(x0 * scale)
x1 = int(x1 * scale)
# clamp to the original image size to handle cases where padding was applied
x1 = min(iw, x1)
y1 = min(ih, y1)
print(result_class_ids[i])
cv2.rectangle(original_image, (x0, y0), (x1, y1), (0, 0, 255), 2)
cv2.imwrite("res.jpg", original_image)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--model", type=str, required=True, help="the yolo26 model path")
parser.add_argument("--img", type=str, required=True, help="the input image path")
parser.add_argument("--precision", type=str, default="normal", help="inference precision: normal, low, high, lowBF")
parser.add_argument(
"--backend",
type=str,
default="CPU",
help="inference backend: CPU, OPENCL, OPENGL, NN, VULKAN, METAL, TRT, CUDA, HIAI",
)
parser.add_argument("--thread", type=int, default=4, help="inference using thread: int")
args = parser.parse_args()
inference(args.model, args.img, args.precision, args.backend, args.thread)总结#
本指南介绍如何将 Ultralytics YOLO26 模型导出到 MNN,并使用 MNN 进行推理。MNN 格式为边缘 AI 应用提供出色的性能,非常适合在资源受限设备上部署计算机视觉模型。
如需了解更多用法,请参阅 MNN 文档。
常见问题#
要将你的 Ultralytics YOLO26 模型导出为 MNN 格式,请按照以下步骤操作:
导出from ultralytics import YOLO # Load a YOLO26 model model = YOLO("yolo26n.pt") # Export to MNN format model.export(format="mnn") # creates 'yolo26n.mnn' with fp32 weight model.export(format="mnn", quantize=16) # creates 'yolo26n.mnn' with fp16 weight model.export(format="mnn", quantize=8) # creates 'yolo26n.mnn' with int8 weight有关详细的导出选项,请查看文档中的 Export 页面。
要使用导出的 YOLO26 MNN 模型进行预测,请使用 YOLO 类中的
predict函数。Predictfrom ultralytics import YOLO # Load the YOLO26 MNN model model = YOLO("yolo26n.mnn") # Run inference results = model("https://ultralytics.com/images/bus.jpg") for result in results: result.show() # display to screen result.save(filename="result.jpg") # save to diskMNN 具有很强的通用性,支持多种平台:
- 移动端:Android、iOS、Harmony。
- 嵌入式系统和物联网设备:例如 Raspberry Pi 和 NVIDIA Jetson 等设备。
- 桌面端和服务器:Linux、Windows 和 macOS。
要在移动设备上部署你的 YOLO26 模型:
- 构建 Android 应用:按照 MNN Android 指南操作。
- 构建 iOS 应用:按照 MNN iOS 指南操作。
- 构建 Harmony 应用:按照 MNN Harmony 指南操作。