yxma commited on
Commit
0ca8ec8
·
verified ·
1 Parent(s): 8ea02d2

Add probe_rtm_area_intensity.py

Browse files
Files changed (1) hide show
  1. scripts/probe_rtm_area_intensity.py +216 -0
scripts/probe_rtm_area_intensity.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Probe RTM with a joint (contact_area × contact_intensity) keep rule.
3
+
4
+ For each touch, we pick the peak-deformation frame within the touch-window
5
+ (same as before), then compute two scalars on the central 50% crop:
6
+
7
+ pixel_diff = |frame - baseline| # grey-level per pixel
8
+ mask = pixel_diff > PIXEL_THRESH # ignore sensor noise
9
+ contact_area = sum(mask) # in pixels
10
+ contact_int = mean(pixel_diff[mask]) if mask.any() else 0
11
+
12
+ A touch is kept iff `contact_area >= A_min AND contact_int >= I_min`.
13
+
14
+ Outputs:
15
+ - rtm_area_intensity_scatter.png : 2D scatter of (area, intensity)
16
+ with operating-point lines drawn
17
+ - samples_100_rtm_op_<name>.png : 10x10 grid for each candidate
18
+ (A_min, I_min) operating point
19
+ """
20
+
21
+ import io, os, random, time
22
+ from glob import glob
23
+
24
+ import cv2
25
+ import numpy as np
26
+ import pyarrow.parquet as pq
27
+ import matplotlib
28
+ matplotlib.use("Agg")
29
+ import matplotlib.pyplot as plt
30
+ from PIL import Image, ImageDraw, ImageFont
31
+
32
+ ROOT = "/media/yxma/Disk1/yuxiang/mini_data/markerless/RealTactileMNIST"
33
+ OUT = "/media/yxma/Disk1/yuxiang/mini_data_parquet/assets"
34
+
35
+ PIXEL_THRESH = 10 # per-pixel grey-level threshold (noise floor)
36
+ PROBE_TOUCHES = 2500
37
+
38
+ # Candidate operating points (A_min in pixels, I_min in grey-levels)
39
+ # Central crop is 240 wide × 120 tall ≈ 28800 px ... actually our crop is
40
+ # 1/2 × 1/2 = 1/4 of frame -> for 320x240 that's 160x120 = 19,200 px
41
+ OPERATING_POINTS = [
42
+ ("strict", dict(A_min=200, I_min=20)), # large + strong
43
+ ("balanced", dict(A_min=100, I_min=18)), # default rec.
44
+ ("lenient", dict(A_min=50, I_min=15)), # accept smaller
45
+ ("area-only", dict(A_min=100, I_min=0)), # area, no intensity bar
46
+ ("intensity-only", dict(A_min=0, I_min=20)), # intensity, no area bar
47
+ ]
48
+
49
+
50
+ def decode_touch(vid_bytes):
51
+ tmpf = f"/tmp/_rtm_ai_{os.getpid()}.mp4"
52
+ with open(tmpf, "wb") as f: f.write(vid_bytes)
53
+ cap = cv2.VideoCapture(tmpf)
54
+ frames, grays = [], []
55
+ while True:
56
+ ok, fr = cap.read()
57
+ if not ok: break
58
+ frames.append(fr[:, :, ::-1])
59
+ g = cv2.cvtColor(fr, cv2.COLOR_BGR2GRAY).astype(np.float32)
60
+ h, w = g.shape
61
+ grays.append(g[h//4:3*h//4, w//4:3*w//4])
62
+ cap.release()
63
+ try: os.remove(tmpf)
64
+ except: pass
65
+ if len(frames) < 8: return None
66
+ return frames, grays
67
+
68
+
69
+ def analyse(frames, grays, ts, ts0, ts1):
70
+ """Return (peak_idx, area, intensity, peak_frame_rgb, mean_diff)."""
71
+ baseline = np.median(np.stack(grays[:5]), axis=0)
72
+ # mean-diff (the old scalar metric) for cross-comparison
73
+ deforms = [float(np.abs(g - baseline).mean()) for g in grays]
74
+ in_window = list(range(len(frames)))
75
+ try:
76
+ if ts is not None and ts0 is not None and ts1 is not None \
77
+ and len(ts) == len(frames):
78
+ in_window = [k for k, t in enumerate(ts) if ts0 <= t <= ts1]
79
+ if not in_window: in_window = list(range(len(frames)))
80
+ except Exception:
81
+ pass
82
+ peak_idx = in_window[int(np.argmax([deforms[k] for k in in_window]))]
83
+
84
+ diff = np.abs(grays[peak_idx] - baseline)
85
+ mask = diff > PIXEL_THRESH
86
+ area = int(mask.sum())
87
+ intensity = float(diff[mask].mean()) if area > 0 else 0.0
88
+ return peak_idx, area, intensity, frames[peak_idx], deforms[peak_idx]
89
+
90
+
91
+ def main():
92
+ rng = random.Random(11)
93
+ pq_files = sorted(glob(f"{ROOT}/data/*.parquet"))
94
+ bucket = [] # list of (area, intensity, mean_diff, peak_rgb, label)
95
+ t0 = time.time()
96
+ print(f"probing up to {PROBE_TOUCHES} touches...", flush=True)
97
+ for p in pq_files:
98
+ if len(bucket) >= PROBE_TOUCHES: break
99
+ pf = pq.ParquetFile(p)
100
+ for batch in pf.iter_batches(batch_size=4):
101
+ if len(bucket) >= PROBE_TOUCHES: break
102
+ cols = batch.to_pydict()
103
+ n = len(cols["label"])
104
+ for i in range(n):
105
+ if rng.random() > 0.06: continue
106
+ videos = cols["sensor_video"][i] or []
107
+ ts_seq = cols.get("time_stamp_rel_seq", [None]*n)[i] or []
108
+ t_start = cols.get("touch_start_time_rel", [None]*n)[i] or []
109
+ t_end = cols.get("touch_end_time_rel", [None]*n)[i] or []
110
+ label = cols["label"][i]
111
+ for tj, vs in enumerate(videos):
112
+ if rng.random() > 0.3: continue
113
+ if len(bucket) >= PROBE_TOUCHES: break
114
+ vb = vs.get("bytes") if isinstance(vs, dict) else None
115
+ if not vb: continue
116
+ out = decode_touch(vb)
117
+ if out is None: continue
118
+ frames, grays = out
119
+ ts = ts_seq[tj] if tj < len(ts_seq) else None
120
+ ts0 = t_start[tj] if tj < len(t_start) else None
121
+ ts1 = t_end[tj] if tj < len(t_end) else None
122
+ pidx, area, intensity, peak_rgb, md = analyse(frames, grays, ts, ts0, ts1)
123
+ bucket.append((area, intensity, md, peak_rgb, label))
124
+ if len(bucket) % 200 == 0:
125
+ dt = time.time() - t0
126
+ print(f" {len(bucket)} touches "
127
+ f"({len(bucket)/max(dt,0.01):.1f}/s)",
128
+ flush=True)
129
+ n_total = len(bucket)
130
+ print(f"\ncollected {n_total} touches in {time.time()-t0:.0f}s")
131
+ A = np.array([b[0] for b in bucket])
132
+ I = np.array([b[1] for b in bucket])
133
+ MD = np.array([b[2] for b in bucket])
134
+ print(f"area: min={A.min()} median={int(np.median(A))} mean={int(A.mean())} max={A.max()}")
135
+ print(f"intensity: min={I.min():.1f} median={np.median(I):.1f} mean={I.mean():.1f} max={I.max():.1f}")
136
+ print(f"correlation(area, intensity) = {np.corrcoef(A, I)[0,1]:.3f}")
137
+ print(f"correlation(area, mean_diff) = {np.corrcoef(A, MD)[0,1]:.3f}")
138
+
139
+ # ------------------------------------------------------------------
140
+ # 2D scatter
141
+ # ------------------------------------------------------------------
142
+ fig, ax = plt.subplots(figsize=(8.5, 6.5))
143
+ sc = ax.scatter(A, I, c=MD, s=8, alpha=0.55, cmap="magma",
144
+ edgecolor="none")
145
+ ax.set_xlabel(f"contact_area (# pixels with |diff| > {PIXEL_THRESH})",
146
+ fontsize=11)
147
+ ax.set_ylabel(f"contact_intensity (mean |diff| over those pixels)",
148
+ fontsize=11)
149
+ ax.set_title(f"Real Tactile MNIST · peak-frame (area, intensity) "
150
+ f"for {n_total} touches\n"
151
+ f"point colour = current mean-diff scalar (no longer "
152
+ f"used as the keep rule)",
153
+ fontsize=11, pad=10)
154
+ cbar = plt.colorbar(sc, ax=ax)
155
+ cbar.set_label("mean |diff| (old metric)", fontsize=10)
156
+ # Draw operating-point boundaries
157
+ colors_op = ["#d62728", "#2ca02c", "#1f77b4", "#9467bd", "#ff7f0e"]
158
+ for (name, op), col in zip(OPERATING_POINTS, colors_op):
159
+ kept = (A >= op["A_min"]) & (I >= op["I_min"])
160
+ pct = 100 * kept.sum() / n_total
161
+ ax.axvline(op["A_min"], color=col, linestyle="--", alpha=0.5, linewidth=1)
162
+ ax.axhline(op["I_min"], color=col, linestyle="--", alpha=0.5, linewidth=1)
163
+ ax.text(op["A_min"] + 5, op["I_min"] + 0.3,
164
+ f"{name}: A≥{op['A_min']}, I≥{op['I_min']} → {pct:.0f}%",
165
+ fontsize=8, color=col, fontweight="bold")
166
+ ax.set_xlim(0, max(800, A.max()*1.05))
167
+ ax.set_ylim(0, max(40, I.max()*1.05))
168
+ ax.grid(alpha=0.2)
169
+ plt.tight_layout()
170
+ out_scatter = f"{OUT}/rtm_area_intensity_scatter.png"
171
+ plt.savefig(out_scatter, dpi=140)
172
+ plt.close()
173
+ print(f"saved {out_scatter}")
174
+
175
+ # ------------------------------------------------------------------
176
+ # Per-operating-point 10x10 sample grid
177
+ # ------------------------------------------------------------------
178
+ try:
179
+ f_title = ImageFont.truetype("DejaVuSans-Bold.ttf", 18)
180
+ except Exception:
181
+ f_title = ImageFont.load_default()
182
+
183
+ for name, op in OPERATING_POINTS:
184
+ kept = [b for b in bucket if b[0] >= op["A_min"] and b[1] >= op["I_min"]]
185
+ if not kept:
186
+ print(f"op {name}: 0 kept, skip"); continue
187
+ sample = rng.sample(kept, min(100, len(kept)))
188
+ side = 144; cols = 10; pad = 4; title_h = 44
189
+ rows = (len(sample) + cols - 1) // cols
190
+ W = pad + cols * (side + pad)
191
+ H = title_h + rows * (side + pad) + pad
192
+ canvas = Image.new("RGB", (W, H), (255, 255, 255))
193
+ d = ImageDraw.Draw(canvas)
194
+ pct = 100 * len(kept) / n_total
195
+ d.text((pad + 4, 8),
196
+ f"real_tactile_mnist · '{name}' op: "
197
+ f"area ≥ {op['A_min']} & intensity ≥ {op['I_min']} "
198
+ f"· would keep {pct:.1f}% of touches",
199
+ fill=(0, 0, 0), font=f_title)
200
+ for i, (area, intensity, md, fr, lbl) in enumerate(sample):
201
+ r, c = i // cols, i % cols
202
+ x = pad + c * (side + pad)
203
+ y = title_h + r * (side + pad)
204
+ im = Image.fromarray(fr)
205
+ w, h = im.size
206
+ s = min(w, h)
207
+ im = im.crop(((w-s)//2, (h-s)//2, (w+s)//2, (h+s)//2))
208
+ im = im.resize((side, side), Image.LANCZOS)
209
+ canvas.paste(im, (x, y))
210
+ out = f"{OUT}/samples_100_rtm_op_{name}.png"
211
+ canvas.save(out, optimize=True)
212
+ print(f"saved {out} ({pct:.1f}% kept · {len(sample)} shown)")
213
+
214
+
215
+ if __name__ == "__main__":
216
+ main()