跳至主要內容

ML 多維陣列模組

MLMultiArray 是 CoreML 里最常見的張量類型。
這頁統一說明 coreml 模組中與 MLMultiArray 相關的模組級函式和物件方法,包括:

  • 建立張量
  • 把 Lua / 影像 / OpenCV 資料轉成張量
  • MLMultiArray 與 ORT tensor 互轉
  • 常用數學運算、歸約、排序和拼接
  • 檢測 / OBB / mask / keypoint / tracker 等後處理輔助

如果你要在 Lua 層封裝分類、Embedding、文字模型、檢測模型或其它通用 CoreML 模型,這一頁里的能力就是主要基礎。

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

建立與轉換

coreml.new_multi_array(opts) / coreml.tensor(opts)

多維陣列物件, 錯誤資訊 = coreml.new_multi_array({
shape = 形狀陣列,
data_type = 資料類型,
})

用於建立一個空的 CoreML 多維陣列物件,適合後續作為模型輸入或中間張量使用。

  • shape 為目標形狀,例如 {1, 3, 224, 224}
  • data_type 可選 "int32""float32""float16""double""float64" 可作為 "double" 的別名
  • coreml.tensor(opts) 是同義別名

coreml.multi_array_from_table(data, opts) / coreml.tensor_from_table(data, opts)

多維陣列物件, 錯誤資訊 = coreml.multi_array_from_table(資料表, {
shape = 形狀陣列,
data_type = 資料類型,
})

用於把 Lua 表中的資料顯式轉換成 MLMultiArray

  • shape 必須與資料總量匹配
  • data_type 規則與 new_multi_array() 一致
  • coreml.tensor_from_table(...) 是同義別名

coreml.tensor_from_image(image[, opts])

多維陣列物件, 元資訊 = coreml.tensor_from_image(圖片, 設定)

用於把圖片物件按顯式設定轉換為 CoreML 可用的張量。

常用設定字段:

  • width / height
  • layout:僅支援 "nchw""nhwc"
  • channel_order"rgb""bgr""gray""grey""grayscale"
  • data_type
  • scale
  • mean
  • std
  • resize_mode"stretch""letterbox""center_crop"
  • letterbox_mode:支援 "center""top_left",其中 "topleft" 也會按 "top_left" 處理
  • pad_color
  • interpolation"bilinear""nearest"
  • alpha_mode"ignore""white""black""premultiply"
  • crop = {x, y, width, height}

說明:

  • 該函式只負責顯式設定驅動的影像張量化,不會隱式綁定某個具體模型的預處理規則
  • 成功時第二個回傳值是預處理元資訊表;失敗時返回 nil, 錯誤資訊
  • 元資訊常見字段包括: src_widthsrc_heightcrop_xcrop_ycrop_widthcrop_heightdst_widthdst_heightresized_widthresized_heightscale_xscale_yratiopad_leftpad_toppad_rightpad_bottomresize_modeoffset_xoffset_yletterbox_mode

coreml.tensor_from_images(images[, opts])

批量張量, 批量元資訊 = coreml.tensor_from_images({img1, img2}, {
width = 640,
height = 640,
layout = "nchw",
})

把一組影像批量轉換成 MLMultiArray

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

coreml.image_from_tensor(tensor[, opts])

影像物件, 錯誤資訊 = coreml.image_from_tensor(張量, opts)

把 2D / 3D / 4D MLMultiArray 還原成影像物件,適合偵錯模型輸入輸出。

常用設定字段:

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

說明:

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

coreml.image_to_multi_array(image[, opts])

這是舊介面名,目前只是 coreml.tensor_from_image(...) 的兼容別名。新代碼建議統一使用 tensor_from_image()

coreml.tensor_from_cv_mat(mat[, opts]) / coreml.multi_array_from_cv_mat(mat[, opts])

用於把 cv.mat 轉成 MLMultiArray

  • 需要先 require("image.cv")
  • 兩個名稱是同義別名

coreml.tensor_from_quad(mat, quad[, opts]) / coreml.multi_array_from_quad(mat, quad[, opts])

多維陣列物件, 錯誤資訊 = coreml.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",
data_type = "float32",
})

用於從 cv.mat 中按四邊形區域做透視裁剪,再直接得到 MLMultiArray

  • 需要先 require("image.cv")
  • quad 可以直接傳四個點,也可以傳帶 points 字段的表
  • 常用 optstensor_from_image() 基本一致,額外常見字段有 content_widthcontent_heightborder_type
  • 適合 OCR 識別前的單框拉正與張量化

coreml.tensor_from_quads(mat, quads[, opts]) / coreml.multi_array_from_quads(mat, quads[, opts])

批量張量, 錯誤資訊 = coreml.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 張量。

  • 需要先 require("image.cv")
  • quads 必須是非空陣列;每項可以帶 points
  • 每項里的 content_widthcontent_height 會覆蓋全域 opts 里的同名稱段
  • 回傳值會按結果 rank 自動走 stack()concat() 拼成 batch,適合 OCR 多框批處理

coreml.multi_array_from_ort_tensor(tensor[, data_type])

多維陣列物件, 錯誤資訊 = coreml.multi_array_from_ort_tensor(ORT 張量[, "float32"])

用於把 onnxruntime.tensor 原生拷貝成 MLMultiArray

  • 這個函式預設不存在;只有執行過 require("onnxruntime") 後才會被注入到內置 coreml 模組中
  • 轉換過程走 native 層拷貝,不經過 Lua table
  • string tensor 不能轉換成 MLMultiArray

類型判斷與別名

coreml.is_multi_array(value) / coreml.is_tensor(value)

是否多維陣列 = coreml.is_multi_array(需要判斷的值)

用於判斷一個值是否為 coreml_multi_array_objectis_tensor() 是同義別名。

模組級輔助函式

基礎張量輔助

  • coreml.concat(arrays, axis)
  • coreml.stack(arrays, axis)
  • coreml.gather(array, dim, indices)
  • coreml.take(array, indices[, dim])
  • coreml.gather_rows(array, indices)
  • coreml.clamp(array, min, max)
  • coreml.sigmoid(array)
  • coreml.exp(array)
  • coreml.where(condition, x, y)
  • coreml.matmul(lhs, rhs)

說明:

  • take() 預設沿第 1 維取值
  • gather_rows()take(array, indices, 1) 的便捷別名
  • where() 支援標量與 MLMultiArray 混用,並按廣播規則生成結果
  • matmul() 目前支援 rank-1 / rank-2 輸入組合

幾何與檢測輔助

  • coreml.nms(boxes, scores[, opts])
  • coreml.box_points(rotated_boxes)
  • coreml.xywh_to_xyxy(boxes)
  • coreml.xyxy_to_xywh(boxes)
  • coreml.rotated_iou(lhs, rhs)
  • coreml.rotated_nms(boxes, scores[, opts])

說明:

  • nms()boxes 必須是 [N, 4]scores 必須是 [N][N, C]
  • rotated_nms()boxes 必須是 [N, 5];目前 scores 使用 Lua 數字陣列
  • 兩者返回的都是儲存 1-based 索引的 MLMultiArray

解碼與 record 輔助

  • coreml.create_decoder(schema)
  • coreml.decode_yolo(output[, opts])
  • coreml.decode_yolo_obb(output[, opts])
  • coreml.decode_matrix_candidates(output, schema[, opts])
  • coreml.decode_dense_detection(output, opts)
  • coreml.records_from_boxes(boxes, scores, class_ids[, keep_indices])
  • coreml.obb_records_from_rows(rows, scores, class_ids[, angles[, keep_indices[, opts]]])
  • coreml.points_to_records(points[, opts])

說明:

  • create_decoder() 返回 decoder 物件,支援 :decode():task():schema()
  • decode_dense_detection() 返回 { boxes, scores, labels },當輸入是 batch 時返回 batch 結果陣列
  • decode_dense_detection()opts.strides 是必填項,且必須是非空正整數陣列
  • decode_dense_detection() 還要求 decode_widthdecode_height,且目前只支援 box_encoding = "grid_center_log_wh"
  • records_from_boxes()obb_records_from_rows()points_to_records() 會把張量結果整理成更適合 Lua 使用的 record table

掩碼、關鍵點與跟蹤輔助

  • coreml.threshold_masks(masks, threshold)
  • coreml.crop_masks_by_boxes(masks, boxes)
  • coreml.resize_masks(masks, width, height[, opts])
  • coreml.mask_iou(lhs_mask, rhs_mask)
  • coreml.mask_to_polygon(mask[, opts])
  • coreml.proto_masks(proto, coeffs, boxes, image_width, image_height[, opts])
  • coreml.project_masks(proto, coeffs, boxes, image_width, image_height[, opts])
  • coreml.db_postprocess(score_map[, opts])
  • coreml.tracker([opts])
  • coreml.reshape_keypoints(points[, keypoint_count[, keypoint_dim|opts]])
  • coreml.scale_boxes(boxes, transform)
  • coreml.clip_boxes(boxes, clip_width, clip_height)
  • coreml.scale_points(points, transform[, opts])
  • coreml.scale_keypoints(points, transform[, opts])
  • coreml.clip_keypoints(points, clip_width, clip_height[, opts])
  • coreml.ctc_greedy_decode(logits[, opts])
  • coreml.sample_logits(logits[, opts])

說明:

  • project_masks()proto_masks() 的別名
  • 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 可直接復用影像張量化返回的元資訊
  • tracker() 返回跟蹤器物件,支援 :update():reset():state():close()
  • ctc_greedy_decode() 輸入支援 [T, C][N, T, C]
  • ctc_greedy_decode() 支援 blank_indexmerge_repeatedapply_softmaxreturn_probabilitiescharset
  • ctc_greedy_decode() 一定會返回 indices;只有傳了 charset 才會帶 text;只有啟用 apply_softmaxreturn_probabilities 才會帶 confidence;只有啟用 return_probabilities 才會額外帶 probabilitiesprobability_confidence
  • sample_logits() 支援 argmaxtemperaturetop_ktop_pmin_pseed
  • sample_logits() 對 1D logits 返回單個 1-based 索引;對 batched logits 返回索引 MLMultiArray

物件基礎方法

基礎查詢

  • array:shape()
  • array:data_type()
  • array:count()
  • array:strides()
  • array:to_table()
  • array:to_cv_mat([opts])

說明:

  • data_type() 返回 "int32""float32""float16""double"
  • to_cv_mat() 需要先 require("image.cv")

ORT 橋接

  • array:to_ort_tensor([data_type])

這個方法預設不存在;只有執行過 require("onnxruntime") 後才會被注入到 coreml_multi_array_object

類型與形狀變換

  • array:astype(data_type)
  • array:clone()
  • array:reshape(shape)
  • array:transpose(axes)
  • array:slice(dim, start, stop[, step])
  • array:select(dim, index)
  • array:squeeze([dim])
  • array:unsqueeze(dim)
  • array:flatten([start_dim[, end_dim]])

說明:

  • reshape()transpose()squeeze()unsqueeze()flatten() 預設返回 view,不複製底層資料
  • reshape() / flatten() 對非連續佈局會報錯;這時可先 clone()
  • slice()select() 返回新的連續張量,不是 view
  • slice() / select() / gather() / take() 的索引語義都與 ONNX 頁保持 1-based 一致

數值與索引方法

  • array:gather(dim, indices)
  • array:take(indices[, dim])
  • array:l2_norm()
  • array:dot(other)
  • array:max([axis])
  • array:min([axis])
  • array:add(other)
  • array:sub(other)
  • array:mul(other)
  • array:div(other)
  • array:clamp(min, max)
  • array:sigmoid()
  • array:exp()
  • array:matmul(other)
  • array:scale(number)

說明:

  • add/sub/mul/div 支援標量和有限 broadcasting
  • sigmoid()exp()matmul() 的結果會提升到浮點輸出

歸約、排序與選擇

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

說明:

  • argmax() 不傳軸時返回整個陣列最大值的 1-based 線性索引
  • argmax(axis) 返回儲存索引的 MLMultiArray
  • topk() 返回 { values = 張量, indices = 張量 }
  • sort() 返回排序後的新 MLMultiArray不會 額外返回索引表

幾何與後處理物件方法

  • array:clip_boxes(clip_width, clip_height)
  • array:xywh_to_xyxy()
  • array:xyxy_to_xywh()
  • array:reshape_keypoints([keypoint_count[, keypoint_dim|opts]])
  • array:scale_points(transform[, opts])
  • array:clip_keypoints(clip_width, clip_height[, opts])

這些方法與同名模組級函式共享同一套底層實現,只是把目前陣列作為第一個參數傳入。

使用建議

  • 對新的通用 CoreML 介面來說,MLMultiArray 是預設的一等資料類型,不建議過早轉換為 Lua 表
  • 大多數批量運算應盡量在張量物件上完成,只有在偵錯、小資料輸出或兼容舊代碼時再呼叫 to_table()
  • 影像預處理規則應通過 tensor_from_image() 的參數顯式指定,避免把某個模型的預處理硬編碼到通用流程中
  • 如果你需要一份獨立副本,或希望把非連續佈局整理成連續張量,請顯式呼叫 clone()

範例

local arr = assert(coreml.tensor({
shape = {2, 3},
data_type = "float32",
}))

local filled = assert(coreml.tensor_from_table({
{1, 2, 3},
{4, 5, 6},
}, {
shape = {2, 3},
data_type = "float32",
}))

local merged = assert(coreml.concat({filled, filled}, 1))
print(coreml.is_tensor(merged))
print(merged:shape())