Skip to main content

YOLO26 모델을 위한 MNN 내보내기 및 배포

MNN

MNN mobile neural network inference framework

MNN은 매우 효율적이고 가벼운 딥러닝 프레임워크입니다. 이 프레임워크는 딥러닝 모델의 추론 및 학습을 지원하며, 온디바이스(on-device) 추론 및 학습 분야에서 업계 최고의 성능을 자랑합니다. 현재 MNN은 Alibaba Inc의 Taobao, Tmall, Youku, DingTalk, Xianyu 등 30개 이상의 앱에 통합되어 있으며, 라이브 방송, 숏폼 비디오 캡처, 검색 추천, 이미지 기반 상품 검색, 인터랙티브 마케팅, 자산 분배, 보안 위험 관리 등 70개 이상의 사용 사례를 포괄하고 있습니다. 또한 MNN은 IoT와 같은 임베디드 장치에서도 사용됩니다.



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

MNN으로 내보내기: YOLO26 모델 변환하기

YOLO26 모델을 MNN 형식으로 변환하여 모델 호환성과 배포 유연성을 확장할 수 있습니다. Ultralytics YOLO 이 변환은 모델을 모바일 및 임베디드 환경에 최적화하여 리소스가 제한된 장치에서도 효율적인 성능을 보장합니다.

설치

필요한 패키지를 설치하려면 다음을 실행하십시오:

설치
# Install the required package for YOLO26 and MNN
pip install ultralytics
pip install MNN

사용법

모든 Ultralytics YOLO26 모델는 별도의 설정 없이 내보내기를 지원하도록 설계되어 있어, 선호하는 배포 워크플로우에 쉽게 통합할 수 있습니다. 지원되는 내보내기 형식 및 구성 옵션 전체 목록 확인을 통해 애플리케이션에 가장 적합한 설정을 선택하십시오.

사용법
  from ultralytics import YOLO

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

  # Export the model to MNN format
  model.export(format="mnn")  # creates 'yolo26n.mnn'

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

  # Run inference
  results = mnn_model("https://ultralytics.com/images/bus.jpg")

내보내기 인수

인자유형기본값설명
formatstr'mnn'내보낸 모델의 대상 형식으로, 다양한 배포 환경과의 호환성을 정의합니다.
imgszint 또는 tuple640모델 입력에 필요한 이미지 크기입니다. 정사각형 이미지를 위한 정수이거나 튜플일 수 있습니다. (height, width))를 사용하거나, 특정 치수의 경우 튜플
halfboolFalseFP16(반정밀도) 양자화를 활성화하여 모델 크기를 줄이고 지원되는 하드웨어에서 추론 속도를 높일 수 있습니다.
int8boolFalseINT8 양자화를 활성화하여 모델을 추가로 압축하고 최소한의 정확도 손실 함수, 주로 엣지 장치용입니다.
batchint1내보낸 모델의 배치 추론 크기 또는 내보낸 모델이 동시에 처리할 최대 이미지 수를 지정합니다. predict 모드에서 사용됩니다.
devicestrNone내보내기용 장치를 지정합니다: GPU(device=0), CPU(device=cpu), Apple 실리콘용 MPS(device=mps).

내보내기 프로세스에 대한 자세한 내용은 다음을 방문하십시오. Ultralytics 내보내기 문서 페이지.

MNN 전용 추론

YOLO26 추론 및 전처리를 위해 오직 MNN에만 의존하는 기능이 구현되어 있으며, 모든 시나리오에서 쉽게 배포할 수 있도록 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)

요약

이 가이드에서는 Ultralytics YOLO26 모델을 MNN으로 내보내고 MNN을 사용하여 추론하는 방법을 소개합니다. MNN 형식은 edge AI 애플리케이션에 탁월한 성능을 제공하므로, 리소스가 제한된 장치에 컴퓨터 비전 모델을 배포하는 데 이상적입니다.

더 많은 사용 방법은 다음을 참조하십시오. MNN 문서.

FAQ

Ultralytics YOLO26 모델을 MNN 형식으로 어떻게 내보내나요?

Ultralytics YOLO26 모델을 MNN 형식으로 내보내려면 다음 단계를 따르십시오:

내보내기(Export)
from ultralytics import YOLO

# Load the 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

자세한 내보내기 옵션은 다음을 확인하십시오. 내보내기(Export) 문서 페이지.

내보낸 YOLO26 MNN 모델로 어떻게 예측하나요?

내보낸 YOLO26 MNN 모델로 예측하려면 다음을 사용하십시오. predict YOLO 클래스의 함수.

예측
from ultralytics import YOLO

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

# Export to MNN format
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 disk

MNN은 어떤 플랫폼을 지원하나요?

MNN은 다재다능하며 다양한 플랫폼을 지원합니다:

Ultralytics YOLO26 MNN 모델을 모바일 장치에 어떻게 배포하나요?

YOLO26 모델을 모바일 장치에 배포하려면:

  1. Android용 빌드: 다음을 따르십시오. MNN Android 가이드를 참조하십시오.
  2. iOS용 빌드: 다음을 따르십시오. MNN iOS 가이드를 참조하십시오.
  3. Harmony용 빌드: 다음을 따르십시오. MNN Harmony 가이드를 참조하십시오.

댓글