メインコンテンツまでスキップ

ONNX Runtime テンソルモジュール

このモジュールは 20260402 以降のバージョンでのみ使用できます

このページでは、onnxruntime モジュールでよく使用されるテンソル関連の関数とオブジェクトメソッドについて説明します。

作成と変換

onnxruntime.tensor(type, shape[, data])

テンソル, エラー情報 = onnxruntime.tensor("float32", {1, 3}, {1, 2, 3})

通常の ORT テンソルを作成します。

  • type は要素型の名前です
  • shape は形状を表す配列です
  • data は省略可能です。省略すると空のテンソルが作成されます
  • 数値テンソルにはスカラーを渡すことができ、その値でテンソル全体が埋められます
  • string テンソルには単一の文字列を渡すことができ、その文字列でテンソル全体が埋められます

onnxruntime.tensor_from_bytes(type, shape, bytes)

テンソル, エラー情報 = onnxruntime.tensor_from_bytes("float32", {1, 3}, 生バイト列)

連続した生バイト列からテンソルを作成します。

  • 数値型と bool 型のみをサポートします
  • バイト長は shape および type と完全に一致する必要があります

onnxruntime.tensor_from_cv_mat(mat[, opts])

テンソル, エラー情報 = onnxruntime.tensor_from_cv_mat(mat, {
layout = "hwc",
channel_order = "rgb",
type = "uint8",
})

cv.mat をテンソルに変換します。

説明:

  • あらかじめ require("image.cv") を実行する必要があります
  • opts.type は変換先テンソルの要素型です

onnxruntime.tensor_from_quad(mat, quad[, opts])

テンソル, エラー情報 = onnxruntime.tensor_from_quad(mat, {
{x = 0, y = 0},
{x = 100, y = 0},
{x = 100, y = 32},
{x = 0, y = 32},
}, {
width = 100,
height = 32,
layout = "hwc",
channel_order = "rgb",
type = "uint8",
})

cv.mat の四辺形領域を透視変換で切り出し、ORT テンソルを直接取得します。

  • あらかじめ require("image.cv") を実行する必要があります
  • quad には四つの点を直接渡すか、points フィールドを持つテーブルを渡せます
  • 一般的な optstensor_from_image() とほぼ同じです。追加でよく使用されるフィールドには content_widthcontent_heightborder_type があります
  • OCR 認識前に単一のボックスを補正してテンソル化する用途に適しています

onnxruntime.tensor_from_quads(mat, quads[, opts])

バッチテンソル, エラー情報 = onnxruntime.tensor_from_quads(mat, {
{
points = quad1,
content_width = 96,
content_height = 32,
},
{
points = quad2,
content_width = 80,
content_height = 32,
},
}, {
width = 96,
height = 32,
resize_mode = "top_left_letterbox",
border_type = "replicate",
})

複数の四辺形を一括で切り出し、自動的にバッチテンソルへまとめます。

  • あらかじめ require("image.cv") を実行する必要があります
  • quads は空でない配列である必要があります。各要素には points を含められます
  • 各要素の content_widthcontent_height は、グローバルな opts にある同名フィールドを上書きします
  • 結果のランクに応じて stack() または concat() が自動的に使用され、バッチにまとめられます。OCR の複数ボックスの一括処理に適しています

onnxruntime.tensor_from_image(image[, opts])

テンソル, 前処理情報 = onnxruntime.tensor_from_image(画像オブジェクト, {
width = 224,
height = 224,
layout = "nchw",
channel_order = "rgb",
data_type = "float32",
scale = 1 / 255,
mean = {0.485, 0.456, 0.406},
std = {0.229, 0.224, 0.225},
resize_mode = "letterbox",
})

画像オブジェクトを ONNX Runtime で使用できる入力テンソルへ直接変換します。

よく使用する設定フィールド:

  • width / height
  • layout"nchw""nhwc""chw""hwc"
  • channel_order"rgb""bgr""gray""grey""grayscale"
  • data_type
  • scale
  • mean
  • std
  • resize_mode"stretch""letterbox""center_crop"
  • letterbox_mode"top_left" をサポートします。それ以外の場合は中央に配置してパディングします
  • pad_color
  • interpolation"bilinear""nearest"
  • alpha_mode"ignore""white""black""premultiply"
  • crop = {x, y, width, height}
  • add_batch

成功した場合、二番目の戻り値は前処理情報のテーブルです。次のフィールドが含まれます:

  • src_width / src_height
  • crop_x / crop_y / crop_width / crop_height
  • dst_width / dst_height
  • resized_width / resized_height
  • layout
  • channel_order
  • resize_mode
  • scale_x / scale_y / ratio
  • offset_x / offset_y
  • pad_left / pad_top / pad_right / pad_bottom

onnxruntime.tensor_from_images(images[, opts])

バッチテンソル, バッチメタデータ = onnxruntime.tensor_from_images({img1, img2}, {
width = 640,
height = 640,
layout = "nchw",
})

一連の画像を一括でテンソルに変換します。

  • 元画像のサイズは異なっていてもかまいません
  • 各画像を処理した後の出力形状と data_type が一致していれば、バッチにまとめられます
  • 二番目の戻り値は、入力順に対応するメタデータ配列です

onnxruntime.image_from_tensor(tensor[, opts])

画像オブジェクト, エラー情報 = onnxruntime.image_from_tensor(テンソル, {
layout = "nchw",
channel_order = "rgb",
batch_index = 1,
scale = 1 / 255,
mean = {0.485, 0.456, 0.406},
std = {0.229, 0.224, 0.225},
value_range = "0_1",
})

2D / 3D / 4D テンソルを画像オブジェクトに戻します。モデルの入出力のデバッグに適しています。

よく使用する設定フィールド:

  • layout
  • channel_order
  • batch_index:1-based。デフォルトは 1 番目のバッチです
  • scale
  • mean
  • std
  • clamp
  • value_range"0_255" または "0_1"

説明:

  • 2D / 3D / 4D テンソルのみをサポートします
  • チャネル数は 1 または 3 のみをサポートします

テンソルオブジェクトのメソッド

基本情報

  • tensor:shape()
  • tensor:rank()
  • tensor:size()
  • tensor:type()
  • tensor:to_table()
  • tensor:bytes()

説明:

  • to_table() は内容を展開して Lua テーブルにします
  • bytes() は数値テンソルと bool テンソルのみをサポートします

読み書きとコピー

  • tensor:get(index1[, index2, ...])
  • tensor:set(index1[, index2, ...], value)
  • tensor:fill(value_or_table)
  • tensor:clone()
  • tensor:copy_from_bytes(raw_bytes)
  • tensor:to(type)

説明:

  • fill() にスカラーを渡すとテンソル全体が埋められます。テーブルを渡す場合は、要素数が完全に一致する必要があります
  • copy_from_bytes() は数値テンソルと bool テンソルのみをサポートし、バイト長が完全に一致する必要があります
  • get() / set() のインデックスは 1-based です
  • tensor:to("string") は現在、string -> string のみをサポートします

形状とインデックス

  • tensor:reshape(shape)
  • tensor:transpose([axes])
  • tensor:flatten([start_dim[, end_dim]])
  • tensor:squeeze([dim])
  • tensor:unsqueeze(dim)
  • tensor:slice(dim, start, stop[, step])
  • tensor:select(dim, index)
  • tensor:gather(dim, indices)

説明:

  • slice()startstop はどちらも 1-based で、終了位置を含みます
  • slice()step は正の整数である必要があります
  • select() は選択した次元を削除します
  • gather()indices には Lua 配列または形状 [N] のテンソルを指定できます。インデックスは同様に 1-based です
  • これらのメソッドはすべて新しいテンソルオブジェクトを返します

数値演算

  • tensor:add(other)
  • tensor:sub(other)
  • tensor:mul(other)
  • tensor:div(other)
  • tensor:clamp(min, max)
  • tensor:sigmoid()
  • tensor:exp()
  • tensor:matmul(other)
  • tensor:dot(other)

説明:

  • other にはスカラーまたは同じ形状のテンソルを指定できます
  • matmul() は現在、rank-1 / rank-2 テンソルの組み合わせをサポートします
  • sigmoid() / exp() / matmul() の戻り値は浮動小数点の結果型に昇格します
  • これらの演算は string テンソルをサポートしません

リダクション、ソート、確率

  • tensor:argmax([axis])
  • tensor:sum([axis])
  • tensor:mean([axis])
  • tensor:max([axis])
  • tensor:min([axis])
  • tensor:softmax([axis])
  • tensor:normalize([axis])
  • tensor:sort([axis[, descending]])
  • tensor:topk(k[, axis])

説明:

  • argmax() に軸を指定しない場合、単一の 1-based インデックスを返します
  • argmax(axis)int64 テンソルを返し、インデックスは同様に 1-based です
  • sort(){ values = テンソル, indices = テンソル } を返します
  • topk(){ values = テンソル, indices = テンソル } を返します
  • sort() / topk() が返すインデックスはいずれも 1-based です

OpenCV ブリッジ

  • tensor:to_cv_mat([opts])
mat, エラー情報 = tensor:to_cv_mat({
layout = "hwc",
channel_order = "rgb",
coreml_data_type = "uint8",
})

説明:

  • あらかじめ require("image.cv") を実行する必要があります
  • 一部のテンソル型は cv.mat に直接マッピングできません。その場合は coreml_data_type を明示的に渡す必要があります

モジュールレベルのテンソル補助

基本的な数値処理の補助

  • onnxruntime.clamp(tensor, min, max)
  • onnxruntime.sigmoid(tensor)
  • onnxruntime.exp(tensor)
  • onnxruntime.where(condition, x, y)
  • onnxruntime.matmul(lhs, rhs)
  • onnxruntime.concat(tensors[, axis])
  • onnxruntime.stack(tensors[, axis])

説明:

  • clamp()sigmoid()exp()matmul() は、対応する tensor: メソッドと同じ実装を共有します
  • where() ではスカラー / ブール値 / テンソルを組み合わせて使用でき、ブロードキャスト規則に従って結果を計算します

その他の後処理補助

  • onnxruntime.mask_iou(lhs_mask, rhs_mask)
  • onnxruntime.db_postprocess(score_map[, opts])

説明:

  • mask_iou() は二つのマスクの IoU を直接計算します
  • mask_iou() は第三引数 opts もサポートします。compare_size = true を渡すか、位置合わせ後の比較サイズとして width / height を明示的に渡せます
  • db_postprocess() は DB / DBNet 系のテキスト検出の後処理に適しています。入力は [H, W][C, H, W][N, C, H, W] をサポートします
  • db_postprocess() は検出結果の配列を返します。各要素には scorepointsbox が含まれ、meta / image_meta には画像のテンソル化で返されたメタデータをそのまま再利用できます

onnxruntime.nms(boxes, scores[, opts])

通常の矩形ボックスに対する NMS です。

よく使用するオプション:

  • iou_threshold
  • score_threshold
  • top_k
  • class_aware
  • class_ids

戻り値は int64 テンソルで、インデックスは 1-based です。

onnxruntime.box_points(rotated_boxes)

回転ボックス [cx, cy, w, h, theta] を四つの頂点座標に変換します。

  • 入力には形状 [5][1, 5][N, 5] のテンソルを指定できます
  • 単一のボックスでは Lua の点テーブルを、複数のボックスでは点テーブルの配列を返します

onnxruntime.xywh_to_xyxy(boxes)

矩形ボックスを [cx, cy, w, h] から [x1, y1, x2, y2] に変換します。

onnxruntime.xyxy_to_xywh(boxes)

矩形ボックスを [x1, y1, x2, y2] から [cx, cy, w, h] に変換します。

onnxruntime.rotated_iou(box1, box2)

二つの回転ボックス間の IoU を計算します。

onnxruntime.rotated_nms(boxes, scores[, opts])

回転ボックスに対する NMS です。戻り値は同様に int64 テンソルで、インデックスは 1-based です。

  • boxes は形状 [N, 5] の回転ボックステンソルである必要があります
  • scores には Lua 配列または形状 [N] / [N, 1] のテンソルを指定できます

onnxruntime.create_decoder(schema)

再利用可能なデコーダーオブジェクトを作成します。

  • デコーダーオブジェクトは :decode(output[, opts]):task():schema() をサポートします
  • 検出 / OBB / 分類出力のスキーマをあらかじめ固定し、繰り返し再利用する場合に適しています

onnxruntime.decode_yolo(output[, opts])

組み込みの YOLO 検出ロジックに従って直接デコードし、検出レコードのリストを返します。

onnxruntime.decode_yolo_obb(output[, opts])

組み込みの YOLO OBB ロジックに従って直接デコードし、回転ボックスの検出レコードのリストを返します。

onnxruntime.decode_matrix_candidates(output, schema[, opts])

スキーマに従って行列出力を候補テンソルのテーブルに分割します。通常、戻り値には次のフィールドが含まれます:

  • boxes
  • scores
  • class_ids
  • keep_indices
  • selected_rows
  • angles(OBB などに関連するスキーマのみ)

onnxruntime.decode_dense_detection(output, opts)

dense detection head の出力を次の形式にデコードします:

  • boxes
  • scores
  • labels

boxes / scores / labels はすべてテンソルです。

  • 入力は [R, C] または [N, R, C] をサポートします
  • opts.strides は必須であり、空でない正の整数配列である必要があります
  • decode_widthdecode_height も必須です
  • 現在は box_encoding = "grid_center_log_wh" のみをサポートします
  • その他のよく使用されるフィールドには box_offsetscore_offsetclass_offsetnum_classesscore_threshold があります
  • バッチ化された出力を渡した場合、戻り値はバッチ単位でまとめられた Lua 配列になります

onnxruntime.records_from_boxes(boxes, scores, class_ids[, keep_indices])

[N, 4] のボックス、スコア、クラスなどのテンソルを Lua レコードのリストにまとめます。通常、各要素には次のフィールドが含まれます:

  • box
  • score
  • class_id
  • row_index
  • x1 / y1 / x2 / y2
  • width / height
  • cx / cy

onnxruntime.obb_records_from_rows(rows, scores, class_ids[, angles[, keep_indices[, opts]]])

OBB の行データを Lua レコードのリストにまとめます。

  • optsx_indexy_indexwidth_indexheight_index をサポートします

onnxruntime.points_to_records(points[, opts])

[N, P, D] または [N, P*D] の点 / キーポイントテンソルを Lua テーブルにまとめます。

  • optspoint_count / keypoint_count をサポートします
  • optspoint_dim / keypoint_dim をサポートします

マスク補助

onnxruntime.threshold_masks(masks, threshold)

連続値のマスクテンソルをしきい値処理し、Lua マスクテーブルのリストに変換します。各マスクには次のフィールドが含まれます:

  • width
  • height
  • bits
  • pixel_count
  • bounds

onnxruntime.crop_masks_by_boxes(masks, boxes)

[N, 4] のボックスに従って、しきい値処理済みのマスクリストを切り出します。

onnxruntime.resize_masks(masks, width, height[, opts])

マスクリストを指定したサイズにリサイズします。

  • 現在は opts.interpolation = "nearest" のみをサポートします

onnxruntime.mask_to_polygon(mask[, opts])

単一のバイナリマスクを多角形の点列に変換します。

  • opts.epsilon / opts.approx_epsilon は近似による単純化に使用できます

onnxruntime.proto_masks(proto, coeffs, boxes, image_width, image_height[, opts])

プロトタイプマスク、マスク係数、検出ボックスを対象画像のサイズに投影し直します。

  • project_masks() はこの関数の別名です
  • 戻り値はテンソルではなく、Lua マスクテーブルのリストです

キーポイントと幾何処理の補助

  • onnxruntime.reshape_keypoints(points[, keypoint_count[, keypoint_dim|opts]])
  • onnxruntime.scale_boxes(boxes, transform)
  • onnxruntime.clip_boxes(boxes, clip_width, clip_height)
  • onnxruntime.scale_points(points, transform[, opts])
  • onnxruntime.scale_keypoints(points, transform[, opts])
  • onnxruntime.clip_keypoints(points, clip_width, clip_height[, opts])

説明:

  • reshape_keypoints()[N, K*D][N, K, D] の間の整形をサポートします
  • scale_points() はデフォルトで通常の点レイアウトとして解釈し、scale_keypoints() はデフォルトでキーポイントレイアウトとして解釈します
  • transform 関連のテーブルは画像前処理のメタデータフィールドに対応します。よく使用されるフィールドには scale_xscale_ypad_leftpad_top があります

onnxruntime.tracker([opts])

再利用可能なトラッカーオブジェクトを作成します。次のメソッドをサポートします:

  • tracker:update(detections[, timestamp])
  • tracker:reset()
  • tracker:state()
  • tracker:close()

よく使用する設定フィールド:

  • iou_threshold
  • max_age
  • min_hits

onnxruntime.ctc_greedy_decode(logits[, opts])

次の形式で返します:

  • indices

  • text

  • confidence

  • 入力は [T, C] または [N, T, C] をサポートします

  • blank_indexmerge_repeatedapply_softmaxreturn_probabilitiescharset をサポートします

  • 必ず indices を返します

  • charset を渡した場合のみ text が含まれます

  • apply_softmax または return_probabilities を有効にした場合のみ confidence が含まれます

  • return_probabilities を有効にした場合のみ、probabilitiesprobability_confidence も含まれます

  • 入力がバッチの場合、バッチ結果の配列を返します

onnxruntime.sample_logits(logits[, opts])

次のサンプリングパラメータをサポートします:

  • argmax
  • temperature
  • top_k
  • top_p
  • min_p
  • seed

1D logits では単一のインデックスを返し、複数行の logits では int64 テンソルを返します。インデックスは 1-based です。

local ort = require("onnxruntime")

local tensor = assert(ort.tensor("float32", {2, 3}, {
1, 9, 3,
8, 2, 7,
}))

local sliced = assert(tensor:slice(2, 2, 3))
print(sliced:to_table()[1]) -- 9

local topk = assert(tensor:topk(2, 2))
print(topk.values:to_table()[1]) -- 9
print(topk.indices:to_table()[1]) -- 2