File size: 12,115 Bytes
8b5f9ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""ForeHOI Dataset WebDataset Loader with Random Sampling"""
import argparse
import tarfile
import json
import random
import io
from pathlib import Path
from PIL import Image
import torch
from torch.utils.data import IterableDataset
import pickle
import numpy as np
from typing import List, Dict, Tuple
import cv2


class ForeHOIRandomDataset(IterableDataset):
    """
    - Sample 级别随机打乱(流式)
    - 每个 Sample 内随机选 N 个不同的 view/frame 组合
    - 索引缓存,避免重复扫描 tar 文件
    """
    
    def __init__(self, tar_path: str, n_frames_per_sample: int = 4, 
                 cache_dir: str = None, reshuffle: bool = True):
        self.tar_path = Path(tar_path)
        self.n_frames = n_frames_per_sample
        self.reshuffle = reshuffle
        
        if cache_dir is None:
            cache_dir = self.tar_path.parent
        self.cache_path = Path(cache_dir) / f"{self.tar_path.stem}.index.pkl"
        
        self.sample_index = self._load_or_build_index()
        self.sample_ids = list(self.sample_index.keys())
        print(f"Dataset loaded: {len(self.sample_ids)} samples, "
              f"avg {np.mean([len(v) for v in self.sample_index.values()]):.1f} frames/sample")
    
    def _build_index(self) -> Dict[str, List[Dict]]:
        """
        构建索引: {sample_id: [{key, view_id, frame_id, files}, ...]}
        """
        print(f"Building index for {self.tar_path}...")
        index = {}
        
        with tarfile.open(self.tar_path, "r") as tar:
            for member in tar:
                if not member.isfile():
                    continue
                
                # 文件名示例: "sample_01/view_0/000.rgb.webp"
                full_name = member.name
                
                # 1. 确定文件类型 (data_type) 和 基础键 (base_key)
                if full_name.endswith('.rgb.webp'):
                    data_type = 'rgb'
                    base_key = full_name[:-9] # 去掉 .rgb.webp
                elif full_name.endswith('.obj_mask.webp'):
                    data_type = 'obj_mask'
                    base_key = full_name[:-14] # 去掉 .obj_mask.webp
                elif full_name.endswith('.hand_mask.webp'):
                    data_type = 'hand_mask'
                    base_key = full_name[:-15] # 去掉 .hand_mask.webp
                elif full_name.endswith('.meta.json'):
                    data_type = 'meta'
                    base_key = full_name[:-10] # 去掉 .meta.json
                else:
                    # 跳过不符合命名规范的文件
                    continue
                
                # 2. 解析 sample/view/frame
                parts = base_key.split('/')
                if len(parts) != 3:
                    continue
                
                sample_id, view_id, frame_id = parts
                
                if sample_id not in index:
                    index[sample_id] = []
                
                # 3. 查找或创建 entry
                existing = next((e for e in index[sample_id] 
                               if e["view_id"] == view_id and e["frame_id"] == frame_id), None)
                
                if existing is None:
                    existing = {
                        "key": base_key,
                        "view_id": view_id,
                        "frame_id": frame_id,
                        "files": {}  # data_type -> {offset, size}
                    }
                    index[sample_id].append(existing)
                
                # 4. 记录文件偏移量,使用 data_type (rgb/obj_mask...) 作为 key
                if hasattr(member, 'offset_data') and member.offset_data is not None:
                    data_offset = member.offset_data
                else:
                    data_offset = member.offset + 512
                existing["files"][data_type] = {
                    "offset": data_offset,
                    "size": member.size
                }
        
        # 排序
        for sid in index:
            index[sid].sort(key=lambda x: (x["view_id"], x["frame_id"]))
            
        return index

    def _load_or_build_index(self):
        if self.cache_path.exists():
            print(f"Loading cached index from {self.cache_path}")
            with open(self.cache_path, 'rb') as f:
                return pickle.load(f)
        
        index = self._build_index()
        with open(self.cache_path, 'wb') as f:
            pickle.dump(index, f)
        print(f"Index cached to {self.cache_path}")
        return index
    
    def _read_file_at_offset(self, tar, offset_info: Dict) -> bytes:
        tar.fileobj.seek(offset_info["offset"])
        return tar.fileobj.read(offset_info["size"])
    
    def _decode_entry(self, tar, entry_info: Dict) -> Dict:
        """读取并解码单个 entry"""
        result = {
            "key": entry_info["key"],
            "view_id": entry_info["view_id"],
            "frame_id": entry_info["frame_id"]
        }
        
        # 遍历该 entry 下的所有文件类型 (rgb, obj_mask, hand_mask, meta)
        for data_type, offset_info in entry_info["files"].items():
            data = self._read_file_at_offset(tar, offset_info)
            
            if data_type == 'rgb':
                img = Image.open(io.BytesIO(data)).convert("RGB")
                result['rgb'] = np.array(img)
            elif data_type in ['obj_mask', 'hand_mask']:
                img = Image.open(io.BytesIO(data)).convert("L")
                result[data_type] = np.array(img)
            elif data_type == 'meta':
                result['meta'] = json.loads(data.decode('utf-8'))
        
        return result
    
    def _sample_to_tensor(self, entry: Dict) -> Dict:
        """转换为 Tensor 格式"""
        if 'rgb' not in entry:
            # 这种情况通常不应该发生,除非 tar 包损坏
            print(f"Warning: Missing RGB for {entry['key']}")
            return None 

        # RGB: [3, H, W], 0-1
        # entry['rgb'] 已经在 _decode_entry 中转为 numpy (或 PIL)
        rgb_np = np.array(entry["rgb"])
        rgb_tensor = torch.from_numpy(rgb_np).permute(2, 0, 1).float() / 255.0
        
        h, w = rgb_np.shape[:2]

        # Masks: [H, W], 0-1
        # 处理可能缺失 mask 的情况
        if "obj_mask" in entry:
            obj_mask_np = entry["obj_mask"]
        else:
            print(f"Warning: Missing obj mask for {entry['key']}")
            return None

        if "hand_mask" in entry:
            hand_mask_np = entry["hand_mask"]
        else:
            print(f"Warning: Missing hand mask for {entry['key']}")
            return None
        
        obj_tensor = torch.from_numpy(obj_mask_np).float() / 255.0
        hand_tensor = torch.from_numpy(hand_mask_np).float() / 255.0
        
        meta = entry.get("meta", {})
        
        return {
            "key": entry["key"],
            "sample_id": entry["key"].split('/')[0],
            "view_id": entry["view_id"],
            "frame_id": entry["frame_id"],
            "rgb": rgb_tensor,
            "obj_mask": obj_tensor,
            "hand_mask": hand_tensor,
            "camera_pose": torch.tensor(meta.get("camera_pose", [])),
            "obj_pose": torch.tensor(meta.get("obj_pose", [])),
            "width": meta.get("width", w),
            "height": meta.get("height", h),
        }
    
    def __iter__(self):
        worker_info = torch.utils.data.get_worker_info()
        
        if worker_info is None:
            sample_ids = self.sample_ids.copy()
        else:
            per_worker = len(self.sample_ids) // worker_info.num_workers
            start = worker_info.id * per_worker
            end = start + per_worker if worker_info.id < worker_info.num_workers - 1 else len(self.sample_ids)
            sample_ids = self.sample_ids[start:end]
        
        if self.reshuffle:
            random.shuffle(sample_ids)
        
        with tarfile.open(self.tar_path, "r") as tar:
            for sample_id in sample_ids:
                entries = self.sample_index[sample_id]
                
                if len(entries) <= self.n_frames:
                    selected_entries = random.choices(entries, k=self.n_frames)
                else:
                    selected_entries = random.sample(entries, self.n_frames)
                
                batch = []
                for entry_info in selected_entries:
                    data = self._decode_entry(tar, entry_info)
                    tensor_data = self._sample_to_tensor(data)
                    if tensor_data is not None:
                        batch.append(tensor_data)
                
                if batch:
                    yield {
                        "sample_id": sample_id,
                        "keys": [b["key"] for b in batch],
                        "rgb": torch.stack([b["rgb"] for b in batch]),
                        "obj_mask": torch.stack([b["obj_mask"] for b in batch]),
                        "hand_mask": torch.stack([b["hand_mask"] for b in batch]),
                        "camera_pose": torch.stack([b["camera_pose"] for b in batch]) if batch[0]["camera_pose"].numel() > 0 else None,
                        "meta": [b.get("meta", {}) for b in batch]
                    }

def visualize_and_save(batch: Dict, output_dir: str, max_samples: int = 10):
    output_path = Path(output_dir)
    output_path.mkdir(parents=True, exist_ok=True)
    
    sample_id = batch["sample_id"]
    n_frames = len(batch["keys"])
    
    for i in range(min(n_frames, max_samples)):
        rgb = batch["rgb"][i].permute(1, 2, 0).cpu().numpy()
        obj_mask = batch["obj_mask"][i].cpu().numpy()
        hand_mask = batch["hand_mask"][i].cpu().numpy()
        
        rgb_img = (rgb * 255).astype(np.uint8)
        obj_mask_img = (obj_mask * 255).astype(np.uint8)
        hand_mask_img = (hand_mask * 255).astype(np.uint8)
        
        obj_mask_color = np.stack([obj_mask_img] * 3, axis=-1)
        hand_mask_color = np.stack([hand_mask_img] * 3, axis=-1)
        
        combined = np.hstack([rgb_img, obj_mask_color, hand_mask_color])
        combined_pil = Image.fromarray(combined)
        
        view_id = batch["keys"][i].split('/')[1]
        frame_id = batch["keys"][i].split('/')[2]
        filename = f"{sample_id}_{view_id}_{frame_id}.png"
        
        save_path = output_path / filename
        combined_pil.save(save_path)
        print(f"Saved: {save_path} ({rgb.shape[1]}x{rgb.shape[0]})")
    
    return n_frames

def main():
    parser = argparse.ArgumentParser(description="随机采样 ForeHOI WebDataset 并保存可视化结果")
    parser.add_argument("--tar_path", type=str, required=True, help="输入的 tar 文件路径")
    parser.add_argument("--output_dir", type=str, default="./visualization", help="可视化输出目录")
    parser.add_argument("--n_samples", type=int, default=10, help="随机选多少个 sample")
    parser.add_argument("--n_frames", type=int, default=4, help="每个 sample 随机采多少帧")
    parser.add_argument("--save_per_sample", type=int, default=10, help="每个 sample 保存多少张可视化图")
    
    args = parser.parse_args()
    
    dataset = ForeHOIRandomDataset(
        args.tar_path, 
        n_frames_per_sample=args.n_frames,
        reshuffle=True
    )
    
    dataloader = torch.utils.data.DataLoader(
        dataset,
        batch_size=None,
        num_workers=0,
        pin_memory=False
    )
    
    saved_samples = 0
    
    print(f"\n开始随机采样 {args.n_samples} 个 samples...")
    
    for batch_idx, batch in enumerate(dataloader):
        if batch_idx >= args.n_samples:
            break
        
        print(f"\n[{batch_idx+1}/{args.n_samples}] Sample: {batch['sample_id']}, Frames: {len(batch['keys'])}")
        visualize_and_save(batch, args.output_dir, max_samples=args.save_per_sample)
        saved_samples += 1
    
    print(f"\n完成!")

if __name__ == "__main__":
    main()