yxma commited on
Commit
028cafc
·
verified ·
1 Parent(s): bf617c2

Add probe_rtm_thresholds.py

Browse files
Files changed (1) hide show
  1. scripts/probe_rtm_thresholds.py +146 -0
scripts/probe_rtm_thresholds.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Probe RTM at multiple peak-deformation thresholds.
3
+
4
+ Samples ~1500 touches, computes peak-within-window deformation for each,
5
+ then for each threshold (0.5, 0.7, 1.0, 1.5, 2.0) randomly draws 100
6
+ touches from the kept subset and assembles a 10x10 sample grid.
7
+
8
+ Output: /media/yxma/Disk1/yuxiang/mini_data_parquet/assets/samples_100_rtm_tau_{tau}.png
9
+ """
10
+
11
+ import io, os, random, time
12
+ from glob import glob
13
+
14
+ import cv2
15
+ import numpy as np
16
+ import pyarrow.parquet as pq
17
+ from PIL import Image, ImageDraw, ImageFont
18
+
19
+ ROOT = "/media/yxma/Disk1/yuxiang/mini_data/markerless/RealTactileMNIST"
20
+ OUT = "/media/yxma/Disk1/yuxiang/mini_data_parquet/assets"
21
+ N_TOUCHES = 2500 # how many touches to sample for the probe
22
+ TAUS = [0.5, 0.7, 1.0, 1.5, 2.0]
23
+ GRID_SIDE = 144
24
+ COLS = 10
25
+ ROWS = 10
26
+
27
+
28
+ def pick_peak(vid_bytes, ts, ts0, ts1):
29
+ """Decode video bytes; return (peak_rgb, peak_deform, peak_idx) or None."""
30
+ tmpf = f"/tmp/_rtm_probe_{os.getpid()}.mp4"
31
+ with open(tmpf, "wb") as f: f.write(vid_bytes)
32
+ cap = cv2.VideoCapture(tmpf)
33
+ frames, grays = [], []
34
+ while True:
35
+ ok, fr = cap.read()
36
+ if not ok: break
37
+ frames.append(fr[:, :, ::-1])
38
+ g = cv2.cvtColor(fr, cv2.COLOR_BGR2GRAY).astype(np.float32)
39
+ h, w = g.shape
40
+ grays.append(g[h//4:3*h//4, w//4:3*w//4])
41
+ cap.release()
42
+ try: os.remove(tmpf)
43
+ except: pass
44
+ if len(frames) < 8: return None
45
+ baseline = np.median(np.stack(grays[:5]), axis=0)
46
+ deforms = [float(np.abs(g - baseline).mean()) for g in grays]
47
+ in_window = list(range(len(frames)))
48
+ try:
49
+ if ts is not None and ts0 is not None and ts1 is not None \
50
+ and len(ts) == len(frames):
51
+ in_window = [k for k, t in enumerate(ts) if ts0 <= t <= ts1]
52
+ if not in_window: in_window = list(range(len(frames)))
53
+ except Exception: pass
54
+ peak_idx = in_window[int(np.argmax([deforms[k] for k in in_window]))]
55
+ return frames[peak_idx], deforms[peak_idx], peak_idx
56
+
57
+
58
+ def main():
59
+ rng = random.Random(42)
60
+ pq_files = sorted(glob(f"{ROOT}/data/*.parquet"))
61
+ # Subsample 0.5% of rows -> each row has 256 touches -> we hit plenty
62
+ SUBSAMPLE_ROW = 0.05
63
+
64
+ bucket = [] # list of (peak_deform, frame_rgb, label)
65
+ t0 = time.time()
66
+ for p in pq_files:
67
+ if len(bucket) >= N_TOUCHES: break
68
+ pf = pq.ParquetFile(p)
69
+ for batch in pf.iter_batches(batch_size=4):
70
+ if len(bucket) >= N_TOUCHES: break
71
+ cols = batch.to_pydict()
72
+ n = len(cols["label"])
73
+ for i in range(n):
74
+ if rng.random() > SUBSAMPLE_ROW: continue
75
+ if len(bucket) >= N_TOUCHES: break
76
+ videos = cols["sensor_video"][i] or []
77
+ ts_seq = cols.get("time_stamp_rel_seq", [None]*n)[i] or []
78
+ t_start = cols.get("touch_start_time_rel", [None]*n)[i] or []
79
+ t_end = cols.get("touch_end_time_rel", [None]*n)[i] or []
80
+ label = cols["label"][i]
81
+ for tj, vs in enumerate(videos):
82
+ if rng.random() > 0.3: continue
83
+ if len(bucket) >= N_TOUCHES: break
84
+ vb = vs.get("bytes") if isinstance(vs, dict) else None
85
+ if not vb: continue
86
+ ts = ts_seq[tj] if tj < len(ts_seq) else None
87
+ ts0 = t_start[tj] if tj < len(t_start) else None
88
+ ts1 = t_end[tj] if tj < len(t_end) else None
89
+ out = pick_peak(vb, ts, ts0, ts1)
90
+ if out is None: continue
91
+ fr, d, idx = out
92
+ bucket.append((d, fr, label))
93
+ if len(bucket) % 200 == 0:
94
+ dt = time.time() - t0
95
+ print(f"collected {len(bucket)} touches "
96
+ f"({len(bucket)/max(dt,0.01):.1f}/s)", flush=True)
97
+ print(f"\ntotal collected: {len(bucket)} touches in {time.time()-t0:.0f}s")
98
+ deforms = np.array([b[0] for b in bucket])
99
+ print(f"peak-deform stats: min={deforms.min():.2f} "
100
+ f"median={np.median(deforms):.2f} mean={deforms.mean():.2f} "
101
+ f"max={deforms.max():.2f}")
102
+
103
+ # Build grids
104
+ try:
105
+ f_title = ImageFont.truetype("DejaVuSans-Bold.ttf", 18)
106
+ except Exception:
107
+ f_title = ImageFont.load_default()
108
+
109
+ for tau in TAUS:
110
+ kept = [b for b in bucket if b[0] >= tau]
111
+ n_kept = len(kept)
112
+ if n_kept == 0:
113
+ print(f"tau={tau}: 0 frames kept, skip")
114
+ continue
115
+ sample = rng.sample(kept, min(COLS*ROWS, n_kept))
116
+ n_pick = len(sample)
117
+ rows = (n_pick + COLS - 1) // COLS
118
+ pad = 4
119
+ title_h = 44
120
+ W = pad + COLS * (GRID_SIDE + pad)
121
+ H = title_h + rows * (GRID_SIDE + pad) + pad
122
+ canvas = Image.new("RGB", (W, H), (255, 255, 255))
123
+ d = ImageDraw.Draw(canvas)
124
+ pct = 100 * n_kept / len(bucket)
125
+ d.text((pad + 4, 8),
126
+ f"real_tactile_mnist · peak-deform τ ≥ {tau} · "
127
+ f"would keep {pct:.1f}% of touches · showing {n_pick} "
128
+ f"randomly drawn samples",
129
+ fill=(0, 0, 0), font=f_title)
130
+ for i, (deform, fr, lbl) in enumerate(sample):
131
+ r, c = i // COLS, i % COLS
132
+ x = pad + c * (GRID_SIDE + pad)
133
+ y = title_h + r * (GRID_SIDE + pad)
134
+ im = Image.fromarray(fr)
135
+ w, h = im.size
136
+ s = min(w, h)
137
+ im = im.crop(((w-s)//2, (h-s)//2, (w+s)//2, (h+s)//2))
138
+ im = im.resize((GRID_SIDE, GRID_SIDE), Image.LANCZOS)
139
+ canvas.paste(im, (x, y))
140
+ out = f"{OUT}/samples_100_rtm_tau_{tau:.1f}.png"
141
+ canvas.save(out, optimize=True)
142
+ print(f"saved {out} (kept fraction={pct:.1f}% · {n_pick} samples shown)")
143
+
144
+
145
+ if __name__ == "__main__":
146
+ main()