File size: 9,337 Bytes
b584148
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Inspect preprocessed DROID data to verify structure and visualize tracks.

Checks:
1. Data structure (keys, shapes)
2. Track counts (should be 1105 for both views after reprocessing)
3. Wrist mesh vertices existence
4. Visualize tracked points on sample frames
"""

import numpy as np
import cv2
import sys
from pathlib import Path
import random

# Add parent to path
sys.path.insert(0, str(Path(__file__).parent.parent))


def inspect_npz_structure(npz_path):
    """Print detailed structure of .npz file."""
    data = np.load(npz_path, allow_pickle=True)

    print(f"\n{'='*80}")
    print(f"File: {npz_path.name}")
    print(f"{'='*80}")

    # Print all keys
    print("\nKeys in file:")
    for key in sorted(data.keys()):
        print(f"  {key}")

    # Print shapes
    print("\nData shapes:")
    for key in sorted(data.keys()):
        value = data[key]
        if hasattr(value, 'shape'):
            print(f"  {key:40s}: {value.shape}")
        else:
            print(f"  {key:40s}: {type(value).__name__} = {value}")

    # Check for specific keys
    print("\nStructure checks:")

    # Check exterior tracks
    if 'tracks_exterior' in data:
        tracks_ext = data['tracks_exterior']
        print(f"  ✓ Exterior tracks: {tracks_ext.shape} (expected: [T, 1105, 2])")
        if tracks_ext.shape[1] == 1105:
            print(f"    ✓ Correct point count (1105)")
        else:
            print(f"    ✗ WRONG point count! Expected 1105, got {tracks_ext.shape[1]}")
    else:
        print(f"  ✗ Missing 'tracks_exterior'")

    # Check wrist tracks
    if 'tracks_wrist' in data:
        tracks_wrist = data['tracks_wrist']
        print(f"  ✓ Wrist tracks: {tracks_wrist.shape} (expected: [T, 1105, 2])")
        if tracks_wrist.shape[1] == 1105:
            print(f"    ✓ Correct point count (1105)")
        else:
            print(f"    ✗ WRONG point count! Expected 1105, got {tracks_wrist.shape[1]}")
    else:
        print(f"  ✗ Missing 'tracks_wrist'")

    # Check wrist mesh vertices (fixed)
    if 'mesh_vertices_2d_wrist_fixed' in data:
        mesh_wrist = data['mesh_vertices_2d_wrist_fixed']
        print(f"  ✓ Wrist fixed mesh: {mesh_wrist.shape} (expected: [T, 7, 2])")
    else:
        print(f"  ✗ Missing 'mesh_vertices_2d_wrist_fixed'")

    # Check exterior mesh vertices
    if 'mesh_vertices_2d_exterior' in data:
        mesh_ext = data['mesh_vertices_2d_exterior']
        print(f"  ✓ Exterior mesh: {mesh_ext.shape} (expected: [T, 7, 2])")
    else:
        print(f"  ✗ Missing 'mesh_vertices_2d_exterior'")

    return data


def visualize_tracks(data, npz_path, output_dir, num_frames=5):
    """
    Visualize tracked points on sample frames.

    Shows:
    - Exterior: mesh vertices (blue) + tracked points (green)
    - Wrist: fixed mesh (cyan) + tracked mesh (magenta) + tracked points (green)
    """
    images_ext = data['images_exterior']  # [T, H, W, 3]
    images_wrist = data['images_wrist']
    tracks_ext = data['tracks_exterior']  # [T, N, 2]
    tracks_wrist = data['tracks_wrist']
    tracks_vis_ext = data['tracks_vis_exterior']
    tracks_vis_wrist = data['tracks_vis_wrist']

    # Get mesh data
    mesh_2d_ext = data.get('mesh_vertices_2d_exterior', None)  # [T, 7, 2]
    mesh_vis_ext = data.get('mesh_vertices_vis_exterior', None)  # [T, 7]
    mesh_2d_wrist_fixed = data.get('mesh_vertices_2d_wrist_fixed', None)

    T = images_ext.shape[0]

    # Sample frames evenly
    frame_indices = np.linspace(0, T-1, min(num_frames, T), dtype=int)

    print(f"\nVisualizing {len(frame_indices)} frames...")

    output_dir = Path(output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)

    for idx, t in enumerate(frame_indices):
        # Exterior view
        viz_ext = images_ext[t].copy()

        # Draw ground truth mesh vertices (blue circles)
        if mesh_2d_ext is not None and mesh_vis_ext is not None:
            for i in range(7):
                if mesh_vis_ext[t, i]:
                    pt = tuple(mesh_2d_ext[t, i].astype(int))
                    cv2.circle(viz_ext, pt, 5, (255, 0, 0), 2)  # Blue hollow
                    cv2.putText(viz_ext, str(i), (pt[0]+6, pt[1]-6),
                               cv2.FONT_HERSHEY_SIMPLEX, 0.3, (255, 0, 0), 1)

        # Draw all tracked points (green, smaller)
        for i in range(tracks_ext.shape[1]):
            if tracks_vis_ext[t, i]:
                pt = tuple(tracks_ext[t, i].astype(int))
                # First 7 points are mesh - draw in red
                if i < 7:
                    cv2.circle(viz_ext, pt, 3, (0, 0, 255), -1)  # Red filled
                else:
                    cv2.circle(viz_ext, pt, 1, (0, 255, 0), -1)  # Green

        cv2.putText(viz_ext, f"Ext: GT mesh (blue) | Tracked mesh (red) | Others (green) | {tracks_ext.shape[1]} pts",
                   (5, 15), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (255, 255, 255), 1)

        # Wrist view
        viz_wrist = images_wrist[t].copy()

        # Draw TRACKED mesh vertices (first 7 points) - magenta filled circles
        for i in range(min(7, tracks_wrist.shape[1])):
            if tracks_vis_wrist[t, i]:
                pt = tuple(tracks_wrist[t, i].astype(int))
                cv2.circle(viz_wrist, pt, 3, (255, 0, 255), -1)  # Magenta filled

        # Draw FIXED mesh vertices (from separate array) - cyan hollow circles
        if mesh_2d_wrist_fixed is not None:
            for i in range(7):
                pt = tuple(mesh_2d_wrist_fixed[t, i].astype(int))
                cv2.circle(viz_wrist, pt, 4, (255, 255, 0), 2)  # Cyan hollow
                # Label finger tips and joints
                if i in [1, 2, 3, 4]:
                    cv2.putText(viz_wrist, str(i), (pt[0]+5, pt[1]-5),
                               cv2.FONT_HERSHEY_SIMPLEX, 0.25, (255, 255, 0), 1)

        # Draw other tracked points (grid + random, green, smaller)
        for i in range(7, tracks_wrist.shape[1]):
            if tracks_vis_wrist[t, i]:
                pt = tuple(tracks_wrist[t, i].astype(int))
                cv2.circle(viz_wrist, pt, 1, (0, 255, 0), -1)  # Green

        cv2.putText(viz_wrist, f"Wrist: Tracked mesh (magenta) | Fixed mesh (cyan) | Others (green) | {tracks_wrist.shape[1]} pts",
                   (5, 15), cv2.FONT_HERSHEY_SIMPLEX, 0.3, (255, 255, 255), 1)

        # Concatenate side by side
        combined = np.concatenate([viz_ext, viz_wrist], axis=1)
        cv2.putText(combined, f"Episode {data['episode_idx']} | Frame {t}/{T}",
                   (combined.shape[1]//2 - 60, 15),
                   cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)

        # Save frame
        output_path = output_dir / f"{npz_path.stem}_frame_{t:03d}.png"
        cv2.imwrite(str(output_path), combined)
        print(f"  Saved: {output_path.name}")


def main():
    import argparse
    parser = argparse.ArgumentParser(description="Inspect preprocessed DROID data")
    parser.add_argument('--data-dir', type=str, default='/mnt/kevin/data/droid_processed_1000pts',
                       help='Directory with preprocessed .npz files')
    parser.add_argument('--num-samples', type=int, default=5,
                       help='Number of episodes to sample (default: 5)')
    parser.add_argument('--num-frames', type=int, default=5,
                       help='Number of frames to visualize per episode (default: 5)')
    parser.add_argument('--output-dir', type=str, default='/tmp/droid_inspect',
                       help='Output directory for visualizations')
    parser.add_argument('--specific-episodes', type=int, nargs='+', default=None,
                       help='Specific episode indices to inspect (e.g., 100 200 300)')
    args = parser.parse_args()

    data_dir = Path(args.data_dir) / 'data'
    output_dir = Path(args.output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)

    # Get all .npz files
    npz_files = sorted(data_dir.glob('episode_*.npz'))
    print(f"Found {len(npz_files)} preprocessed episodes in {data_dir}")

    if len(npz_files) == 0:
        print("No .npz files found!")
        return

    # Select episodes to inspect
    if args.specific_episodes:
        # Use specific episode indices
        sample_files = []
        for ep_idx in args.specific_episodes:
            ep_file = data_dir / f"episode_{ep_idx:06d}.npz"
            if ep_file.exists():
                sample_files.append(ep_file)
            else:
                print(f"Warning: Episode {ep_idx} not found")
    else:
        # Random sample
        sample_files = random.sample(npz_files, min(args.num_samples, len(npz_files)))

    print(f"\nInspecting {len(sample_files)} episodes...\n")

    # Inspect each file
    for npz_path in sample_files:
        try:
            # Print structure
            data = inspect_npz_structure(npz_path)

            # Visualize tracks
            visualize_tracks(data, npz_path, output_dir, num_frames=args.num_frames)

        except Exception as e:
            print(f"\nError processing {npz_path.name}: {e}")
            import traceback
            traceback.print_exc()
            continue

    print(f"\n{'='*80}")
    print(f"Inspection complete!")
    print(f"Visualizations saved to: {output_dir}")
    print(f"{'='*80}")


if __name__ == '__main__':
    main()