-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathload_data.py
More file actions
2118 lines (1784 loc) · 82.1 KB
/
Copy pathload_data.py
File metadata and controls
2118 lines (1784 loc) · 82.1 KB
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import io
import math
import os
import re
from collections import deque
import h5py
import numpy as np
def process_pressure_discrete_intervals(
pressure: np.ndarray,
max_value: float = 3072.0,
num_intervals: int = 5,
output_range: str = "uint8",
method: str = "binning",
noise_threshold: float = 500.0,
) -> np.ndarray:
"""Convert pressure to discrete interval levels.
Args:
pressure: Raw pressure array (any shape)
max_value: Maximum tactile value (default: 3072.0)
num_intervals: Discrete levels - 3/5/7 (default: 5)
output_range: 'uint8' [0,255] or 'float' [0,1] (default: 'uint8')
method: 'binning' 'linear' 'log' 'none'
noise_threshold: Noise floor for linear/log methods (default: 500.0)
Returns:
Discretized pressure array (uint8 or float32)
"""
frame = np.asarray(pressure, dtype=np.float32)
frame = np.where(np.isfinite(frame), frame, 0.0)
frame = np.clip(frame, 0.0, max_value)
if method == "binning":
if num_intervals > 1:
bins = np.linspace(0.0, max_value, num_intervals + 1, dtype=np.float32)
indices = np.digitize(frame, bins[1:-1], right=False)
levels = np.linspace(0.0, 1.0, num_intervals, dtype=np.float32)
frame = levels[indices]
else:
frame = frame / max_value
elif method == "linear":
vmin, vmax = noise_threshold, max_value
clamped = np.clip(frame, vmin, vmax)
norm = (clamped - vmin) / (vmax - vmin)
if num_intervals > 1:
levels = np.linspace(0.0, 1.0, num_intervals, dtype=np.float32)
indices = np.round(norm * (num_intervals - 1)).astype(np.int32)
frame = levels[np.clip(indices, 0, num_intervals - 1)]
else:
frame = norm
elif method == "log":
vmin, vmax = noise_threshold, max_value
clamped = np.clip(frame, vmin, vmax)
log_val = np.log10(clamped)
norm = (log_val - np.log10(vmin)) / (np.log10(vmax) - np.log10(vmin))
if num_intervals > 1:
levels = np.linspace(0.0, 1.0, num_intervals, dtype=np.float32)
indices = np.round(norm * (num_intervals - 1)).astype(np.int32)
frame = levels[np.clip(indices, 0, num_intervals - 1)]
else:
frame = norm
else:
# no discretization, use normalized pressure (0-1)
frame = frame / max_value
if output_range == "uint8":
return (frame * 255.0).astype(np.uint8)
elif output_range == "float":
return frame.astype(np.float32)
else:
raise ValueError(f"Invalid output_range: {output_range}. Use 'uint8' or 'float'")
def load_hdf5(file_path):
"""Load data from an HDF5 file.
Args:
file_path (str): Path to the HDF5 file
Returns:
dict: Dictionary containing all datasets from the file
"""
with h5py.File(file_path, 'r') as f:
return {key: _load_hdf5_item(f[key]) for key in f.keys()}
def list_hdf5_keys(file_path, recursive=False, root=None):
"""List keys contained within an HDF5 file.
Args:
file_path (str): Path to the HDF5 file
recursive (bool): If True, include nested keys in their full paths.
root (str | None): Optional path within the file to start listing from.
Returns:
list[str]: Collection of keys (top-level by default, full paths if recursive)
"""
def _collect_keys(group, prefix=""):
keys = []
for name, item in group.items():
full_name = f"{prefix}/{name}" if prefix else name
keys.append(full_name)
if recursive and isinstance(item, h5py.Group):
keys.extend(_collect_keys(item, full_name))
return keys
with h5py.File(file_path, 'r') as f:
if not root:
return _collect_keys(f)
obj = f[root]
if isinstance(obj, h5py.Dataset):
return [root]
keys = [root]
keys.extend(_collect_keys(obj, prefix=root))
return keys
def _require_data_group(h5file, file_path):
"""Retrieve the `data` group from an HDF5 file.
Raises:
KeyError: If 'data' group is not found
"""
if "data" not in h5file:
raise KeyError(f"No 'data' group found in '{file_path}'.")
return h5file["data"]
def _numeric_suffix(value):
match = re.search(r"(\d+)$", value or "")
return int(match.group(1)) if match else None
def _resolve_demo_name(data_group, requested_demo):
"""
Resolve a requested demo id to an actual name inside the `data` group.
Supports exact matches (e.g., 'grocery_clip_000') and aliases that share the same
numeric suffix (e.g., 'demo_00'). When suffix matching fails, falls back to ordering.
"""
if requested_demo in data_group:
return requested_demo
target_index = _numeric_suffix(requested_demo)
if target_index is None:
return None
names = sorted(data_group.keys())
for name in names:
if _numeric_suffix(name) == target_index:
return name
if 0 <= target_index < len(names):
return names[target_index]
return None
_HAND_CONNECTIONS = [
(0, 1), (1, 2), (2, 3), (3, 4), # Thumb
(0, 5), (5, 6), (6, 7), (7, 8), # Index
(0, 9), (9, 10), (10, 11), (11, 12), # Middle
(0, 13), (13, 14), (14, 15), (15, 16), # Ring
(0, 17), (17, 18), (18, 19), (19, 20), # Pinky
]
_POSE_COLORS = {
"left_hand_landmarks": (66, 165, 245),
"right_hand_landmarks": (244, 81, 96),
}
def export_demo(file_path, demo_id, output_path, skip_keys=None):
"""Export an individual demo to a separate HDF5 file.
Args:
file_path (str): Path to the source HDF5 file.
demo_id (str): Demo identifier under the `data` group.
output_path (str): Destination path for the exported HDF5.
skip_keys (Iterable[str] | None): Optional top-level datasets/groups to remove.
Raises:
KeyError: If demo is not found
"""
skip = set(skip_keys or [])
with h5py.File(file_path, 'r') as src:
data_group = _require_data_group(src, file_path)
resolved_demo = _resolve_demo_name(data_group, demo_id)
if resolved_demo is None:
available = ", ".join(list(data_group.keys())[:5])
raise KeyError(f"Demo '{demo_id}' not found in '{file_path}'. Available demos include: {available}")
demo_group = data_group[resolved_demo]
with h5py.File(output_path, 'w') as dst:
src.copy(demo_group, dst, name=demo_id)
if skip:
out_group = dst[demo_id]
for key in skip:
if key in out_group:
del out_group[key]
def load_all_demos(file_path, demos=None, skip_keys=None):
"""Load one or more demos from the `data` group of an HDF5 file.
Args:
file_path (str): Path to the HDF5 file.
demos (Iterable[str] | None): Demo ids to load (e.g., {"demo_00"}).
Loads all demos when omitted.
skip_keys (Iterable[str] | None): Dataset/group names within each demo to skip.
Returns:
dict: Mapping of demo id to loaded content.
Raises:
KeyError: If requested demos are not found
"""
skip = set(skip_keys or [])
with h5py.File(file_path, 'r') as f:
data_group = _require_data_group(f, file_path)
if demos is None:
selected = sorted(data_group.keys())
else:
selected = []
missing = []
for name in demos:
resolved = _resolve_demo_name(data_group, name)
if resolved is None:
missing.append(name)
else:
selected.append(resolved)
if missing:
available = ", ".join(list(data_group.keys())[:5])
raise KeyError(f"Demo ids not found: {', '.join(missing)}. Available demos include: {available}")
loaded = {}
for demo in selected:
group = data_group[demo]
loaded[demo] = {
key: _load_hdf5_item(group[key])
for key in group.keys()
if key not in skip
}
return loaded
def _decode_attr(value):
"""Best-effort conversion of HDF5 attribute values to python strings."""
if value is None:
return None
if isinstance(value, bytes):
return value.decode("utf-8")
if isinstance(value, np.ndarray):
if value.shape == ():
return _decode_attr(value.item())
return None
return str(value)
def _get_demo_dataset(src, resolved_demo, dataset_name):
"""Get dataset from resolved demo path.
Raises:
KeyError: If dataset is not found
TypeError: If path points to a group instead of dataset
"""
demo_dataset_path = f"data/{resolved_demo}/{dataset_name}"
if demo_dataset_path not in src:
raise KeyError(f"Dataset '{dataset_name}' not found for demo '{resolved_demo}'.")
dataset = src[demo_dataset_path]
if not isinstance(dataset, h5py.Dataset):
raise TypeError(f"'{demo_dataset_path}' is not a dataset.")
return dataset
def load_hdf5_dataset(file_path, dataset_name):
"""Load a specific dataset from an HDF5 file.
Args:
file_path (str): Path to the HDF5 file
dataset_name (str): Name of the dataset to load
Returns:
numpy.ndarray: The requested dataset
Raises:
KeyError: If dataset is not found
TypeError: If the path points to a group instead of dataset
"""
with h5py.File(file_path, 'r') as f:
if dataset_name not in f:
raise KeyError(f"Dataset '{dataset_name}' not found in '{file_path}'.")
obj = f[dataset_name]
if isinstance(obj, h5py.Group):
raise TypeError(f"'{dataset_name}' is an HDF5 group. Provide the full path to a dataset.")
return obj[()]
def _load_hdf5_item(obj):
"""
Recursively load datasets or groups from an HDF5 object.
"""
if isinstance(obj, h5py.Dataset):
return obj[()]
if isinstance(obj, h5py.Group):
return {name: _load_hdf5_item(obj[name]) for name in obj.keys()}
raise TypeError(f"Unknown HDF5 object type: {type(obj)}")
def export_rgb_frames(
file_path,
demo_id,
output_dir,
dataset_name="rgb_images_jpeg",
target_size=(480, 480),
channel_order=None,
):
"""Extract RGB frames stored as JPEG byte arrays for a demo and write them to disk.
Args:
file_path (str): Path to the source HDF5 file.
demo_id (str): Demo identifier under the `data` group.
output_dir (str): Directory where frames will be written.
dataset_name (str): Dataset name containing the encoded RGB frames.
target_size (tuple[int, int] | None): Resize frames to this resolution.
channel_order (str | None): Override color channel order when saving (e.g., "bgr").
Raises:
KeyError: If demo or dataset is not found
"""
with h5py.File(file_path, "r") as src:
data_group = _require_data_group(src, file_path)
resolved_demo = _resolve_demo_name(data_group, demo_id)
if resolved_demo is None:
available = ", ".join(list(data_group.keys())[:5])
raise KeyError(f"Demo '{demo_id}' not found in '{file_path}'. Available demos include: {available}")
dataset = _get_demo_dataset(src, resolved_demo, dataset_name)
os.makedirs(output_dir, exist_ok=True)
from PIL import Image, ImageEnhance
attr_order = _decode_attr(dataset.attrs.get("channel_order"))
attr_order = attr_order or _decode_attr(dataset.attrs.get("color_order"))
active_order = (channel_order or attr_order or "rgb").lower()
for idx, entry in enumerate(dataset):
buffer = entry.tobytes() if isinstance(entry, np.ndarray) else bytes(entry)
image = Image.open(io.BytesIO(buffer)).convert("RGB")
if active_order == "bgr":
# swap channels
image = Image.fromarray(np.array(image)[:, :, ::-1], mode="RGB")
if target_size:
image = image.resize(target_size, Image.BILINEAR)
# ---- adjust brightness & contrast here ----
brightness_factor = 1.2 # >1 = brighter, <1 = darker
contrast_factor = 1.2 # >1 = more contrast, <1 = less
enhancer = ImageEnhance.Brightness(image)
image = enhancer.enhance(brightness_factor)
enhancer = ImageEnhance.Contrast(image)
image = enhancer.enhance(contrast_factor)
# ------------------------------------------
frame_path = os.path.join(output_dir, f"{demo_id}_{idx:05d}.jpg")
image.save(frame_path, format="JPEG", quality=95)
def export_tactile_heatmaps_raw(
file_path,
demo_id,
output_dir,
process_fn,
dataset_names=("left_pressure", "right_pressure"),
cmap="viridis",
target_size=(480, 480),
max_value=3072.0,
method="none",
noise_threshold=500.0,
gaussian_sigma=0.0,
temporal_alpha=0.2,
):
"""Convert tactile pressure samples using custom processing function (e.g., raw normalization).
Args:
file_path (str): Path to the source HDF5 file.
demo_id (str): Demo identifier under the `data` group.
output_dir (str): Directory where heatmaps will be written.
process_fn: Function to process pressure data (e.g., process_pressure_discrete_intervals).
dataset_names (Iterable[str]): Names of tactile datasets to export.
cmap (str): Matplotlib colormap name (fallback to grayscale if unavailable).
target_size (tuple[int, int] | None): Resize each image to this size.
max_value (float): Maximum tactile value expected; values above are clipped.
method (str): Processing method passed to process_fn.
noise_threshold (float): Noise threshold passed to process_fn.
gaussian_sigma (float): Spatial Gaussian smoothing sigma in pixels. <=0 disables.
temporal_alpha (float): Temporal smoothing factor (0-1). <=0 disables.
Raises:
KeyError: If demo is not found
"""
try:
import matplotlib.cm as cm
colormap = cm.get_cmap(cmap)
except ImportError:
colormap = None
max_value = float(max_value) if max_value is not None else 3072.0
if max_value <= 0.0:
max_value = 3072.0
with h5py.File(file_path, "r") as src:
data_group = _require_data_group(src, file_path)
resolved_demo = _resolve_demo_name(data_group, demo_id)
if resolved_demo is None:
available = ", ".join(list(data_group.keys())[:5])
raise KeyError(f"Demo '{demo_id}' not found in '{file_path}'. Available demos include: {available}")
demo_prefix = f"data/{resolved_demo}"
for name in dataset_names:
dataset_path = f"{demo_prefix}/{name}"
if dataset_path not in src:
continue
dset = src[dataset_path]
if not isinstance(dset, h5py.Dataset):
continue
target_dir = os.path.join(output_dir, name)
os.makedirs(target_dir, exist_ok=True)
prev_frame = None
for idx, sample in enumerate(dset):
frame = _prepare_tactile_frame(sample, dset.attrs)
# Apply spatial Gaussian smoothing before processing
if gaussian_sigma and gaussian_sigma > 0.0:
frame = _apply_gaussian(frame, gaussian_sigma)
# Apply temporal smoothing
if (
prev_frame is not None
and temporal_alpha is not None
and 0.0 < temporal_alpha < 1.0
):
frame = temporal_alpha * frame + (1.0 - temporal_alpha) * prev_frame
prev_frame = frame
# Use custom processing function
normalized = process_fn(
pressure=frame,
max_value=max_value,
num_intervals=1, # No discretization for raw
output_range="float",
method=method,
noise_threshold=noise_threshold,
)
# Apply colormap
if colormap is None:
pixels = (normalized * 255.0).astype(np.uint8)
mode = "L"
else:
rgba = (colormap(normalized) * 255.0).astype(np.uint8)
pixels = rgba[..., :3]
mode = "RGB"
from PIL import Image
image = Image.fromarray(pixels, mode=mode)
if target_size:
image = image.resize(target_size, _HEATMAP_RESAMPLE)
filename = os.path.join(target_dir, f"{demo_id}_{idx:05d}.png")
image.save(filename)
def export_tactile_heatmaps(
file_path,
demo_id,
output_dir,
dataset_names=("left_pressure", "right_pressure"),
cmap="viridis",
target_size=(480, 480),
max_value=3072.0,
num_intervals=5,
method="binning",
gaussian_sigma=0.0,
temporal_alpha=0.2,
):
"""Convert tactile pressure samples into discrete-interval heatmap images (PNG).
Args:
file_path (str): Path to the source HDF5 file.
demo_id (str): Demo identifier under the `data` group.
output_dir (str): Directory where heatmaps will be written.
dataset_names (Iterable[str]): Names of tactile datasets to export.
cmap (str): Matplotlib colormap name (fallback to grayscale if unavailable).
target_size (tuple[int, int] | None): Resize each image to this size.
max_value (float): Maximum tactile value expected; values above are clipped.
num_intervals (int): Number of discrete intervals to map across the range (3, 6, or 9).
method (str): Processing method ('binning', 'linear', or 'log').
gaussian_sigma (float): Spatial Gaussian smoothing sigma in pixels. <=0 disables.
temporal_alpha (float): Temporal smoothing factor (0-1). <=0 disables.
Raises:
KeyError: If demo is not found
"""
try:
import matplotlib.cm as cm
colormap = cm.get_cmap(cmap)
except ImportError:
colormap = None
max_value = float(max_value) if max_value is not None else 3072.0
if max_value <= 0.0:
max_value = 3072.0
num_intervals = int(num_intervals) if num_intervals else 0
if num_intervals < 2:
num_intervals = 5
with h5py.File(file_path, "r") as src:
data_group = _require_data_group(src, file_path)
resolved_demo = _resolve_demo_name(data_group, demo_id)
if resolved_demo is None:
available = ", ".join(list(data_group.keys())[:5])
raise KeyError(f"Demo '{demo_id}' not found in '{file_path}'. Available demos include: {available}")
demo_prefix = f"data/{resolved_demo}"
for name in dataset_names:
dataset_path = f"{demo_prefix}/{name}"
if dataset_path not in src:
continue
dset = src[dataset_path]
if not isinstance(dset, h5py.Dataset):
continue
target_dir = os.path.join(output_dir, name)
os.makedirs(target_dir, exist_ok=True)
prev_frame = None
for idx, sample in enumerate(dset):
frame = _prepare_tactile_frame(sample, dset.attrs)
if gaussian_sigma and gaussian_sigma > 0.0:
frame = _apply_gaussian(frame, gaussian_sigma)
if (
prev_frame is not None
and temporal_alpha is not None
and 0.0 < temporal_alpha < 1.0
):
frame = temporal_alpha * frame + (1.0 - temporal_alpha) * prev_frame
prev_frame = frame
image = _render_heatmap(
frame,
colormap,
max_value=max_value,
num_intervals=num_intervals,
method=method,
)
if target_size:
image = image.resize(target_size, _HEATMAP_RESAMPLE)
filename = os.path.join(target_dir, f"{demo_id}_{idx:05d}.png")
image.save(filename)
def export_tactile_voronoi(
file_path,
demo_id,
output_dir,
dataset_names=("left_pressure", "right_pressure"),
cmap="viridis", # kept for API compatibility (unused)
target_size=(480, 480),
max_value=3072.0,
num_intervals=5, # kept for API compatibility (unused)
method="binning", # kept for API compatibility (unused)
gaussian_sigma=0.2, # extra smoothing at the very end (optional)
temporal_alpha=0.2, # optional temporal smoothing (per-hand)
):
"""
Export tactile frames rendered like visualize_tactile_realtime:
1) Reweight 16x16 taxels using precomputed kernels (voronoi labels)
2) Fill voronoi polygons with value-to-color
3) Apply masked Gaussian blending (no bleeding to background)
4) (Optional) Temporal smoothing per stream
Signature, directory structure, and file naming match export_tactile_heatmaps.
"""
import json, cv2
from xml.etree import ElementTree as ET
# --- Locate mapping + SVG like the realtime script does ---
def _find_first_existing(cands):
for p in cands:
if p and os.path.exists(p):
return p
return None
mapping_json = _find_first_existing([
"point_weight_mappings_large.json",
# "point_weight_mappings_small.json",
os.path.join(os.path.dirname(__file__), "data", "point_weight_mappings_large.json"),
# os.path.join(os.path.dirname(__file__), "data", "point_weight_mappings_small.json"),
])
svg_file = _find_first_existing([
"voronoi_regions_large.svg",
# "voronoi_regions_small.svg",
os.path.join(os.path.dirname(__file__), "data", "voronoi_regions_large.svg"),
# os.path.join(os.path.dirname(__file__), "data", "voronoi_regions_small.svg"),
])
if mapping_json is None or svg_file is None:
raise FileNotFoundError(
"Could not find mapping JSON or Voronoi SVG. "
"Expected one of {point_weight_mappings_[small|large].json} and {voronoi_regions_[small|large].svg}."
)
mapping = json.load(open(mapping_json, "r"))
# --- Parse Voronoi polygons from SVG (id -> [(x,y), ...]) ---
tree = ET.parse(svg_file)
root = tree.getroot()
ns = {'svg': 'http://www.w3.org/2000/svg'}
voronoi_polygons = {
poly.attrib['id']: [
tuple(map(float, p.split(','))) for p in poly.attrib['points'].strip().split()
]
for poly in root.findall('.//svg:polygon', ns)
}
# --- Geometry extents + shift to positive canvas with margin ---
all_points = np.array([pt for pts in voronoi_polygons.values() for pt in pts], dtype=np.float32)
min_x, min_y = all_points.min(axis=0)
max_x, max_y = all_points.max(axis=0)
overlay_width = int(max_x - min_x) + 20
overlay_height = int(max_y - min_y) + 20
shift = np.array([10 - min_x, 10 - min_y], dtype=np.float32)
polygon_pts_shifted = {
label: np.array([(x + shift[0], y + shift[1]) for (x, y) in pts], dtype=np.int32)
for label, pts in voronoi_polygons.items()
}
# --- Weight kernels (copied/adapted from realtime) ---
def _precompute_weights(_mapping, is_left=True):
W = {}
for label, neighbors in _mapping.items():
mat = np.zeros((16, 16), dtype=np.float32)
total = 0.0
for q in ['NE', 'NW', 'SW', 'SE']:
src, dist = neighbors.get(q, ('N/A', 0.0))
if src != 'N/A':
y, x = map(int, src.split('-'))
if not is_left:
# mirror for right as in realtime
y, x = 15 - x, 15 - y
w = 1.0 / dist if dist and dist > 1e-3 else 1e6
mat[y, x] += w
total += w
if total > 0:
mat /= total
W[label] = mat
return W
left_weights = _precompute_weights(mapping, is_left=True)
right_weights = _precompute_weights(mapping, is_left=False)
def _interpolate_fast(pressure16x16, precomputed):
return {label: float(np.sum(W * pressure16x16)) for label, W in precomputed.items()}
# --- Color mapping (HSV→BGR for OpenCV; clamp using max_value) ---
def _hsv_to_bgr(h, s, v):
h = h % 360.0
c = v * s
x = c * (1 - abs((h / 60.0) % 2 - 1))
m = v - c
if h < 60: rp, gp, bp = c, x, 0
elif h < 120: rp, gp, bp = x, c, 0
elif h < 180: rp, gp, bp = 0, c, x
elif h < 240: rp, gp, bp = 0, x, c
elif h < 300: rp, gp, bp = x, 0, c
else: rp, gp, bp = c, 0, x
return (int((bp + m) * 255), int((gp + m) * 255), int((rp + m) * 255))
def _value_to_color(v, vmin=0.0, vmax=3072.0):
clamped = float(np.clip(v, vmin, vmax))
norm = (clamped - vmin) / max(vmax - vmin, 1e-6)
hue = norm * 240.0 # 0=red -> 240=blue (same convention)
return _hsv_to_bgr(hue, 1.0, 1.0)
# --- Masked Gaussian blur (avoid bleeding outside polygons) ---
def _compute_kernel_size(w, h):
base = int(max(15, 0.03 * min(w, h)))
return 3
return base + 1 if base % 2 == 0 else base
def _masked_gaussian_blur(img_bgr, mask_binary, ksize):
img = img_bgr.astype(np.float32) / 255.0
mask = (mask_binary.astype(np.float32) / 255.0)
weighted = cv2.GaussianBlur(img * mask[..., None], (ksize, ksize), 0)
norm = cv2.GaussianBlur(mask, (ksize, ksize), 0)
norm = np.maximum(norm, 1e-6)[..., None]
blended = weighted / norm
mask3 = (mask > 0.5).astype(np.float32)[..., None]
out = img * (1.0 - mask3) + blended * mask3
return (out * 255.0).clip(0, 255).astype(np.uint8)
# --- Single-hand overlay (returns RGB PIL image if available, else BGR numpy) ---
def _render_hand_overlay(interp_dict, mirror_left, target_size_xy, vmax):
canvas = np.ones((overlay_height, overlay_width, 3), dtype=np.uint8) * 255
for label, pts in polygon_pts_shifted.items():
color = _value_to_color(interp_dict.get(label, 0.0), vmin=0.0, vmax=vmax)
cv2.fillPoly(canvas, [pts], color)
mask = (canvas != 255).any(axis=2).astype(np.uint8) * 255
ksize = _compute_kernel_size(overlay_width, overlay_height)
canvas = _masked_gaussian_blur(canvas, mask, ksize)
if mirror_left:
canvas = cv2.flip(canvas, 1) # horizontal flip
# Resize to requested target_size and convert to PIL if available
canvas = cv2.resize(canvas, (int(target_size_xy[0]), int(target_size_xy[1])), interpolation=cv2.INTER_CUBIC)
if Image is not None:
# Convert BGR→RGB for saving with PIL
rgb = cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB)
return Image.fromarray(rgb, mode="RGB")
return canvas # BGR numpy array
# --- Read HDF5, iterate frames per dataset like export_tactile_heatmaps ---
vmax = float(max_value) if max_value and max_value > 0 else 3072.0
width, height = target_size
with h5py.File(file_path, "r") as src:
data_group = _require_data_group(src, file_path)
resolved = _resolve_demo_name(data_group, demo_id)
if resolved is None:
available = ", ".join(list(data_group.keys())[:5])
raise KeyError(f"Demo '{demo_id}' not found in '{file_path}'. Available demos include: {available}")
# Maintain a simple per-dataset temporal buffer
prev_interps = {}
for name in dataset_names:
dpath = f"data/{resolved}/{name}"
if dpath not in src:
continue
dset = src[dpath]
if not isinstance(dset, h5py.Dataset):
continue
is_left = "left" in name.lower()
W = left_weights if is_left else right_weights
out_dir = os.path.join(output_dir, name)
os.makedirs(out_dir, exist_ok=True)
prev_map = None
for idx, sample in enumerate(dset):
# Prepare 16×16 pressure grid (reuses your helper)
grid = _prepare_tactile_frame(sample, dset.attrs)
# Ensure 16x16 float32
grid = np.asarray(grid, dtype=np.float32)
if grid.shape != (16, 16):
# Best-effort reshape if metadata mismatch
grid = cv2.resize(grid, (16, 16), interpolation=cv2.INTER_AREA).astype(np.float32)
# Interpolate onto voronoi labels
interp = _interpolate_fast(grid, W)
# Temporal smoothing on interpolated scalar field (per label)
if prev_map is not None and temporal_alpha and 0.0 < temporal_alpha < 1.0:
for k in interp.keys():
p = prev_map.get(k, interp[k])
interp[k] = temporal_alpha * interp[k] + (1.0 - temporal_alpha) * p
prev_map = interp
# Render single-hand overlay in the realtime style
img_obj = _render_hand_overlay(
interp_dict=interp,
mirror_left=is_left, # realtime flips left
target_size_xy=(width, height),
vmax=vmax,
)
# Save
fname = os.path.join(out_dir, f"{demo_id}_{idx:05d}.png")
if Image is not None and isinstance(img_obj, Image.Image):
img_obj.save(fname, format="PNG")
else:
# Fallback if PIL missing: img_obj is BGR numpy
cv2.imwrite(fname, img_obj)
def export_tactile_layout(
file_path,
demo_id,
output_dir,
dataset_names=("left_pressure", "right_pressure"),
cmap="viridis", # kept for API compatibility (unused)
target_size=(480, 480),
max_value=3072.0,
num_intervals=5, # kept for API compatibility (unused)
method="binning", # kept for API compatibility (unused)
gaussian_sigma=0.0, # not used here (kept for API compatibility)
temporal_alpha=0.0, # optional per-frame EMA on grid before drawing
):
"""
Export frames by drawing each valid taxel at its 2D layout position
(the 'layout map' renderer). Naming, dirs, and signature mirror
export_tactile_heatmaps/export_tactile_voronoi.
"""
import os, json, cv2, numpy as np
# --- helpers (nested) -----------------------------------------------------
def _find_first_existing(cands):
for p in cands:
if p and os.path.exists(p):
return p
return None
def _load_layout_json():
# expects {"positions": {"r-c": {"x":..,"y":.., "mano_faceid":[...]}, ...},
# "erasedNodes": ["r-c", ...]}
layout_json = _find_first_existing([
"handLayoutNewest.json",
os.path.join(os.path.dirname(__file__), "data", "handLayoutNewest.json"),
os.path.join(os.path.dirname(__file__), "handLayoutNewest.json"),
])
if layout_json is None:
raise FileNotFoundError(
"Could not find handLayoutNewest.json (layout). "
"Place it next to load_data.py or in ./data/."
)
with open(layout_json, "r") as f:
d = json.load(f)
layout = d["positions"]
erased = set(d.get("erasedNodes", []))
return layout, erased
def _draw_layout_frame(pressure16, layout, erased_nodes, canvas_size, vmin, vmax):
Ht, Wt = canvas_size[1], canvas_size[0]
# normalize on global min/max
norm = ((pressure16 - vmin) / max(vmax - vmin, 1e-6)).clip(0, 1)
# collect valid xy and also compute a nice aspect-preserving scale
valid = {
nid: (float(pos["x"]), float(pos["y"]))
for nid, pos in layout.items()
if nid not in erased_nodes
}
xs = [x for (x, y) in valid.values()]
ys = [y for (x, y) in valid.values()]
min_x, max_x = min(xs), max(xs)
min_y, max_y = min(ys), max(ys)
pad = 20.0
Wsrc = (max_x - min_x) + 2 * pad
Hsrc = (max_y - min_y) + 2 * pad
# fit into target canvas
scale = min(Wt / Wsrc, Ht / Hsrc)
ox = (Wt - scale * Wsrc) * 0.5
oy = (Ht - scale * Hsrc) * 0.5
canvas = np.zeros((Ht, Wt, 3), dtype=np.uint8)
for nid, (x, y) in valid.items():
r, c = map(int, nid.split('-'))
val = float(norm[r, c])
# viridis via OpenCV
color = cv2.applyColorMap(
np.array([[int(val * 255)]], dtype=np.uint8), cv2.COLORMAP_VIRIDIS
)[0, 0]
px = int(ox + scale * (x - min_x + pad))
py = int(oy + scale * (y - min_y + pad))
cv2.circle(canvas, (px, py), radius=max(3, int(3 * scale)), color=tuple(int(k) for k in color), thickness=-1)
return canvas
# --- pipeline -------------------------------------------------------------
layout, erased_nodes = _load_layout_json()
width, height = target_size
import h5py
with h5py.File(file_path, "r") as src:
data_group = _require_data_group(src, file_path)
resolved = _resolve_demo_name(data_group, demo_id)
if resolved is None:
raise KeyError(f"Demo '{demo_id}' not found in '{file_path}'.")
for name in dataset_names:
dpath = f"data/{resolved}/{name}"
if dpath not in src or not isinstance(src[dpath], h5py.Dataset):
continue
dset = src[dpath]
# Compute global vmin/vmax over valid nodes for consistent colors
vals = []
for sample in dset:
grid = _prepare_tactile_frame(sample, dset.attrs)
grid = np.asarray(grid, dtype=np.float32)
if grid.shape != (16, 16):
grid = cv2.resize(grid, (16, 16), interpolation=cv2.INTER_AREA).astype(np.float32)
vals.append(grid)
stack = np.stack(vals, 0) if vals else np.zeros((0, 16, 16), np.float32)
# mask only nodes present in layout & not erased
valid_mask = np.zeros((16, 16), dtype=bool)
for nid in layout.keys():
if nid in erased_nodes:
continue
r, c = map(int, nid.split('-'))
valid_mask[r, c] = True
if stack.size:
vmin = float(stack[:, valid_mask].min())
vmax = float(stack[:, valid_mask].max())
else:
vmin, vmax = 0.0, 1.0
# optional temporal EMA
prev = None
out_dir = os.path.join(output_dir, name)
os.makedirs(out_dir, exist_ok=True)
for idx, grid in enumerate(vals):
if temporal_alpha and prev is not None:
grid = temporal_alpha * grid + (1.0 - temporal_alpha) * prev
prev = grid
img = _draw_layout_frame(grid, layout, erased_nodes, (width, height), vmin, vmax)
cv2.imwrite(os.path.join(out_dir, f"{demo_id}_{idx:05d}.png"), img)
return True
def export_tactile_mano(
file_path,
demo_id,
output_dir,
dataset_names=("left_pressure", "right_pressure"),
cmap="viridis",
target_size=(480, 480),
max_value=3072.0,
num_intervals=5,
method="binning",
gaussian_sigma=0.0,
temporal_alpha=0.4,
index=[], # <<< NEW: a single index or an iterable of indices
):
"""
Export frames by projecting taxels onto a MANO mesh and rendering with pyrender.
Also export selected mesh frames (vertex/face/color) to OBJ when idx in `index`.
"""
import os, json, cv2, numpy as np, h5py, trimesh
from matplotlib import cm
from pyrenderer import ManoRenderer
# --- small helpers -------------------------------------------------------
def _as_set(x):
# accept int or iterable
if isinstance(x, int):
return {x}
try:
return set(x)
except Exception:
return {int(x)}
def _find_first_existing(cands):
for p in cands:
if p and os.path.exists(p):
return p
return None
def _load_layout_json():
layout_json = _find_first_existing([
"handLayoutNewest_meshid.json",
os.path.join(os.path.dirname(__file__), "data", "handLayoutNewest_meshid.json"),