ONNX Runtime 張量模組
該模組在 20260402 以後版本方可使用
本頁說明 onnxruntime 模組中最常用的 tensor 相關函式和物件方法。
建立與轉換
onnxruntime.tensor(type, shape[, data])
張量, 錯誤資訊 = onnxruntime.tensor("float32", {1, 3}, {1, 2, 3})
用於建立一個普通 ORT tensor。
type為元素類型名稱shape為形狀陣列data可省略;省略時建立空張量- 數值 tensor 可以傳標量,表示用同一個值填滿整個張量
stringtensor 可以傳單個字串,表示按同一個字串填滿整個張量
onnxruntime.tensor_from_bytes(type, shape, bytes)
張量, 錯誤資訊 = onnxruntime.tensor_from_bytes("float32", {1, 3}, 原始位元組字串)
用於從連續原始位元組建立 tensor。
- 只支援數值和
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 轉成 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字段的表- 常用
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",
})
批量裁剪多個四邊形並自動拼成 batch tensor。
- 需要先
require("image.cv") quads必須是非空陣列;每項可以帶points- 每項里的
content_width、content_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/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",
})
用於把一組影像批量轉換成 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 還原成影像物件,適合偵錯模型輸入輸出。
常用設定字段:
layoutchannel_orderbatch_index:1-based,預設第1個 batchscalemeanstdclampvalue_range:"0_255"或"0_1"
說明:
- 僅支援 2D / 3D / 4D tensor
- 通道數僅支援
1或3
張量物件方法
基礎資訊
tensor:shape()tensor:rank()tensor:size()tensor:type()tensor:to_table()tensor:bytes()
說明:
to_table()會把內容展開成 Lua 表bytes()只支援數值和booltensor
讀寫與複製
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()只支援數值和booltensor,位元組長度必須完全匹配get()/set()的索引語義是 1-basedtensor: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]的 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可以是標量,也可以是形狀一致的 tensormatmul()目前支援 rank-1 / rank-2 tensor 組合sigmoid()/exp()/matmul()的回傳值會提升到浮點結果類型- 以上運算都不支援
stringtensor
歸約、排序與概率
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)返回int64tensor,索引語義也是 1-basedsort()返回{ 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()返回檢測陣列,每項都帶score、points和box;meta/image_meta可直接復用影像張量化返回的元資訊
onnxruntime.nms(boxes, scores[, opts])
普通矩形框 NMS。
常用選項:
iou_thresholdscore_thresholdtop_kclass_awareclass_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]的旋轉框 tensorscores可以是 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 把矩陣輸出拆成候選張量表,返回字段通常包括:
boxesscoresclass_idskeep_indicesselected_rowsangles(僅 OBB 等相關 schema)
onnxruntime.decode_dense_detection(output, opts)
把 dense detection head 輸出解碼成:
boxesscoreslabels
其中 boxes / scores / labels 都是 tensor。
- 輸入支援
[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 - 當傳入 batched 輸出時,回傳值是按 batch 組織的 Lua 陣列
onnxruntime.records_from_boxes(boxes, scores, class_ids[, keep_indices])
把 [N, 4] 框、分數、類別等 tensor 整理成 Lua record 清單,每項通常會帶:
boxscoreclass_idrow_indexx1/y1/x2/y2width/heightcx/cy
onnxruntime.obb_records_from_rows(rows, scores, class_ids[, angles[, keep_indices[, opts]]])
把 OBB 行資料整理成 Lua record 清單。
opts支援x_index、y_index、width_index、height_index
onnxruntime.points_to_records(points[, opts])
把 [N, P, D] 或 [N, P*D] 的點 / 關鍵點 tensor 整理成 Lua table。
opts支援point_count/keypoint_countopts支援point_dim/keypoint_dim
掩碼輔助
onnxruntime.threshold_masks(masks, threshold)
把連續 mask tensor 閾值化為 Lua mask table 清單。每個 mask 會包含:
widthheightbitspixel_countbounds
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_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 -
當輸入為 batch 時,返回 batch result 陣列
onnxruntime.sample_logits(logits[, opts])
支援以下採樣參數:
argmaxtemperaturetop_ktop_pmin_pseed
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