본문으로 건너뛰기
SDK Version: 2.5.0

Preprocessing

The preprocessing pipeline in DX-ModelZoo transforms input data into the format required by the model.

Module: dx_modelzoo.preprocessing

PreprocessingPipeline​

A pipeline that sequentially executes preprocessing operations defined in YAML.

class PreprocessingPipeline(Compose):
def __init__(
self,
steps_config: list[dict] | dict[str, list[dict]],
npu_mode: bool = False,
)
def __call__(self, img: np.ndarray) -> np.ndarray
ParameterTypeDescription
steps_configlist[dict] | dict[str, list[dict]]Step configuration dicts ({"type": ..., **params}), i.e. the YAML preprocessing: block. Use a dict keyed by input name for multi-input models
npu_modeboolNPU mode (skips NPU_SKIP_DEFAULT operations when True)
AttributeTypeDescription
stepslistInstantiated preprocessing operation objects built from steps_config
경고

The constructor argument is steps_config and takes config dicts, not operation instances. steps is the built result and is read-only output — passing objects (or using steps=) raises TypeError / AttributeError.

from dx_modelzoo.preprocessing import PreprocessingPipeline

pipeline = PreprocessingPipeline(
steps_config=[
{"type": "resize", "size": [256, 256]},
{"type": "centercrop", "size": [224, 224]},
]
)

Usage Example​

from dx_modelzoo.loader.model_builder import ModelBuilder

builder = ModelBuilder("resnet50_224x224.yaml")
pipeline = builder.build_preprocessing("onnx")

import cv2
img = cv2.imread("test.jpg") # (H, W, 3) BGR uint8
result = pipeline(img) # (1, 3, 224, 224) float32

NPU Skip Behavior​

NPU_SKIP_DEFAULT​

NPU_SKIP_DEFAULT = {"div", "normalize", "transpose", "expanddim", "mul", "add", "subtract"}

When npu_mode=True, operations whose types are included in this set are skipped for uint8 runtime input. For float32 input, arithmetic operations remain unless appendix.npu_skip_arithmetic overrides the behavior.

NPU Mode Caution

For target: dxnn, arithmetic operations are skipped when runtime input dtype is uint8; they remain for float32 input. Set appendix.npu_skip_arithmetic to override this behavior. Spatial transforms such as resize, centercrop, and convertcolor still run on the CPU.

NPU Skip Summary​

TypeNPU SkipReason
resize❌Spatial transform — requires CPU
centercrop❌Spatial transform — requires CPU
convertcolor❌Color conversion — requires CPU
divuint8 onlyHandled internally by NPU for uint8 input
normalizeuint8 onlyHandled internally by NPU for uint8 input
transposeuint8 onlyLayout conversion handled internally for uint8 input
expanddimuint8 onlyBatch handling handled internally for uint8 input
muluint8 onlyHandled internally by NPU for uint8 input
adduint8 onlyHandled internally by NPU for uint8 input
subtractuint8 onlyHandled internally by NPU for uint8 input

Built-in Types​

TypeSummary
resizeResize image
centercropCenter crop
convertcolorColor conversion
divDivide by scalar
normalizeMean/std normalization
transposeAxis permutation
expanddimInsert dimension
mulMultiply by scalar
addAdd scalar
subtractSubtract scalar
bgr_to_y_channelConvert BGR to Y channel
bgr_to_y_channel_uint8Convert BGR to uint8 Y channel
totensorHWC uint8 [0,255] → CHW float32 [0,1]

resize​

Resize an image.

- type: resize
size: [256, 256] # [H, W]
mode: default # torchvision | default | pad | pycls
interpolation: BILINEAR # BILINEAR | BICUBIC | NEAREST | AREA
ParameterTypeDefaultDescription
sizelist[int](required)Target size [H, W]
modestr"default"Resize mode
interpolationstr"BILINEAR"Interpolation method
ModeBackendBehavior
defaultOpenCV (cv2.resize)Plain OpenCV resize to the target size
torchvisionPIL / torchvisionMatches torchvision.transforms.Resize semantics
padOpenCVAspect-ratio preserving resize + padding (letterbox); tune with align_side, scale_method, pad_location, pad_value
pyclsOpenCVpycls-style resize convention
노트

There is no opencv or letterbox mode. Use default for OpenCV resize and pad for letterbox-style resize. Any other value raises ValueError: Invalid mode: ....

centercrop​

Center crop.

- type: centercrop
height: 224
width: 224
ParameterTypeDescription
heightintCrop height
widthintCrop width

convertcolor​

Color space conversion.

- type: convertcolor
form: BGR2RGB
ParameterTypeDescription
formstrConversion format (BGR2RGB, RGB2BGR, BGR2GRAY, etc.)

div​

Division (scaling).

- type: div
x: 255
ParameterTypeDescription
xfloatDivisor value
Automatic NPU Skip

div is included in NPU_SKIP_DEFAULT and is skipped in NPU mode.

normalize​

Mean/standard deviation normalization: (img - mean) / std

- type: normalize
mean: [0.485, 0.456, 0.406]
std: [0.229, 0.224, 0.225]
ParameterTypeDescription
meanlist[float]Per-channel mean
stdlist[float]Per-channel standard deviation

transpose​

Axis transposition (e.g., HWC → CHW).

- type: transpose
axis: [2, 0, 1]
ParameterTypeDescription
axislist[int]Axis order

expanddim​

Add a dimension (e.g., batch dimension).

- type: expanddim
axis: 0
ParameterTypeDescription
axisintAxis position to insert

mul​

Multiplication.

- type: mul
x: 2.0
ParameterTypeDescription
xfloatMultiplier value

add​

Addition.

- type: add
x: 1.0
ParameterTypeDescription
xfloatValue to add

subtract​

Subtraction.

- type: subtract
x: 128.0
ParameterTypeDescription
xfloatValue to subtract

bgr_to_y_channel​

Convert a BGR image to the Y channel (luminance). Primarily used for super-resolution models.

- type: bgr_to_y_channel

No parameters.

bgr_to_y_channel_uint8​

BGR to Y channel conversion (uint8 output). For NPU models.

- type: bgr_to_y_channel_uint8

No parameters.

totensor​

Convert HWC uint8 input in [0, 255] to CHW float32 in [0, 1].

- type: totensor

No parameters.

Equivalent to div(x=255) + transpose, but registered as a single preprocessing step.

Custom Preprocessing​

from dx_modelzoo.preprocessing import PREPROCESSING_REGISTRY

@PREPROCESSING_REGISTRY.register("my_custom_op")
class MyCustomOp:
def __init__(self, param: int = 10):
self.param = param

def __call__(self, img: np.ndarray) -> np.ndarray:
# Custom logic
return img
preprocessing:
- type: my_custom_op
param: 20
NPU Skip for Custom Operations

Custom operations are not skipped in NPU mode by default, as they are not included in NPU_SKIP_DEFAULT. If your custom operation is an arithmetic operation that should be skipped on the NPU, you must add it to the set manually.

For detailed usage, refer to the Custom Models guide.