1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
| import time import serial import numpy as np from math import sin, cos, radians import matplotlib.pyplot as plt from collections import deque
PORT = "/dev/cu.usbmodem1301" BAUD = 115200
SENSOR_OFFSET_MM = 60.0 PAN_OFFSET_DEG = 90.0
READY_TIMEOUT_S = 10 START_TIMEOUT_S = 10 SCAN_TIMEOUT_S = 300
X_SWEEP_DEG = 90.0 X_SAMPLE_DEG = 1.0 Y_MAX_DEG = 90.0 Y_STEP_DEG = 1.0
DIST_MIN_MM = 30.0 DIST_MAX_MM = 800.0
NEIGHBOR_WIN = 1 NEIGHBOR_ABS_MM = 35.0 NEIGHBOR_REL = 0.06 MIN_GOOD_NEIGHBORS = 2
CONNECT_8 = True MIN_COMPONENT_SIZE = 300
KEEP_EVERY_N = 1
def wait_for_token(ser, token: str, timeout_s: float, echo=True): token = token.lower() t0 = time.time() while time.time() - t0 < timeout_s: line = ser.readline().decode("utf-8", errors="ignore").strip() if not line: continue low = line.lower() if echo: print("RX:", line) if token in low: return True if low.startswith("error"): return False return False
def parse_csv3(line: str): parts = line.split(",") if len(parts) != 3: return None try: return float(parts[0]), float(parts[1]), float(parts[2]) except ValueError: return None
def to_xyz(x_deg_raw, y_deg_raw, dist_raw_mm): r = dist_raw_mm + SENSOR_OFFSET_MM pan = radians(x_deg_raw - PAN_OFFSET_DEG) tilt = radians(y_deg_raw)
z = r * sin(tilt) plane = r * cos(tilt) x = plane * cos(pan) y = plane * sin(pan) return x, y, z
def build_grid_axes(): x_vals = np.round(np.arange(0.0, X_SWEEP_DEG + 1e-6, X_SAMPLE_DEG), 2) y_vals = np.round(np.arange(0.0, Y_MAX_DEG + 1e-6, Y_STEP_DEG), 2) return x_vals, y_vals
def neighbor_consistency_mask(dist_grid): """ Keep a point if it agrees with enough neighbors in a window. Agreement threshold is max(NEIGHBOR_ABS_MM, NEIGHBOR_REL * dist). """ H, W = dist_grid.shape valid = ~np.isnan(dist_grid) keep = np.zeros((H, W), dtype=bool)
for r in range(H): r0 = max(0, r - NEIGHBOR_WIN) r1 = min(H, r + NEIGHBOR_WIN + 1) for c in range(W): if not valid[r, c]: continue
c0 = max(0, c - NEIGHBOR_WIN) c1 = min(W, c + NEIGHBOR_WIN + 1)
center = dist_grid[r, c] window = dist_grid[r0:r1, c0:c1].reshape(-1) window = window[~np.isnan(window)]
if window.size <= 1: continue
thr = max(NEIGHBOR_ABS_MM, NEIGHBOR_REL * center) close = np.sum(np.abs(window - center) <= thr) - 1 if close >= MIN_GOOD_NEIGHBORS: keep[r, c] = True
return keep
def largest_connected_component(mask): """ Return a mask containing only the largest connected component of True cells. """ H, W = mask.shape visited = np.zeros_like(mask, dtype=bool)
if CONNECT_8: neighbors = [(-1, -1), (-1, 0), (-1, 1), ( 0, -1), ( 0, 1), ( 1, -1), ( 1, 0), ( 1, 1)] else: neighbors = [(-1, 0), (1, 0), (0, -1), (0, 1)]
best_cells = None best_size = 0
for r in range(H): for c in range(W): if not mask[r, c] or visited[r, c]: continue
q = deque([(r, c)]) visited[r, c] = True cells = [(r, c)]
while q: rr, cc = q.popleft() for dr, dc in neighbors: nr, nc = rr + dr, cc + dc if 0 <= nr < H and 0 <= nc < W and mask[nr, nc] and not visited[nr, nc]: visited[nr, nc] = True q.append((nr, nc)) cells.append((nr, nc))
size = len(cells) if size > best_size: best_size = size best_cells = cells
out = np.zeros_like(mask, dtype=bool) if best_cells is not None and best_size >= MIN_COMPONENT_SIZE: for r, c in best_cells: out[r, c] = True
return out, best_size
def set_equalish_3d(ax, X, Y, Z): if len(X) < 10: return x_min, x_max = float(np.min(X)), float(np.max(X)) y_min, y_max = float(np.min(Y)), float(np.max(Y)) z_min, z_max = float(np.min(Z)), float(np.max(Z))
cx = 0.5 * (x_min + x_max) cy = 0.5 * (y_min + y_max) cz = 0.5 * (z_min + z_max)
span = max(x_max - x_min, y_max - y_min, z_max - z_min) if span <= 1e-6: return half = 0.5 * span ax.set_xlim(cx - half, cx + half) ax.set_ylim(cy - half, cy + half) ax.set_zlim(cz - half, cz + half)
x_vals, y_vals = build_grid_axes() nx, ny = len(x_vals), len(y_vals)
dist_grid = np.full((ny, nx), np.nan, dtype=np.float32) x_to_i = {float(x): i for i, x in enumerate(x_vals)} y_to_j = {float(y): j for j, y in enumerate(y_vals)}
ser = serial.Serial(PORT, BAUD, timeout=1) ser.reset_input_buffer() time.sleep(1.5)
print("Waiting for 'ready'...") wait_for_token(ser, "ready", READY_TIMEOUT_S, echo=True)
print("TX: go") ser.write(b"go\n") ser.flush()
print("Waiting for 'start'...") wait_for_token(ser, "start", START_TIMEOUT_S, echo=True)
print("Receiving data into range image...") t0 = time.time() n_recv = 0 n_store = 0
try: while True: if time.time() - t0 > SCAN_TIMEOUT_S: print("Safety timeout stopping.") break
line = ser.readline().decode("utf-8", errors="ignore").strip() if not line: continue
low = line.lower() if "done" in low: print("Scan complete!") break if low.startswith("error"): print("Arduino error:", line) break if low in ("ready", "start"): continue
parsed = parse_csv3(line) if not parsed: continue
x_deg, y_deg, dist = parsed n_recv += 1
if dist < DIST_MIN_MM or dist > DIST_MAX_MM: continue
xq = float(np.round(x_deg / X_SAMPLE_DEG) * X_SAMPLE_DEG) yq = float(np.round(y_deg / Y_STEP_DEG) * Y_STEP_DEG) xq = float(np.round(xq, 2)) yq = float(np.round(yq, 2))
if xq in x_to_i and yq in y_to_j: dist_grid[y_to_j[yq], x_to_i[xq]] = dist n_store += 1
if n_recv % 3000 == 0: print(f"recv={n_recv} stored={n_store}")
finally: ser.close()
raw_valid = np.count_nonzero(~np.isnan(dist_grid)) print(f"Raw valid grid points: {raw_valid}")
print("Filtering: neighbor consistency...") mask_consistent = neighbor_consistency_mask(dist_grid) print(f"Consistent points: {np.count_nonzero(mask_consistent)}")
print("Filtering: largest connected component...") mask_lcc, lcc_size = largest_connected_component(mask_consistent) print(f"Largest component size: {lcc_size}")
final_mask = mask_lcc if lcc_size >= MIN_COMPONENT_SIZE else mask_consistent
ys_idx, xs_idx = np.where(final_mask) if KEEP_EVERY_N > 1: sel = np.arange(len(xs_idx)) % KEEP_EVERY_N == 0 ys_idx, xs_idx = ys_idx[sel], xs_idx[sel]
Xlist, Ylist, Zlist = [], [], [] for j, i in zip(ys_idx, xs_idx): x_deg = float(x_vals[i]) y_deg = float(y_vals[j]) d = float(dist_grid[j, i]) x, y, z = to_xyz(x_deg, y_deg, d) Xlist.append(x); Ylist.append(y); Zlist.append(z)
X = np.array(Xlist, dtype=np.float32) Y = np.array(Ylist, dtype=np.float32) Z = np.array(Zlist, dtype=np.float32)
print(f"Final plotted points: {len(X)}")
plt.figure() ax = plt.axes(projection="3d") sc = ax.scatter(X, Y, Z, s=3, c=Z, cmap="viridis", alpha=0.9)
ax.set_xlabel("X (mm)") ax.set_ylabel("Y (mm)") ax.set_zlabel("Z (mm)") ax.set_title("Scanned Object Section (denoised + largest region)")
set_equalish_3d(ax, X, Y, Z) plt.colorbar(sc, ax=ax, shrink=0.6, label="Z (mm)") plt.show()
|