Meet YOLO26: next-gen vision AI.

Link to this sectionYOLO26モデルのMNNエクスポートとデプロイメント#

Link to this sectionMNN#

MNN mobile neural network inference framework

MNNは、非常に効率的で軽量なディープラーニングフレームワークです。ディープラーニングモデルの推論と学習をサポートしており、オンデバイスでの推論と学習において業界トップクラスのパフォーマンスを誇ります。現在、MNNはTaobao、Tmall、Youku、DingTalk、Xianyuなど、Alibaba Incの30以上のアプリに統合されており、ライブ配信、ショート動画キャプチャ、検索レコメンデーション、画像による商品検索、インタラクティブマーケティング、資産分配、セキュリティリスク管理など、70以上の利用シーンをカバーしています。さらに、MNNはIoTなどの組み込みデバイスでも使用されています。



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

Link to this sectionMNNへのエクスポート: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'エクスポートするモデルのターゲット形式。さまざまなデプロイ環境との互換性を定義します。
imgszintまたはtuple640モデル入力用の希望する画像サイズ。正方形画像の場合は整数、特定の寸法の場合はタプル(height, width)を指定できます。
quantizeint または strNone量子化精度: 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 sectionMNN専用推論#

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)

Link to this section要約#

このガイドでは、Ultralytics YOLO26モデルをMNNにエクスポートする方法と、推論にMNNを使用する方法を紹介します。MNN形式はedge AIアプリケーションに対して優れたパフォーマンスを提供し、リソースが制限されたデバイスへのコンピュータビジョンモデルのデプロイに最適です。

その他の使用方法については、MNN documentationを参照してください。

Link to this sectionよくある質問 (FAQ)#

Link to this sectionUltralytics 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。
  • 組み込みシステムおよびIoTデバイス: 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ガイドに従ってください。

コメント