302 lines
15 KiB
Python
302 lines
15 KiB
Python
#!/usr/bin/env python3
|
||
"""Xuat anh ban do 2D + 3D tu mot DB RTAB-Map cua vslam_cpp, de bao cao.
|
||
|
||
Doc thang DB (sqlite, chi doc) -- khong can build hay chay vslam_node:
|
||
2D : luoi cuc bo (LiDAR) cua tung node, ghep theo pose DA TOI UU bang log-odds
|
||
(ProbHit 0.7 / ProbMiss 0.4, kep 0.1192-0.971 -- mac dinh RTAB-Map), cong
|
||
lop vat can camera (cung luat voi runtime) va quy dao.
|
||
3D : depth tung node -> diem (calib da gom nghieng + nang banh) -> pose toi uu
|
||
-> voxel 5 cm, chi giu o >= --hits node thay. Anh xien: tu chieu phoi
|
||
canh bang numpy (ti le that), ve xa truoc gan sau; san = ban do 2D LiDAR.
|
||
|
||
Mac dinh --hits / --obs khop voxel.min_node_hits / voxel.obstacle_z_* trong
|
||
configuration_files/slam.yaml luc viet script; doi yaml thi truyen lai tham so.
|
||
|
||
Ra OUTDIR: map2d.png, map2d_lidar.png, map3d_top.png, map3d_view.png,
|
||
map3d_view2.png, map3d.ply, thong_so.txt. Can numpy + matplotlib.
|
||
|
||
Chay tu goc repo:
|
||
python3 tools/render_map.py resources/maps/<db> report/<ngay> [--hits 3] [--obs 0.15 0.55] [--dec 4]
|
||
"""
|
||
import argparse, datetime, math, os, sqlite3, struct, zlib
|
||
import numpy as np
|
||
|
||
RES = 0.05
|
||
FREE_RGB, WALL_RGB, CAM_RGB, TRAJ_RGB = (0.88, 0.88, 0.88), (0.25, 0.25, 0.25), (0.95, 0.55, 0.10), (0.85, 0.10, 0.10)
|
||
|
||
|
||
def decode_depth(blob):
|
||
"""Data.depth: "DEPTHRVL" + rows, cols + RVL (VLE nibble, zigzag delta)."""
|
||
assert blob[:8] == b"DEPTHRVL"
|
||
rows, cols = struct.unpack_from("<ii", blob, 8)
|
||
words = np.frombuffer(blob[16:] + b"\0" * 4, dtype="<u4")
|
||
n = rows * cols
|
||
out = np.zeros(n, dtype=np.uint16)
|
||
st = {"i": 0, "word": 0, "nib": 0}
|
||
|
||
def vle():
|
||
value, bits = 0, 29
|
||
while True:
|
||
if st["nib"] == 0:
|
||
st["word"] = int(words[st["i"]]); st["i"] += 1; st["nib"] = 8
|
||
nibble = st["word"] & 0xF0000000
|
||
value |= ((nibble << 1) & 0xFFFFFFFF) >> bits
|
||
st["word"] = (st["word"] << 4) & 0xFFFFFFFF
|
||
st["nib"] -= 1; bits -= 3
|
||
if not (nibble & 0x80000000): return value
|
||
|
||
k, prev = 0, 0
|
||
while k < n:
|
||
z = vle(); k += z
|
||
nz = vle()
|
||
for _ in range(nz):
|
||
p = vle(); delta = (p >> 1) ^ -(p & 1)
|
||
prev = (prev + delta) & 0xFFFF
|
||
out[k] = prev; k += 1
|
||
return out.reshape(rows, cols)
|
||
|
||
|
||
def decode_calib(b):
|
||
"""Data.calibration: 11 int header, K (double), bo qua D/R/P, T 3x4 float (base <- optical)."""
|
||
hdr = struct.unpack_from("<11i", b, 0)
|
||
nK, nD, nR, nP, nT = hdr[6:11]
|
||
o = 44
|
||
K = np.array(struct.unpack_from(f"<{nK}d", b, o)).reshape(3, 3); o += 8 * nK + 8 * (nD + nR + nP)
|
||
T = np.array(struct.unpack_from(f"<{nT}f", b, o)).reshape(3, 4)
|
||
return hdr, K, T
|
||
|
||
|
||
def mat(blob):
|
||
return zlib.decompress(blob[:-12]) # 12 byte cuoi = rows, cols, type
|
||
|
||
|
||
def logit(p):
|
||
return math.log(p / (1 - p))
|
||
|
||
|
||
def keys(p, res):
|
||
i = np.floor(p / res).astype(np.int64) + (1 << 20)
|
||
return (i[:, 0] << 42) | (i[:, 1] << 21) | i[:, 2]
|
||
|
||
|
||
def unkeys(k, res):
|
||
x = ((k >> 42) & 0x1FFFFF) - (1 << 20)
|
||
y = ((k >> 21) & 0x1FFFFF) - (1 << 20)
|
||
z = (k & 0x1FFFFF) - (1 << 20)
|
||
return (np.stack([x, y, z], 1).astype(np.float64) + 0.5) * res
|
||
|
||
|
||
def oblique(path, layers, azim, elev, title, zr, dpi=200, size=(12.0, 7.5)):
|
||
"""layers: [(xyz Nx3, rgb 3, canh_m)]. Chieu phoi canh, ve xa truoc gan sau."""
|
||
import matplotlib.pyplot as plt
|
||
from matplotlib.colorbar import ColorbarBase
|
||
from matplotlib.colors import Normalize
|
||
from matplotlib.lines import Line2D
|
||
from matplotlib.patches import Patch
|
||
xyz = np.concatenate([l[0] for l in layers])
|
||
rgb = np.concatenate([np.tile(l[1], (len(l[0]), 1)) if np.ndim(l[1]) == 1 else l[1] for l in layers])
|
||
side = np.concatenate([np.full(len(l[0]), l[2]) for l in layers])
|
||
lo, hi = xyz.min(0), xyz.max(0)
|
||
tgt = (lo + hi) / 2; tgt[2] = 0.3
|
||
dist = 1.5 * max(hi[0] - lo[0], hi[1] - lo[1])
|
||
az, el = math.radians(azim), math.radians(elev)
|
||
back = np.array([math.cos(el) * math.cos(az), math.cos(el) * math.sin(az), math.sin(el)])
|
||
f = -back
|
||
r = np.cross(f, [0.0, 0.0, 1.0]); r /= np.linalg.norm(r)
|
||
u = np.cross(r, f)
|
||
v = xyz - (tgt + dist * back)
|
||
dep = v @ f
|
||
x, y = (v @ r) / dep, (v @ u) / dep
|
||
order = np.argsort(-dep)
|
||
|
||
fig = plt.figure(figsize=size)
|
||
ax = fig.add_axes([0, 0, 1, 0.93]); ax.axis("off")
|
||
wpx, hpx = size[0] * dpi, size[1] * 0.93 * dpi
|
||
scale = 0.97 * min(wpx / np.ptp(x), hpx / np.ptp(y)) # px / don vi chieu, 2 truc bang nhau
|
||
cx, cy = (x.max() + x.min()) / 2, (y.max() + y.min()) / 2
|
||
ax.set_xlim(cx - wpx / scale / 2, cx + wpx / scale / 2)
|
||
ax.set_ylim(cy - hpx / scale / 2, cy + hpx / scale / 2)
|
||
pt = side / dep * scale * 72.0 / dpi # canh o vuong (point)
|
||
ax.scatter(x[order], y[order], s=pt[order] ** 2, c=rgb[order], marker="s", linewidths=0)
|
||
ax.legend(handles=[Patch(color=FREE_RGB, label="sàn trống (bản đồ 2D LiDAR)"),
|
||
Patch(color=WALL_RGB, label="tường (LiDAR)"),
|
||
Line2D([], [], color=TRAJ_RGB, lw=2, label="quỹ đạo robot")],
|
||
loc="lower right", fontsize=9, framealpha=0.9)
|
||
cax = fig.add_axes([0.03, 0.08, 0.012, 0.35])
|
||
ColorbarBase(cax, cmap=plt.get_cmap("viridis"), norm=Normalize(*zr)).set_label("độ cao voxel (m)")
|
||
fig.text(0.5, 0.965, title, ha="center", va="center", fontsize=13)
|
||
fig.savefig(path, dpi=dpi); plt.close(fig)
|
||
|
||
|
||
def main():
|
||
ap = argparse.ArgumentParser()
|
||
ap.add_argument("db"); ap.add_argument("out")
|
||
ap.add_argument("--hits", type=int, default=3)
|
||
ap.add_argument("--obs", type=float, nargs=2, default=(0.15, 0.55))
|
||
ap.add_argument("--zrange", type=float, nargs=2, default=(0.05, 2.0))
|
||
ap.add_argument("--dec", type=int, default=4)
|
||
a = ap.parse_args()
|
||
os.makedirs(a.out, exist_ok=True)
|
||
|
||
c = sqlite3.connect(f"file:{a.db}?mode=ro", uri=True).cursor()
|
||
ids_b, poses_b = c.execute("select opt_ids, opt_poses from Admin").fetchone()
|
||
ids = np.frombuffer(mat(ids_b), dtype=np.int32)
|
||
P = np.frombuffer(mat(poses_b), dtype=np.float32).reshape(-1, 3, 4).astype(np.float64)
|
||
pose = {int(i): P[k] for k, i in enumerate(ids)}
|
||
links = dict(c.execute("select type, count(*) from Link group by type").fetchall())
|
||
t0, t1 = c.execute("select min(stamp), max(stamp) from Node").fetchone()
|
||
print(f"{len(pose)} node toi uu, lien ket: {links}")
|
||
|
||
# ---------------- 2D: log-odds tu luoi cuc bo ----------------
|
||
lh, lm = logit(0.7), logit(0.4)
|
||
lo, hi = logit(0.1192), logit(0.971)
|
||
per_node = []
|
||
for nid, ob, em in c.execute("select id, obstacle_cells, empty_cells from Data where obstacle_cells is not null or empty_cells is not null order by id"):
|
||
if nid not in pose: continue
|
||
T = pose[nid]
|
||
out = []
|
||
for blob in (em, ob):
|
||
if blob is None: out.append(np.zeros((0, 2))); continue
|
||
q = np.frombuffer(mat(blob), dtype=np.float32).reshape(-1, 2).astype(np.float64)
|
||
out.append(q @ T[:2, :2].T + T[:2, 3])
|
||
per_node.append(out)
|
||
allp = np.concatenate([np.concatenate(x) for x in per_node if len(x[0]) + len(x[1])])
|
||
ext = allp.max(0) - allp.min(0) # kich thuoc that, khong tinh le 1 m
|
||
xmin, ymin = allp.min(0) - 1.0; xmax, ymax = allp.max(0) + 1.0
|
||
W, H = int((xmax - xmin) / RES) + 1, int((ymax - ymin) / RES) + 1
|
||
L = np.zeros((H, W)); seen = np.zeros((H, W), bool)
|
||
for em, ob in per_node:
|
||
for pts, d in ((em, lm), (ob, lh)):
|
||
if not len(pts): continue
|
||
ix = ((pts[:, 0] - xmin) / RES).astype(int); iy = ((pts[:, 1] - ymin) / RES).astype(int)
|
||
flat = np.unique(iy * W + ix)
|
||
L.flat[flat] = np.clip(L.flat[flat] + d, lo, hi); seen.flat[flat] = True
|
||
occ, free = seen & (L > 0), seen & (L < 0)
|
||
|
||
def cells(mask):
|
||
iy, ix = np.nonzero(mask)
|
||
return np.stack([xmin + (ix + 0.5) * RES, ymin + (iy + 0.5) * RES], 1)
|
||
|
||
# ---------------- 3D: depth -> voxel dem node ----------------
|
||
node_keys, npts = [], 0
|
||
for nid, blob, cal in c.execute("select id, depth, calibration from Data where depth is not null order by id"):
|
||
if nid not in pose or blob is None or cal is None: continue
|
||
hdr, K, Tc = decode_calib(cal)
|
||
w, h = hdr[4], hdr[5]
|
||
d = decode_depth(blob).reshape(h, w)[::a.dec, ::a.dec].astype(np.float64) * 0.001
|
||
v, u = np.nonzero((d > 0.22) & (d < 4.0))
|
||
z = d[v, u]; u = u * a.dec; v = v * a.dec
|
||
p = np.stack([(u - K[0, 2]) * z / K[0, 0], (v - K[1, 2]) * z / K[1, 1], z], 1)
|
||
p = p @ Tc[:, :3].T + Tc[:, 3] # base_footprint (z tu san)
|
||
T = pose[nid]; p = p @ T[:, :3].T + T[:, 3] # map
|
||
p = p[(p[:, 2] >= a.zrange[0]) & (p[:, 2] <= a.zrange[1])]
|
||
npts += len(p)
|
||
node_keys.append(np.unique(keys(p, RES)))
|
||
k, cnt = np.unique(np.concatenate(node_keys), return_counts=True)
|
||
vox = unkeys(k[cnt >= a.hits], RES)
|
||
print(f"3D: {npts} diem -> {len(k)} voxel, giu {len(vox)} voxel (>= {a.hits} node)")
|
||
obs = vox[(vox[:, 2] >= a.obs[0]) & (vox[:, 2] <= a.obs[1])]
|
||
|
||
traj = np.array([pose[i][:2, 3] for i in sorted(pose)])
|
||
plen = float(np.linalg.norm(np.diff(traj, axis=0), axis=1).sum())
|
||
|
||
import matplotlib
|
||
matplotlib.use("Agg")
|
||
import matplotlib.pyplot as plt
|
||
|
||
oix = ((obs[:, 0] - xmin) / RES).astype(int); oiy = ((obs[:, 1] - ymin) / RES).astype(int)
|
||
ok = (oix >= 0) & (oix < W) & (oiy >= 0) & (oiy < H)
|
||
cam = np.zeros((H, W), bool); cam[oiy[ok], oix[ok]] = True
|
||
cam &= ~occ
|
||
extent = (xmin, xmin + W * RES, ymin, ymin + H * RES)
|
||
|
||
# ---------------- anh 2D (co / khong lop camera) ----------------
|
||
for name, with_cam in (("map2d.png", True), ("map2d_lidar.png", False)):
|
||
img = np.full((H, W, 3), 0.80)
|
||
img[free] = 1.0
|
||
img[occ] = 0.10
|
||
if with_cam: img[cam] = CAM_RGB
|
||
fig, ax = plt.subplots(figsize=(10, 10 * H / W + 0.8))
|
||
ax.imshow(img, origin="lower", extent=extent, interpolation="nearest")
|
||
ax.plot(traj[:, 0], traj[:, 1], color="#1f77b4", lw=1.2, label="quỹ đạo robot")
|
||
ax.plot(*traj[0], "o", color="green", ms=7, label="xuất phát")
|
||
ax.plot(*traj[-1], "s", color="red", ms=7, label="kết thúc")
|
||
if with_cam:
|
||
ax.plot([], [], "s", color=CAM_RGB, label=f"vật cản từ camera ({a.obs[0]:.2f}–{a.obs[1]:.2f} m)")
|
||
ax.plot([], [], "s", color="0.1", label="tường / vật cản (LiDAR)")
|
||
ax.set_xlabel("x (m)"); ax.set_ylabel("y (m)"); ax.set_aspect("equal")
|
||
src = "LiDAR + camera" if with_cam else "chỉ LiDAR"
|
||
ax.set_title(f"Bản đồ 2D ({src}) — {len(pose)} node, {links.get(2, 0) // 2} liên kết ICP, {ext[0]:.1f} × {ext[1]:.1f} m")
|
||
ax.legend(loc="upper right", fontsize=8, framealpha=0.9)
|
||
fig.tight_layout(); fig.savefig(os.path.join(a.out, name), dpi=200); plt.close(fig)
|
||
|
||
# ---------------- anh 3D: tu tren xuong, nen = ban do 2D mo ----------------
|
||
bx0, by0 = vox[:, :2].min(0) - 1.0; bx1, by1 = vox[:, :2].max(0) + 1.0
|
||
bg = np.full((H, W, 3), 0.95); bg[free] = 1.0; bg[occ] = 0.72
|
||
hmap = np.full((H, W), np.nan) # moi cot 5 cm: do cao voxel cao nhat
|
||
vix = ((vox[:, 0] - xmin) / RES).astype(int); viy = ((vox[:, 1] - ymin) / RES).astype(int)
|
||
okv = (vix >= 0) & (vix < W) & (viy >= 0) & (viy < H)
|
||
np.fmax.at(hmap, (viy[okv], vix[okv]), vox[okv, 2])
|
||
fig, ax = plt.subplots(figsize=(9, 9 * (by1 - by0) / (bx1 - bx0)))
|
||
ax.imshow(bg, origin="lower", extent=extent, interpolation="nearest")
|
||
im = ax.imshow(hmap, origin="lower", extent=extent, interpolation="nearest", cmap="viridis", vmin=a.zrange[0], vmax=a.zrange[1])
|
||
ax.plot(traj[:, 0], traj[:, 1], color="red", lw=1.0, label="quỹ đạo robot")
|
||
ax.plot([], [], "s", color="0.72", label="tường LiDAR (nền)")
|
||
ax.set_xlim(bx0, bx1); ax.set_ylim(by0, by1)
|
||
ax.set_xlabel("x (m)"); ax.set_ylabel("y (m)")
|
||
ax.set_title(f"Bản đồ 3D nhìn từ trên — {len(vox)} voxel 5 cm, màu = độ cao điểm cao nhất")
|
||
from mpl_toolkits.axes_grid1 import make_axes_locatable
|
||
cax = make_axes_locatable(ax).append_axes("right", size="3%", pad=0.1)
|
||
fig.colorbar(im, cax=cax, label="độ cao tính từ sàn (m)"); ax.legend(loc="upper right", fontsize=8)
|
||
fig.tight_layout(); fig.savefig(os.path.join(a.out, "map3d_top.png"), dpi=200, bbox_inches="tight"); plt.close(fig)
|
||
|
||
# ---------------- anh 3D: 2 goc xien, ti le that ----------------
|
||
def crop(p):
|
||
return p[(p[:, 0] >= bx0) & (p[:, 0] <= bx1) & (p[:, 1] >= by0) & (p[:, 1] <= by1)]
|
||
|
||
def at_z(p, z):
|
||
return np.column_stack([p, np.full(len(p), z)])
|
||
|
||
tp = [traj[0]]
|
||
for p0, p1 in zip(traj[:-1], traj[1:]):
|
||
n = max(1, int(np.linalg.norm(p1 - p0) / 0.03))
|
||
tp.extend(p0 + (p1 - p0) * (j / n) for j in range(1, n + 1))
|
||
tp = np.array(tp)
|
||
cmap = plt.get_cmap("viridis")
|
||
vcol = np.array(cmap(np.clip((vox[:, 2] - a.zrange[0]) / (a.zrange[1] - a.zrange[0]), 0, 1)))[:, :3]
|
||
layers = [(at_z(crop(cells(free)), 0.0), np.array(FREE_RGB), RES),
|
||
(at_z(crop(cells(occ)), 0.0), np.array(WALL_RGB), RES),
|
||
(at_z(tp, 0.03), np.array(TRAJ_RGB), 0.08),
|
||
(vox, vcol, RES)]
|
||
for name, azim, elev in (("map3d_view.png", -35, 38), ("map3d_view2.png", 145, 38)):
|
||
oblique(os.path.join(a.out, name), layers, azim, elev,
|
||
f"Bản đồ 3D (góc xiên, tỉ lệ thật) — voxel 5 cm thấy từ >= {a.hits} node", a.zrange)
|
||
|
||
# ---------------- PLY ----------------
|
||
rgb = (vcol * 255).astype(np.uint8)
|
||
with open(os.path.join(a.out, "map3d.ply"), "w") as fp:
|
||
fp.write(f"ply\nformat ascii 1.0\nelement vertex {len(vox)}\nproperty float x\nproperty float y\nproperty float z\n"
|
||
"property uchar red\nproperty uchar green\nproperty uchar blue\nend_header\n")
|
||
for (x, y, z), (r, g, b) in zip(vox, rgb):
|
||
fp.write(f"{x:.3f} {y:.3f} {z:.3f} {r} {g} {b}\n")
|
||
|
||
# ---------------- thong so ----------------
|
||
stats = [
|
||
f"DB: {os.path.basename(a.db)} ({os.path.getsize(a.db) / 1e6:.0f} MB)",
|
||
f"Bắt đầu quét: {datetime.datetime.fromtimestamp(t0):%Y-%m-%d %H:%M:%S}, thời gian {(t1 - t0) / 60:.1f} phút",
|
||
f"Quãng đường robot (quỹ đạo tối ưu): {plen:.1f} m",
|
||
f"Node (keyframe): {len(pose)}; liên kết odom: {links.get(0, 0) // 2}; liên kết ICP (gần theo không gian): {links.get(2, 0) // 2}; đóng vòng toàn cục: {links.get(1, 0) // 2}",
|
||
f"Bản đồ 2D: {ext[0]:.1f} x {ext[1]:.1f} m, ô {RES * 100:.0f} cm; vùng trống đã quét {free.sum() * RES * RES:.0f} m2; "
|
||
f"{int(occ.sum())} ô tường (LiDAR); {int(cam.sum())} ô vật cản chỉ camera thấy (cao {a.obs[0]:.2f}-{a.obs[1]:.2f} m)",
|
||
f"Bản đồ 3D: {npts} điểm depth -> {len(k)} voxel {RES * 100:.0f} cm -> giữ {len(vox)} voxel được >= {a.hits} node thấy; "
|
||
f"cao {a.zrange[0]:.2f}-{a.zrange[1]:.2f} m; vùng {bx1 - bx0 - 2:.1f} x {by1 - by0 - 2:.1f} m",
|
||
]
|
||
with open(os.path.join(a.out, "thong_so.txt"), "w", encoding="utf-8") as fp:
|
||
fp.write("\n".join(stats) + "\n")
|
||
print("\n".join(stats))
|
||
print("xong ->", a.out)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|