跳至主要內容

ONNX Runtime 張量模組

該模組在 20260402 以後版本方可使用

本頁說明 onnxruntime 模組中最常用的 tensor 相關函式和物件方法。

建立與轉換

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

張量, 錯誤資訊 = onnxruntime.tensor("float32", {1, 3}, {1, 2, 3})

用於建立一個普通 ORT tensor。

  • type 為元素類型名稱
  • shape 為形狀陣列
  • data 可省略;省略時建立空張量
  • 數值 tensor 可以傳標量,表示用同一個值填滿整個張量
  • string tensor 可以傳單個字串,表示按同一個字串填滿整個張量

onnxruntime.tensor_from_bytes(type, shape, bytes)

張量, 錯誤資訊 = onnxruntime.tensor_from_bytes("float32", {1, 3}, 原始位元組字串)

用於從連續原始位元組建立 tensor。

  • 只支援數值和 bool 類型
  • 位元組長度必須與 shapetype 完全匹配

onnxruntime.tensor_from_cv_mat(mat[, opts])

張量, 錯誤資訊 = onnxruntime.tensor_from_cv_mat(mat, {
layout = "hwc",
channel_order = "rgb",
type = "uint8",
})

用於把 cv.mat 轉成 tensor。

說明:

  • 需要先 require("image.cv")
  • opts.type 是目標 tensor 元素類型

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 tensor。

  • 需要先 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",
})

批量裁剪多個四邊形並自動拼成 batch tensor。

  • 需要先 require("image.cv")
  • quads 必須是非空陣列;每項可以帶 points
  • 每項里的 content_widthcontent_height 會覆蓋全域 opts 里的同名稱段
  • 回傳值會按結果 rank 自動走 stack()concat() 拼成 batch,適合 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",
})

用於把一組影像批量轉換成 tensor。

  • 原圖尺寸可以不同
  • 只要每張圖解析後的輸出 shape 與 data_type 一致,就能拼成 batch
  • 第二個回傳值是與輸入順序對應的元資訊陣列

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 tensor 還原成影像物件,適合偵錯模型輸入輸出。

常用設定字段:

  • layout
  • channel_order
  • batch_index:1-based,預設第 1 個 batch
  • scale
  • mean
  • std
  • clamp
  • value_range"0_255""0_1"

說明:

  • 僅支援 2D / 3D / 4D tensor
  • 通道數僅支援 13

張量物件方法

基礎資訊

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

說明:

  • to_table() 會把內容展開成 Lua 表
  • bytes() 只支援數值和 bool tensor

讀寫與複製

  • 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 tensor,位元組長度必須完全匹配
  • 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] 的 tensor;索引語義同樣是 1-based
  • 這幾類方法返回的都是新的 tensor 物件

數值運算

  • 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 可以是標量,也可以是形狀一致的 tensor
  • matmul() 目前支援 rank-1 / rank-2 tensor 組合
  • sigmoid() / exp() / matmul() 的回傳值會提升到浮點結果類型
  • 以上運算都不支援 string tensor

歸約、排序與概率

  • 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 tensor,索引語義也是 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")
  • 某些 tensor 類型不能直接映射到 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() 支援標量 / 布林值 / tensor 混用,並按廣播規則計算結果

額外後處理輔助

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

說明:

  • mask_iou() 用於直接計算兩張 mask 的交並比
  • mask_iou() 還支援第三個參數 opts,可傳 compare_size = true,或顯式傳 width / height 作為對齊後的比較尺寸
  • db_postprocess() 適合 DB / DBNet 一類文字檢測後處理;輸入支援 [H, W][C, H, W][N, C, H, W]
  • db_postprocess() 返回檢測陣列,每項都帶 scorepointsboxmeta / image_meta 可直接復用影像張量化返回的元資訊

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

普通矩形框 NMS。

常用選項:

  • iou_threshold
  • score_threshold
  • top_k
  • class_aware
  • class_ids

回傳值是 int64 tensor,索引為 1-based

onnxruntime.box_points(rotated_boxes)

把旋轉框 [cx, cy, w, h, theta] 轉成四個頂點座標。

  • 輸入可以是形狀 [5][1, 5][N, 5] 的 tensor
  • 單個框返回一個 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 tensor,索引為 1-based

  • boxes 必須是 [N, 5] 的旋轉框 tensor
  • scores 可以是 Lua 陣列,也可以是形狀 [N] / [N, 1] 的 tensor

onnxruntime.create_decoder(schema)

建立一個可復用 decoder 物件。

  • decoder 物件支援 :decode(output[, opts]):task():schema()
  • 適合把檢測 / OBB / 分類輸出的 schema 先固化,再多次復用

onnxruntime.decode_yolo(output[, opts])

直接按內置 YOLO 檢測邏輯解碼,返回 detection record 清單。

onnxruntime.decode_yolo_obb(output[, opts])

直接按內置 YOLO OBB 邏輯解碼,返回旋轉框 detection record 清單。

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

按 schema 把矩陣輸出拆成候選張量表,返回字段通常包括:

  • boxes
  • scores
  • class_ids
  • keep_indices
  • selected_rows
  • angles(僅 OBB 等相關 schema)

onnxruntime.decode_dense_detection(output, opts)

把 dense detection head 輸出解碼成:

  • boxes
  • scores
  • labels

其中 boxes / scores / labels 都是 tensor。

  • 輸入支援 [R, C][N, R, C]
  • opts.strides 是必填項,且必須是非空正整數陣列
  • decode_widthdecode_height 也是必填項
  • 目前只支援 box_encoding = "grid_center_log_wh"
  • 其餘常用字段包括 box_offsetscore_offsetclass_offsetnum_classesscore_threshold
  • 當傳入 batched 輸出時,回傳值是按 batch 組織的 Lua 陣列

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

[N, 4] 框、分數、類別等 tensor 整理成 Lua record 清單,每項通常會帶:

  • 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 record 清單。

  • opts 支援 x_indexy_indexwidth_indexheight_index

onnxruntime.points_to_records(points[, opts])

[N, P, D][N, P*D] 的點 / 關鍵點 tensor 整理成 Lua table。

  • opts 支援 point_count / keypoint_count
  • opts 支援 point_dim / keypoint_dim

掩碼輔助

onnxruntime.threshold_masks(masks, threshold)

把連續 mask tensor 閾值化為 Lua mask table 清單。每個 mask 會包含:

  • width
  • height
  • bits
  • pixel_count
  • bounds

onnxruntime.crop_masks_by_boxes(masks, boxes)

[N, 4] 框裁剪閾值化後的 mask 清單。

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

把 mask 清單縮放到指定尺寸。

  • 目前僅支援 opts.interpolation = "nearest"

onnxruntime.mask_to_polygon(mask[, opts])

把單個二值 mask 轉為多邊形點列。

  • opts.epsilon / opts.approx_epsilon 可用於近似簡化

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

把原型 mask、mask 系數和檢測框投影回目標影像尺寸。

  • project_masks() 是它的別名
  • 回傳值是 Lua mask table 清單,而不是 tensor

關鍵點與幾何輔助

  • 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 相關 table 與影像預處理元資訊字段對齊,常見字段包括 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_softmaxreturn_probabilities 才會帶 confidence

  • 只有啟用 return_probabilities 才會額外帶 probabilitiesprobability_confidence

  • 當輸入為 batch 時,返回 batch result 陣列

onnxruntime.sample_logits(logits[, opts])

支援以下採樣參數:

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

1D logits 返回單個索引;多行 logits 返回 int64 tensor,索引語義為 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