본문으로 건너뛰기

ONNX Runtime 텐서 모듈

이 모듈은 20260402 이후 버전에서 사용할 수 있습니다.

이 페이지에서는 onnxruntime 모듈에서 가장 자주 사용하는 tensor 관련 함수와 객체 메서드를 설명합니다.

생성 및 변환

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

텐서, 오류 정보 = onnxruntime.tensor("float32", {1, 3}, {1, 2, 3})

일반 ORT tensor를 생성합니다.

  • type은 요소 유형 이름입니다.
  • shape은 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_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 / 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만 지원합니다.
  • 채널 수는 1 또는 3만 지원합니다.

텐서 객체 메서드

기본 정보

  • 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만 지원합니다.

shape 및 인덱스

  • 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 배열 또는 shape이 [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는 스칼라 또는 shape이 같은 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()에 axis를 전달하지 않으면 단일 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를 함께 사용할 수 있으며 broadcasting 규칙에 따라 결과를 계산합니다.

추가 후처리 도우미

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

설명:

  • mask_iou()는 두 mask의 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_threshold
  • score_threshold
  • top_k
  • class_aware
  • class_ids

반환값은 int64 tensor이며 인덱스는 1-based입니다.

onnxruntime.box_points(rotated_boxes)

회전 상자 [cx, cy, w, h, theta]를 네 꼭짓점 좌표로 변환합니다.

  • 입력은 shape이 [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 배열 또는 shape이 [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_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 목록으로 정리하며 각 항목에는 일반적으로 다음 필드가 포함됩니다.

  • 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 목록으로 정리합니다.

  • optsx_index, y_index, width_index, height_index를 지원합니다.

onnxruntime.points_to_records(points[, opts])

[N, P, D] 또는 [N, P*D] 점 / 키포인트 tensor를 Lua table로 정리합니다.

  • optspoint_count / keypoint_count를 지원합니다.
  • optspoint_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])

prototype mask, mask 계수 및 탐지 상자를 목표 이미지 크기에 다시 투영합니다.

  • project_masks()는 이 함수의 별칭입니다.
  • 반환값은 tensor가 아니라 Lua mask table 목록입니다.

키포인트 및 기하 도우미

  • 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_threshold
  • max_age
  • min_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를 활성화해야 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