YOLO Vision 2026:

Xuất MNN cho các model YOLO26 và triển khai#

MNN#

MNN mobile neural network inference framework

MNN là một framework deep learning cực kỳ hiệu quả và nhẹ. Nó hỗ trợ suy luận và huấn luyện các model deep learning, đồng thời mang lại hiệu suất hàng đầu ngành cho việc suy luận và huấn luyện trên thiết bị (on-device). Hiện tại, MNN đã được tích hợp vào hơn 30 ứng dụng của Alibaba Inc, chẳng hạn như Taobao, Tmall, Youku, DingTalk, Xianyu, v.v., bao gồm hơn 70 kịch bản sử dụng như phát trực tiếp (live broadcast), quay video ngắn, đề xuất tìm kiếm, tìm kiếm sản phẩm bằng hình ảnh, tiếp thị tương tác, phân phối cổ phần và kiểm soát rủi ro bảo mật. Ngoài ra, MNN cũng được sử dụng trên các thiết bị nhúng như IoT.



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

Các tác vụ được hỗ trợ#

Xuất MNN hỗ trợ tất cả bảy tác vụ Ultralytics. Phân đoạn ngữ nghĩa và ước tính độ sâu chỉ khả dụng với YOLO26, họ mô hình duy nhất trang bị các đầu ra đó.

Tác vụYOLOv8YOLO11YOLO26
Detect
Segment
Semantic
Depth
Classify
Pose
OBB

Xuất sang MNN: Chuyển đổi model YOLO26 của bạn#

Bạn có thể mở rộng khả năng tương thích của model và tính linh hoạt khi triển khai bằng cách chuyển đổi các model Ultralytics YOLO sang định dạng MNN. Quá trình chuyển đổi này tối ưu hóa các model của bạn cho môi trường di động và thiết bị nhúng, đảm bảo hiệu suất hiệu quả trên các thiết bị bị hạn chế về tài nguyên.

Cài đặt#

Để cài đặt các gói cần thiết, hãy chạy:

Cài đặt
# Install the required package for YOLO26 and MNN
pip install ultralytics
pip install MNN

Cách sử dụng#

Tất cả các Ultralytics YOLO26 models đều được thiết kế để hỗ trợ xuất ngay khi sử dụng, giúp bạn dễ dàng tích hợp chúng vào quy trình làm việc triển khai ưa thích của mình. Bạn có thể view the full list of supported export formats and configuration options để chọn thiết lập tốt nhất cho ứng dụng của mình.

Định dạng MNN hỗ trợ các chế độ Export, PredictValidate. Hãy xuất model của bạn, sau đó tải model đã xuất để chạy suy luận hoặc xác thực độ chính xác của nó.

Xuất (Export)
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'
Dự đoán (Predict)
from ultralytics import YOLO

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

# Run inference
results = model("https://ultralytics.com/images/bus.jpg")
Xác thực
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")

Đối số xuất#

Đối sốLoạiMặc địnhMô tả
formatstr'mnn'Định dạng đích cho model được xuất, xác định khả năng tương thích với các môi trường triển khai khác nhau.
imgszint hoặc tuple640Kích thước ảnh mong muốn cho đầu vào của mô hình. Có thể là một số nguyên cho ảnh vuông hoặc một tuple (height, width) cho các kích thước cụ thể.
quantizeint hoặc strNoneĐộ chính xác lượng tử hóa: 16 (FP16), 8 (lượng tử hóa trọng số INT8), hoặc 32/không thiết lập (FP32). Thay thế cho các cờ half/int8 đã lỗi thời.
simplifyboolTrueĐơn giản hóa đồ thị ONNX trung gian với onnxslim.
opsetintNoneChỉ định phiên bản ONNX opset cho đồ thị ONNX trung gian. Nếu không được thiết lập, hệ thống sẽ sử dụng phiên bản được hỗ trợ mới nhất.
batchint1Chỉ định kích thước suy luận hàng loạt của mô hình xuất hoặc số lượng ảnh tối đa mà mô hình xuất sẽ xử lý đồng thời ở chế độ predict.
dynamicboolFalseCho phép kích thước ảnh đầu vào động. Không thể kết hợp với nms=True.
nmsboolFalseThêm NMS cho các model detect và pose. Không thể kết hợp với dynamic=True.
devicestrNoneChỉ định thiết bị để xuất: GPU (device=0), CPU (device=cpu), MPS cho Apple silicon (device=mps).

Để biết thêm chi tiết về quá trình xuất, hãy truy cập trang tài liệu của Ultralytics về việc xuất model.

Inference chỉ với MNN#

Một hàm dựa hoàn toàn vào MNN cho việc inference và tiền xử lý YOLO26 đã được triển khai, cung cấp cả phiên bản Python và C++ để dễ dàng triển khai trong mọi tình huống.

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)

Tóm tắt#

Trong hướng dẫn này, chúng tôi giới thiệu cách xuất model Ultralytics YOLO26 sang MNN và sử dụng MNN để suy luận. Định dạng MNN mang lại hiệu suất tuyệt vời cho các ứng dụng edge AI, lý tưởng cho việc triển khai các model computer vision trên các thiết bị bị hạn chế về tài nguyên.

Để biết thêm cách sử dụng, vui lòng tham khảo tài liệu MNN.

Câu hỏi thường gặp#

  • Để xuất model Ultralytics YOLO26 của bạn sang định dạng MNN, hãy làm theo các bước sau:

    Xuất (Export)
    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

    Để biết các tùy chọn xuất chi tiết, hãy kiểm tra trang Export trong tài liệu.

  • Để dự đoán bằng model YOLO26 MNN đã xuất, hãy sử dụng hàm predict từ lớp YOLO.

    Dự đoán (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
  • MNN rất linh hoạt và hỗ trợ nhiều nền tảng khác nhau:

    • Di động: Android, iOS, Harmony.
    • Hệ thống nhúng và thiết bị IoT: Các thiết bị như Raspberry Pi và NVIDIA Jetson.
    • Máy tính để bàn và máy chủ: Linux, Windows và macOS.
  • Để triển khai các model YOLO26 của bạn trên thiết bị di động:

    1. Xây dựng cho Android: Làm theo hướng dẫn MNN Android.
    2. Xây dựng cho iOS: Làm theo hướng dẫn MNN iOS.
    3. Xây dựng cho Harmony: Làm theo hướng dẫn MNN Harmony.

Bình luận