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フィールドを持つテーブルを渡せます- 一般的な
optsはtensor_from_image()とほぼ同じです。追加でよく使用されるフィールドにはcontent_width、content_height、border_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_widthとcontent_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/heightlayout:"nchw"、"nhwc"、"chw"、"hwc"channel_order:"rgb"、"bgr"、"gray"、"grey"、"grayscale"data_typescalemeanstdresize_mode:"stretch"、"letterbox"、"center_crop"letterbox_mode:"top_left"をサポートします。それ以外の場合は中央に配置してパディングしますpad_colorinterpolation:"bilinear"、"nearest"alpha_mode:"ignore"、"white"、"black"、"premultiply"crop = {x, y, width, height}add_batch
成功した場合、二番目の戻り値は前処理情報のテーブルです。次のフィールドが含まれます:
src_width/src_heightcrop_x/crop_y/crop_width/crop_heightdst_width/dst_heightresized_width/resized_heightlayoutchannel_orderresize_modescale_x/scale_y/ratiooffset_x/offset_ypad_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 テンソルを画像オブジェクトに戻します。モデルの入出力のデバッグに適しています。
よく使用する設定フィールド:
layoutchannel_orderbatch_index:1-based。デフォルトは1番目のバッチですscalemeanstdclampvalue_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()のstartとstopはどちらも 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()は検出結果の配列を返します。各要素にはscore、points、boxが含まれ、meta/image_metaには画像のテンソル化で返されたメタデータをそのまま再利用できます
onnxruntime.nms(boxes, scores[, opts])
通常の矩形ボックスに対する NMS です。
よく使用するオプション:
iou_thresholdscore_thresholdtop_kclass_awareclass_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])
スキーマに従って行列出力を候補テンソルのテーブルに分割します。通常、戻り値には次のフィールドが含まれます:
boxesscoresclass_idskeep_indicesselected_rowsangles(OBB などに関連するスキーマのみ)
onnxruntime.decode_dense_detection(output, opts)
dense detection head の出力を次の形式にデコードします:
boxesscoreslabels
boxes / scores / labels はすべてテンソルです。
- 入力は
[R, C]または[N, R, C]をサポートします opts.stridesは必須であり、空でない正の整数配列である必要がありますdecode_widthとdecode_heightも必須です- 現在は
box_encoding = "grid_center_log_wh"のみをサポートします - その他のよく使用されるフィールドには
box_offset、score_offset、class_offset、num_classes、score_thresholdがあります - バッチ化された出力を渡した場合、戻り値はバッチ単位でまとめられた Lua 配列になります
onnxruntime.records_from_boxes(boxes, scores, class_ids[, keep_indices])
[N, 4] のボックス、スコア、クラスなどのテンソルを Lua レコードのリストにまとめます。通常、各要素には次のフィールドが含まれます:
boxscoreclass_idrow_indexx1/y1/x2/y2width/heightcx/cy
onnxruntime.obb_records_from_rows(rows, scores, class_ids[, angles[, keep_indices[, opts]]])
OBB の行データを Lua レコードのリストにまとめます。
optsはx_index、y_index、width_index、height_indexをサポートします
onnxruntime.points_to_records(points[, opts])
[N, P, D] または [N, P*D] の点 / キーポイントテンソルを Lua テーブルにまとめます。
optsはpoint_count/keypoint_countをサポートしますoptsはpoint_dim/keypoint_dimをサポートします
マスク補助
onnxruntime.threshold_masks(masks, threshold)
連続値のマスクテンソルをしきい値処理し、Lua マスクテーブルのリストに変換します。各マスクには次のフィールドが含まれます:
widthheightbitspixel_countbounds
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_x、scale_y、pad_left、pad_topがあります
onnxruntime.tracker([opts])
再利用可能なトラッカーオブジェクトを作成します。次のメソッドをサポートします:
tracker:update(detections[, timestamp])tracker:reset()tracker:state()tracker:close()
よく使用する設定フィールド:
iou_thresholdmax_agemin_hits
onnxruntime.ctc_greedy_decode(logits[, opts])
次の形式で返します:
-
indices -
text -
confidence -
入力は
[T, C]または[N, T, C]をサポートします -
blank_index、merge_repeated、apply_softmax、return_probabilities、charsetをサポートします -
必ず
indicesを返します -
charsetを渡した場合のみtextが含まれます -
apply_softmaxまたはreturn_probabilitiesを有効にした場合のみconfidenceが含まれます -
return_probabilitiesを有効にした場合のみ、probabilitiesとprobability_confidenceも含まれます -
入力がバッチの場合、バッチ結果の配列を返します
onnxruntime.sample_logits(logits[, opts])
次のサンプリングパラメータをサポートします:
argmaxtemperaturetop_ktop_pmin_pseed
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