Link to this sectionXuất MNN cho các model YOLO26 và triển khai#
Link to this sectionMNN#
MNN là một framework deep learning hiệu quả và gọn nhẹ. Nó hỗ trợ suy luận (inference) và huấn luyện các model deep learning, đồng thời sở hữu hiệu năng hàng đầu trong ngành để suy luận và huấn luyện ngay 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 phủ hơn 70 kịch bản sử dụng như phát trực tiếp, 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, kiểm soát rủi ro an ninh. Ngoài ra, MNN còn được sử dụng trên các thiết bị nhúng, chẳng hạn 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 của model và sự linh hoạt trong 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 giúp tối ưu hóa model cho các môi trường di động và nhúng, đảm bảo hiệu năng 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:
# Install the required package for YOLO26 and MNN
pip install ultralytics
pip install MNNLink to this sectionCách sử dụng#
Tất cả các model Ultralytics YOLO26 đều được thiết kế để hỗ trợ xuất dữ liệu 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 suy luận hoặc xác thực độ chính xác của nó.
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Đối số xuất#
| Đối số | Loại | Mặc định | Mô tả |
|---|---|---|---|
format | str | 'mnn' | Định dạng đích cho model đã 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. |
imgsz | int hoặc tuple | 640 | Kí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ể. |
half | bool | False | Kích hoạt lượng tử hóa FP16 (độ chính xác một nửa), giúp giảm kích thước model và có khả năng tăng tốc độ suy luận trên các phần cứng được hỗ trợ. |
int8 | bool | False | Kích hoạt lượng tử hóa INT8, giúp nén model thêm nữa và tăng tốc độ suy luận với mức sụt giảm accuracy tối thiểu, chủ yếu cho các thiết bị cạnh (edge devices). |
batch | int | 1 | Xác định kích thước suy luận batch 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. |
device | str | None | Chỉ đị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ề xuất dữ liệu.
Link to this sectionSuy luận chỉ dùng MNN#
Một hàm chỉ dựa vào MNN để suy luận 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.
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 để suy luận. Định dạng MNN mang lại hiệu năng tuyệt vời cho các ứng dụng edge AI, làm cho nó trở nên lý tưởng để triển khai các model thị giác máy tính 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.
Link to this sectionCâu hỏi thường gặp#
Link to this sectionLàm thế nào để tôi 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:
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", half=True) # creates 'yolo26n.mnn' with fp16 weight
model.export(format="mnn", int8=True) # 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 để tôi dự đoán với một model YOLO26 MNN đã xuất?#
Để dự đoán với một model YOLO26 MNN đã xuất, hãy sử dụng hàm predict từ lớp YOLO.
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", half=True) # predict with `fp16` if device support
for result in results:
result.show() # display to screen
result.save(filename="result.jpg") # save to diskLink 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 cách 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:
- Xây dựng cho Android: Làm theo hướng dẫn MNN Android.
- Xây dựng cho iOS: Làm theo hướng dẫn MNN iOS.
- Xây dựng cho Harmony: Làm theo hướng dẫn MNN Harmony.