Meet YOLO26: next-gen vision AI.

Link to this sectionXuất MNN cho các model YOLO26 và triển khai#

Link to this sectionMNN#

MNN mobile neural network inference framework

MNN là một framework deep learning cực kỳ hiệu quả và gọn nhẹ. Nó hỗ trợ inference và training các model deep learning và có hiệu suất hàng đầu trong ngành cho việc inference và training 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, 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 tuyến, 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 tài sản, kiểm soát rủi ro bảo mật. Ngoài ra, MNN còn đượ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📱

Link to this sectionXuấ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 và tính linh hoạt khi triển khai model 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à 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.

Link to this sectionCà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

Link to this sectionCách sử dụng#

Tất cả các mô hình Ultralytics YOLO26 đều được thiết kế để hỗ trợ xuất ngay lập tức, giúp dễ dàng tích hợp chúng vào quy trình triển khai ưa thích của bạn. Bạn có thể xem danh sách đầy đủ các định dạng xuất và tùy chọn cấu hình được hỗ trợ để 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, Predict, và Validate. Hãy xuất model của bạn, sau đó tải model đã xuất để chạy inference hoặc kiểm chứng độ 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")

Link to this sectionĐố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 hình ảnh mong muốn cho đầu vào của model. Có thể là một số nguyên cho hình ả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ế các flag half/int8 đã bị loại bỏ.
batchint1Chỉ định kích thước batch inference của model khi xuất hoặc số lượng ảnh tối đa mà model đã xuất sẽ xử lý đồng thời ở chế độ predict.
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ề quy trình xuất, hãy truy cập trang tài liệu của Ultralytics về việc xuất.

Link to this sectionInference 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)

Link to this sectionTó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 để thực hiện inference. Định dạng MNN cung cấp hiệu suất tuyệt vời cho các ứng dụng edge AI, giúp nó trở nên lý tưởng cho việc triển khai các model computer vision trên những 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.

Link to this sectionCâu hỏi thường gặp#

Link to this sectionLàm thế nào để xuất các model Ultralytics YOLO26 sang định dạng MNN?#

Để 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.

Link to this sectionLàm thế nào để dự đoán (predict) với model YOLO26 MNN đã xuất?#

Để dự đoán với model YOLO26 MNN đã xuất, hãy sử dụng hàm predict từ class 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

Link to this sectionNhững nền tảng nào được hỗ trợ cho MNN?#

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.

Link to this sectionLàm thế nào tôi có thể triển khai các model Ultralytics YOLO26 MNN trên thiết bị di động?#

Để triển khai các model YOLO26 của bạn trên thiết bị di động:

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

Bình luận