Meet YOLO26: next-gen vision AI.

Link to this section用于 YOLO26 模型和部署的 MNN 导出#

Link to this sectionMNN#

MNN mobile neural network inference framework

MNN 是一个高效且轻量级的深度学习框架。它支持深度学习模型的推理和训练,在端侧推理和训练方面具有业界领先的性能。目前,MNN 已集成到阿里巴巴的 30 多个应用中,如淘宝、天猫、优酷、钉钉、闲鱼等,涵盖了直播、短视频拍摄、搜索推荐、拍立淘、互动营销、权益分发、安全风控等 70 多个使用场景。此外,MNN 也被应用于物联网等嵌入式设备。



Watch: How to Export Ultralytics YOLO26 to MNN Format | Speed up Inference on Mobile Devices📱

Link to this section导出至 MNN:转换你的 YOLO26 模型#

你可以通过将 Ultralytics YOLO 模型转换为 MNN 格式来扩展模型兼容性和部署灵活性。这种转换针对移动和嵌入式环境优化了你的模型,确保了其在资源受限设备上的高效性能。

Link to this section安装#

要安装所需的软件包,请运行:

安装
# Install the required package for YOLO26 and MNN
pip install ultralytics
pip install MNN

Link to this section用法#

所有 Ultralytics YOLO26 模型 都设计为开箱即用支持导出,这使得将它们集成到你首选的部署工作流中变得非常容易。你可以 查看支持的导出格式和配置选项的完整列表,为你的应用选择最佳设置。

MNN 格式支持 ExportPredictValidate 模式。导出你的模型,然后加载导出的模型进行推理或验证其准确性。

导出
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")

Link to this section导出参数#

参数类型默认值描述
formatstr'mnn'导出模型的目标格式,定义了与各种部署环境的兼容性。
imgszinttuple640模型输入的期望图像尺寸。可以是一个用于正方形图像的整数,或者是一个用于特定尺寸的元组 (height, width)
quantizeintstrNone量化精度:16 (FP16)、8 (INT8 权重量化) 或 32/不设置 (FP32)。此选项取代了已弃用的 half/int8 标志。
batchint1指定导出模型的推理批次大小,或导出模型在 predict 模式下并发处理的最大图像数量。
devicestrNone指定导出所用的设备:GPU (device=0)、CPU (device=cpu) 或 Apple 芯片的 MPS (device=mps)。

有关导出过程的更多详细信息,请访问 Ultralytics 导出文档页面

Link to this section仅使用 MNN 进行推理#

我们实现了一个仅依赖 MNN 进行 YOLO26 推理和预处理的函数,并提供了 Python 和 C++ 版本,方便在任何场景下进行部署。

MNN
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)

Link to this section总结#

在本指南中,我们将介绍如何将 Ultralytics YOLO26 模型导出到 MNN,并使用 MNN 进行推理。MNN 格式为 edge AI 应用提供了出色的性能,非常适合在资源受限的设备上部署计算机视觉模型。

更多用法请参阅 MNN 文档

Link to this section常见问题解答#

Link to this section如何将 Ultralytics YOLO26 模型导出为 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 页面。

Link to this section如何使用导出的 YOLO26 MNN 模型进行预测?#

要使用导出的 YOLO26 MNN 模型进行预测,请使用 YOLO 类中的 predict 函数。

预测
from ultralytics import YOLO

# Load the YOLO26 MNN model
model = YOLO("yolo26n.mnn")

# Run inference
results = model("https://ultralytics.com/images/bus.jpg")  # predict with `fp32`
results = model("https://ultralytics.com/images/bus.jpg", quantize=16)  # predict with `fp16` if device support

for result in results:
    result.show()  # display to screen
    result.save(filename="result.jpg")  # save to disk

Link to this sectionMNN 支持哪些平台?#

MNN 功能强大且支持多种平台:

  • 移动端:Android、iOS、Harmony。
  • 嵌入式系统和物联网设备:如 Raspberry Pi 和 NVIDIA Jetson 等设备。
  • 桌面端和服务器:Linux, Windows, macOS。

Link to this section我该如何在移动设备上部署 Ultralytics YOLO26 MNN 模型?#

要在移动设备上部署你的 YOLO26 模型,请执行以下操作:

  1. 构建 Android 版本:请遵循 MNN Android 指南。
  2. 构建 iOS 版本:请遵循 MNN iOS 指南。
  3. 构建 Harmony 版本:请遵循 MNN Harmony 指南。

评论