"""ONNX 图手术:插入 / 检测「BGR→RGB 通道反转」节点。 为什么要这个 ------------ RKNN 的 ``mean_values``/``std_values`` 是**逐通道仿射**(``(x - mean[c]) / std[c]``), 只能改数值,**做不到通道重排**。想让板子直接吃 OpenCV 的 BGR 缓冲 (``model.input_format=bgr_uint8``,唯一零拷贝路径),必须在**计算图里**放一个通道反转 节点,让 NPU 顺手把 B 和 R 换回来: .. code-block:: text images (NCHW/NHWC) ──Gather(axis=C, indices=[2,1,0])──▶ portcv_images_rgb ──▶ 其余节点 这样做的好处:反转跑在 NPU 上(不占 CPU,aarch64 上省 3~6 ms/帧);颜色顺序**写死在模型里**, 不会因为现场改了配置而静默错色——错色通常只掉几个点,现场几乎发现不了。 注意 ``mean_values``/``std_values`` 仍然要按**送进来的数据**(BGR)顺序给, 因为归一化作用在 Gather **之前**的输入缓冲上。 配合 :mod:`portcv.detect.preproc` 的 ``bgr_uint8`` 与 ``scripts/onnx_bgr_input.py`` 使用。 ``onnx`` 是可选依赖,本模块只在函数内部导入它。 """ from __future__ import annotations import numpy as np #: 反通道用的 Gather 索引(BGR → RGB) BGR_INDEX = (2, 1, 0) #: 插入的 initializer 名;同时作为「这个模型已经反过通道」的标记 BGR_IDX_TENSOR = "portcv_bgr_to_rgb_idx" #: 插入节点的输出张量名 BGR_NODE_OUTPUT = "portcv_images_rgb" def _onnx(): """延迟导入 onnx(可选依赖,只有导出/转换机器需要)。""" try: import onnx # type: ignore except ImportError as exc: # pragma: no cover - 只在没装 onnx 的机器上 raise RuntimeError("需要 onnx:pip install onnx") from exc return onnx def _graph_input(graph, input_name=None): """取图的第 1 个真实输入(排除旧 IR 里重复声明成 input 的 initializer)。""" initializers = {init.name for init in graph.initializer} inputs = [value for value in graph.input if value.name not in initializers] if not inputs: raise ValueError("图里没有输入张量") if input_name: for value in inputs: if value.name == input_name: return value raise ValueError( "找不到输入 %s(可选:%s)" % (input_name, ", ".join(v.name for v in inputs)) ) return inputs[0] def channel_axis(value) -> int: """推断 4 维输入的通道轴:NCHW → 1、NHWC → 3(静态通道数必须是 3)。""" dims = value.type.tensor_type.shape.dim if len(dims) != 4: raise ValueError( "只支持 4 维输入(NCHW/NHWC),%s 是 %d 维" % (value.name, len(dims)) ) sizes = [int(dim.dim_value) for dim in dims] # 0 表示动态 if sizes[1] == 3: return 1 if sizes[3] == 3: return 3 raise ValueError( "输入 %s 形状 %s 里没看出 3 通道(第 1 维=%d、第 3 维=%d,0 表示动态);" "动态通道的模型请先固定 batch/通道再导出" % (value.name, sizes, sizes[1], sizes[3]) ) def has_channel_reversal(model) -> bool: """模型里是否已经有反通道节点(用 initializer 名或输出张量名判定)。""" if any(init.name.startswith(BGR_IDX_TENSOR) for init in model.graph.initializer): return True return any(node.output[0].startswith(BGR_NODE_OUTPUT) for node in model.graph.node if node.output) def _graph_uses(graph, tensor: str) -> bool: """图(含嵌套子图)里是否有节点直接引用 ``tensor``。""" for node in graph.node: if any(name == tensor for name in node.input): return True for attr in node.attribute: if attr.type == attr.GRAPH and _graph_uses(attr.g, tensor): return True if attr.type == attr.GRAPHS and any(_graph_uses(g, tensor) for g in attr.graphs): return True return False def _subgraph_uses(graph, tensor: str) -> bool: """``tensor`` 是否被 If/Loop **子图**引用(主图的普通消费者不算)。""" for node in graph.node: for attr in node.attribute: if attr.type == attr.GRAPH and _graph_uses(attr.g, tensor): return True if attr.type == attr.GRAPHS and any(_graph_uses(g, tensor) for g in attr.graphs): return True return False def _unique(name: str, taken) -> str: """``taken`` 里已有同名张量时加后缀,避免撞名。""" if name not in taken: return name index = 1 while "%s_%d" % (name, index) in taken: index += 1 return "%s_%d" % (name, index) def insert_channel_reversal(model, input_name=None): """在 ``model`` 的输入后插入 ``Gather(x, [2,1,0], axis=C)``,就地修改并返回信息字典。 幂等:已经插过(见 :func:`has_channel_reversal`)就返回 ``inserted=False``。 返回 ``{"inserted", "input", "output", "axis", "consumers"}``。 """ onnx = _onnx() graph = model.graph value = _graph_input(graph, input_name) axis = channel_axis(value) if has_channel_reversal(model): existing = next( (node.output[0] for node in graph.node if node.output and BGR_IDX_TENSOR in node.input), BGR_NODE_OUTPUT, ) return { "inserted": False, "input": value.name, "output": existing, "axis": axis, "consumers": 0, } if _subgraph_uses(graph, value.name): raise ValueError( "输入 %s 被 If/Loop 子图引用,自动插入不安全:请在这些子图里也插入 " "Gather([2,1,0]) 节点后再导出" % value.name ) taken = {init.name for init in graph.initializer} taken.update(out for node in graph.node for out in node.output) taken.update(item.name for item in list(graph.input) + list(graph.output)) taken.update(item.name for item in graph.value_info) idx_name = _unique(BGR_IDX_TENSOR, taken) out_name = _unique(BGR_NODE_OUTPUT, taken) graph.initializer.append( onnx.numpy_helper.from_array(np.array(BGR_INDEX, dtype=np.int64), idx_name) ) node = onnx.helper.make_node("Gather", [value.name, idx_name], [out_name], axis=axis) node.name = out_name + "_node" # 先记下原来的消费者(同一批 proto 对象),再把它们的入口改成反通道后的张量 consumers = list(graph.node) graph.node.insert(0, node) redirected = 0 for consumer in consumers: for index, name in enumerate(consumer.input): if name == value.name: consumer.input[index] = out_name redirected += 1 onnx.checker.check_model(model) return { "inserted": True, "input": value.name, "output": out_name, "axis": axis, "consumers": redirected, } def verify_reversal(before, after, input_name=None, seed: int = 0, atol: float = 1e-5): """用 ``onnx.reference`` 数值自检:反通道后的模型吃 BGR 应与原模型吃 RGB 等价。 返回 ``{"ok", "axis", "shape", "max_abs_diff", "diff_without_reversal"}``; 其中 ``diff_without_reversal`` 是「不反通道直接喂 BGR」的差异,用来判断这个节点 是否真的必需(若也是 0,说明该模型对通道顺序不敏感)。 """ from onnx.reference import ReferenceEvaluator # 只在这条自检路径用到 onnx = _onnx() value = _graph_input(before.graph, input_name) axis = channel_axis(value) shape = [int(dim.dim_value) or 1 for dim in value.type.tensor_type.shape.dim] elem = value.type.tensor_type.elem_type rng = np.random.default_rng(int(seed)) if elem == onnx.TensorProto.UINT8: data = rng.integers(0, 256, size=shape, dtype=np.uint8) elif elem == onnx.TensorProto.FLOAT: data = rng.random(shape, dtype=np.float32) else: raise ValueError("自检只支持 float32 / uint8 输入,实际 elem_type=%d" % elem) name = value.name ref = np.asarray(ReferenceEvaluator(before).run(None, {name: data})[0], dtype=np.float64) flipped = np.asarray( ReferenceEvaluator(after).run(None, {name: np.flip(data, axis=axis)})[0], dtype=np.float64 ) straight = np.asarray(ReferenceEvaluator(after).run(None, {name: data})[0], dtype=np.float64) return { "ok": bool(np.allclose(ref, flipped, atol=atol)), "axis": axis, "shape": shape, "max_abs_diff": float(np.max(np.abs(ref - flipped))), "diff_without_reversal": float(np.max(np.abs(ref - straight))), }