vpr: VprEncoder TensorRT (chi Jetson, -DVSLAM_WITH_TENSORRT=ON) + vslam_vpr_check + tools/vpr_export_onnx.py
This commit is contained in:
97
tools/vpr_export_onnx.py
Normal file
97
tools/vpr_export_onnx.py
Normal file
@@ -0,0 +1,97 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Xuat mo hinh VPR (EigenPlaces ResNet50, 2048 chieu) sang ONNX cho vslam_node, kem file mo ta
|
||||
tien xu ly; tuy chon tinh mo ta THAM CHIEU bang PyTorch cho mot DB de doi chieu ban TensorRT.
|
||||
|
||||
Tien xu ly PHAI giong het tools/vpr_eval.py bien the +clahe (noi da do 88-89% top-1 tren anh IR):
|
||||
anh IR xam -> CLAHE (clip 2.0, luoi 8x8) -> resize 512x384 (INTER_LINEAR) -> /255 -> lap 3 kenh
|
||||
-> chuan hoa ImageNet -> mo hinh (da L2 o lop cuoi).
|
||||
|
||||
Do tren Jetson (JetPack 6.1, 2026-09-30): TensorRT fp16 6.5 ms/anh, OpenCV CPU 299 ms/anh.
|
||||
OpenCV 4.2 (may dev) KHONG doc duoc ONNX nay (ReduceL2) -- khong sao: VPR chi can tren robot
|
||||
(anh mo phong den het).
|
||||
|
||||
python3 tools/vpr_export_onnx.py --out resources/vpr/eigenplaces_r50_2048_384x512.onnx
|
||||
python3 tools/vpr_export_onnx.py --out ... --ref-db DB --ref-out logs/vpr_ref.npz
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from vpr_eval import clahe, load_db # noqa: E402 -- CUNG tien xu ly noi da do
|
||||
|
||||
W, H = 512, 384
|
||||
MEAN = [0.485, 0.456, 0.406]
|
||||
STD = [0.229, 0.224, 0.225]
|
||||
|
||||
|
||||
def load_model():
|
||||
import torch
|
||||
# skip_validation: khong goi API GitHub (gioi han 60 lan/gio -> 403).
|
||||
return torch.hub.load("gmberton/eigenplaces", "get_trained_model", backbone="ResNet50",
|
||||
fc_output_dim=2048, trust_repo=True, skip_validation=True).eval()
|
||||
|
||||
|
||||
def preprocess(img_gray):
|
||||
"""Anh IR xam uint8 -> (3, H, W) float32, y nhu vpr_eval.torch_desc voi bien the +clahe."""
|
||||
x = cv2.resize(clahe(img_gray), (W, H), interpolation=cv2.INTER_LINEAR).astype(np.float32) / 255.0
|
||||
x = np.repeat(x[None], 3, axis=0)
|
||||
return (x - np.array(MEAN, np.float32)[:, None, None]) / np.array(STD, np.float32)[:, None, None]
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--out", required=True, help="duong dan .onnx (vd resources/vpr/eigenplaces_r50_2048_384x512.onnx)")
|
||||
ap.add_argument("--ref-db", default="", help="DB: tinh mo ta THAM CHIEU (PyTorch fp32) cho moi anh")
|
||||
ap.add_argument("--ref-out", default="", help=".npz: ids (int32), desc (float32 N x 2048)")
|
||||
ap.add_argument("--device", default="cuda")
|
||||
a = ap.parse_args()
|
||||
|
||||
import onnx
|
||||
import torch
|
||||
m = load_model()
|
||||
os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True)
|
||||
x = torch.from_numpy(np.random.RandomState(0).rand(1, 3, H, W).astype(np.float32))
|
||||
torch.onnx.export(m, x, a.out, input_names=["image"], output_names=["desc"], opset_version=13)
|
||||
mo = onnx.load(a.out)
|
||||
onnx.checker.check_model(mo)
|
||||
meta = dict(model="EigenPlaces ResNet50 fc 2048 (gmberton/eigenplaces, torch.hub)", input="image",
|
||||
output="desc", shape=[1, 3, H, W], clahe_clip=2.0, clahe_grid=8, resize="INTER_LINEAR",
|
||||
scale=1.0 / 255.0, mean=MEAN, std=STD, gray_to_rgb="lap 3 kenh", l2_normalized=True)
|
||||
with open(os.path.splitext(a.out)[0] + ".json", "w") as f:
|
||||
json.dump(meta, f, indent=2)
|
||||
print(f"ONNX: {a.out} ({os.path.getsize(a.out) / 1e6:.0f} MB), phep toan: "
|
||||
f"{sorted({n.op_type for n in mo.graph.node})}")
|
||||
|
||||
if a.ref_db:
|
||||
dev = a.device if torch.cuda.is_available() else "cpu"
|
||||
m = m.to(dev)
|
||||
nodes = load_db(a.ref_db)
|
||||
out, t0 = [], time.time()
|
||||
with torch.no_grad():
|
||||
for i in range(0, len(nodes), 32):
|
||||
b = np.stack([preprocess(n["img"]) for n in nodes[i:i + 32]])
|
||||
out.append(m(torch.from_numpy(b).to(dev)).float().cpu().numpy())
|
||||
desc = np.concatenate(out)
|
||||
ref_out = a.ref_out or os.path.splitext(a.out)[0] + "_ref.npz"
|
||||
np.savez_compressed(ref_out, ids=np.array([n["id"] for n in nodes], np.int32),
|
||||
desc=desc.astype(np.float32))
|
||||
print(f"mo ta tham chieu: {len(nodes)} anh tu {a.ref_db} trong {time.time() - t0:.1f} s -> {ref_out}")
|
||||
# Cung du lieu, dang nhi phan tho cho C++ (tools/vslam_vpr_check):
|
||||
# int32 N, int32 D, int32 ids[N], float32 desc[N*D].
|
||||
bin_out = os.path.splitext(ref_out)[0] + ".bin"
|
||||
with open(bin_out, "wb") as f:
|
||||
np.array([len(nodes), desc.shape[1]], np.int32).tofile(f)
|
||||
np.array([n["id"] for n in nodes], np.int32).tofile(f)
|
||||
desc.astype(np.float32).tofile(f)
|
||||
print(f" + ban nhi phan cho C++: {bin_out}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user