46 lines
1.7 KiB
Python
46 lines
1.7 KiB
Python
"""Adapt the pinned OpenCV Zoo NanoDet graph to a smaller square input."""
|
|
import hashlib
|
|
import sys
|
|
import onnx
|
|
from onnx import numpy_helper
|
|
|
|
source, output, size = sys.argv[1:4]
|
|
size = int(size)
|
|
if size < 192 or size % 32:
|
|
raise ValueError("Size must be a multiple of 32, at least 192")
|
|
with open(source, "rb") as stream:
|
|
digest = hashlib.sha256(stream.read()).hexdigest()
|
|
if digest != "4b82da9944b88577175ee23a459dce2e26e6e4be573def65b1055dc2d9720186":
|
|
raise ValueError("Unexpected upstream NanoDet artifact")
|
|
print("Original SHA-256", digest)
|
|
model = onnx.load(source)
|
|
graph = model.graph
|
|
del graph.value_info[:]
|
|
initializers = {item.name: item for item in graph.initializer}
|
|
inputs = [item for item in graph.input if item.name not in initializers]
|
|
assert len(inputs) == 1 and inputs[0].name == "input.1"
|
|
assert [d.dim_value for d in inputs[0].type.tensor_type.shape.dim] == [1, 3, 416, 416]
|
|
del graph.input[:]
|
|
graph.input.extend(inputs)
|
|
for dim in graph.input[0].type.tensor_type.shape.dim[2:]:
|
|
dim.dim_value = size
|
|
|
|
resized = set()
|
|
for node in graph.node:
|
|
if node.op_type not in ("Reshape", "Resize"):
|
|
continue
|
|
name = node.input[-1]
|
|
if name in resized:
|
|
continue
|
|
item = initializers[name]
|
|
dimensions = numpy_helper.to_array(item).copy()
|
|
if len(dimensions) >= 4 and dimensions[-2] == dimensions[-1] and dimensions[-1] in (13, 26, 52):
|
|
dimensions[-2:] = dimensions[-1] * size // 416
|
|
item.CopyFrom(numpy_helper.from_array(dimensions, name))
|
|
resized.add(name)
|
|
for index, item in enumerate(graph.output):
|
|
stride = (8, 16, 32)[index % 3]
|
|
item.type.tensor_type.shape.dim[1].dim_value = (size // stride) ** 2
|
|
onnx.checker.check_model(model)
|
|
onnx.save(model, output)
|