File size: 30,022 Bytes
b22263c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import numpy as np
import torch
from sklearn.cluster import AgglomerativeClustering
from plyfile import PlyData, PlyElement
import os
from pathlib import Path

# 评估指标库
from skimage.metrics import structural_similarity as ssim
from skimage.metrics import peak_signal_noise_ratio as psnr
import lpips
import cv2

class GaussianMerger:
    """

    3DGS聚类Merge实现

    核心思路:

    1. 空间划分为带padding的cells

    2. 在每个cell内使用AgglomerativeClustering聚类

    3. 使用矩匹配合并高斯参数

    4. 只保留中心在no-padding区域的簇

    """
    def __init__(self, cell_size, padding_ratio=0.1, target_points_per_cluster=3):
        """

        Args:

            cell_size: float, cell边长

            padding_ratio: float, padding占边长的比例

            target_points_per_cluster: int, 目标每簇点数(2-4)

        """
        self.cell_size = cell_size
        self.padding_ratio = padding_ratio
        self.padding_size = cell_size * padding_ratio
        self.target_points_per_cluster = target_points_per_cluster
        
        # 聚类特征权重
        # 归一化位置(3维) + 不透明度(1维) + SH(48维,RGB三阶)
        self.feature_weights = {
            'position': 1.0,    # 空间位置权重
            'opacity': 1.0,     # 不透明度权重
            'sh': 0.2,          # SH系数权重(颜色特征)
        }
    
    def load_ply(self, ply_path):
        """

        加载3DGS的.ply文件

        

        3DGS数据格式:

        - xyz: 3个坐标

        - opacity: 1个不透明度

        - f_dc_0/1/2: DC分量(3维)

        - f_rest_0~44: SH系数(45维,对应RGB各15个三阶SH系数)

        - scale_0/1/2: 3个尺度

        - rot_0/1/2/3: 四元数旋转(4维)

        

        Returns:

            dict: {

                'xyz': (N,3),

                'opacity': (N,1), 

                'dc': (N,3), DC颜色分量

                'sh': (N,45), SH系数

                'scale': (N,3),

                'rotation': (N,4) 四元数 [w,x,y,z]

            }

        """
        print(f"Loading 3DGS from {ply_path}...")
        plydata = PlyData.read(ply_path)
        vertices = plydata['vertex']
        
        # 提取xyz坐标
        xyz = np.stack([vertices['x'], vertices['y'], vertices['z']], axis=1)
        
        # 提取不透明度
        opacity = vertices['opacity'][:, np.newaxis]
        
        # 提取DC分量
        dc = np.stack([vertices['f_dc_0'], vertices['f_dc_1'], vertices['f_dc_2']], axis=1)
        
        # 提取SH系数 (RGB三阶共45维)
        sh_features = []
        for i in range(45):
            sh_features.append(vertices[f'f_rest_{i}'])
        sh = np.stack(sh_features, axis=1)
        
        # 提取scale
        scale = np.stack([vertices['scale_0'], vertices['scale_1'], vertices['scale_2']], axis=1)
        
        # 提取rotation (四元数)
        rotation = np.stack([vertices['rot_0'], vertices['rot_1'], 
                            vertices['rot_2'], vertices['rot_3']], axis=1)
        
        print(f"Loaded {len(xyz)} Gaussians")
        print(f"Scene bounds: {xyz.min(axis=0)} to {xyz.max(axis=0)}")
        
        return {
            'xyz': xyz,
            'opacity': opacity,
            'dc': dc,
            'sh': sh,
            'scale': scale,
            'rotation': rotation
        }
    
    def save_ply(self, gaussians, output_path):
        """

        保存merge后的高斯到.ply文件

        

        Args:

            gaussians: dict, merge后的高斯参数

            output_path: str, 输出路径

        """
        print(f"Saving merged 3DGS to {output_path}...")
        
        xyz = gaussians['xyz']
        opacity = gaussians['opacity'].flatten()
        dc = gaussians['dc']
        sh = gaussians['sh']
        scale = gaussians['scale']
        rotation = gaussians['rotation']
        
        n_points = len(xyz)
        
        # 构建dtype
        dtype_list = [
            ('x', 'f4'), ('y', 'f4'), ('z', 'f4'),
            ('opacity', 'f4'),
            ('f_dc_0', 'f4'), ('f_dc_1', 'f4'), ('f_dc_2', 'f4'),
        ]
        
        # 添加SH系数
        for i in range(45):
            dtype_list.append((f'f_rest_{i}', 'f4'))
        
        # 添加scale和rotation
        dtype_list.extend([
            ('scale_0', 'f4'), ('scale_1', 'f4'), ('scale_2', 'f4'),
            ('rot_0', 'f4'), ('rot_1', 'f4'), ('rot_2', 'f4'), ('rot_3', 'f4')
        ])
        
        # 创建结构化数组
        elements = np.empty(n_points, dtype=dtype_list)
        
        # 填充数据
        elements['x'] = xyz[:, 0]
        elements['y'] = xyz[:, 1]
        elements['z'] = xyz[:, 2]
        elements['opacity'] = opacity
        elements['f_dc_0'] = dc[:, 0]
        elements['f_dc_1'] = dc[:, 1]
        elements['f_dc_2'] = dc[:, 2]
        
        for i in range(45):
            elements[f'f_rest_{i}'] = sh[:, i]
        
        elements['scale_0'] = scale[:, 0]
        elements['scale_1'] = scale[:, 1]
        elements['scale_2'] = scale[:, 2]
        elements['rot_0'] = rotation[:, 0]
        elements['rot_1'] = rotation[:, 1]
        elements['rot_2'] = rotation[:, 2]
        elements['rot_3'] = rotation[:, 3]
        
        # 创建PlyElement
        el = PlyElement.describe(elements, 'vertex')
        
        # 写入文件
        PlyData([el]).write(output_path)
        print(f"Saved {n_points} merged Gaussians")
    
    def partition_space(self, xyz):
        """

        空间划分: 将场景划分为cell网格

        

        策略:

        - 每个cell有padding区域用于聚类

        - 但只保留中心在no-padding区域的簇

        

        Args:

            xyz: (N, 3) 点的位置

        Returns:

            cell_dict: {cell_id: [point_indices]} cell内的点索引(含padding)

            cell_info: {cell_id: {'center', 'bounds_no_padding', 'bounds_with_padding'}}

        """
        print("Partitioning space into cells...")
        
        # 计算场景边界(稍微扩大一点避免边界问题)
        min_bound = xyz.min(axis=0) - self.padding_size
        max_bound = xyz.max(axis=0) + self.padding_size
        
        # 计算每个点所属的cell(基于no-padding边界)
        cell_indices = np.floor((xyz - min_bound) / self.cell_size).astype(int)
        
        # 获取所有唯一的cell
        unique_cells = np.unique(cell_indices, axis=0)
        
        cell_dict = {}
        cell_info = {}
        
        for cell_idx in unique_cells:
            cell_id = tuple(cell_idx)
            
            # Cell的no-padding边界
            cell_min = min_bound + cell_idx * self.cell_size
            cell_max = cell_min + self.cell_size
            
            # Cell的with-padding边界
            cell_min_padded = cell_min - self.padding_size
            cell_max_padded = cell_max + self.padding_size
            
            # 找到所有在padding范围内的点
            mask = np.all((xyz >= cell_min_padded) & (xyz < cell_max_padded), axis=1)
            point_indices = np.where(mask)[0]
            
            if len(point_indices) > 0:
                cell_dict[cell_id] = point_indices
                cell_info[cell_id] = {
                    'center': (cell_min + cell_max) / 2,
                    'bounds_no_padding': (cell_min, cell_max),
                    'bounds_with_padding': (cell_min_padded, cell_max_padded)
                }
        
        print(f"Created {len(cell_dict)} cells")
        points_per_cell = [len(indices) for indices in cell_dict.values()]
        print(f"Points per cell: min={min(points_per_cell)}, max={max(points_per_cell)}, avg={np.mean(points_per_cell):.1f}")
        
        return cell_dict, cell_info
    
    def compute_features_for_clustering(self, gaussians, point_indices, cell_bounds):
        """

        计算聚类特征: 归一化位置(3) + 不透明度(1) + SH系数(48)

        

        注意:

        - 位置需要在padding后的cell内归一化

        - SH系数包含DC(3维)和高阶(45维),共48维

        - 不同特征使用不同权重

        

        Args:

            gaussians: 完整的高斯数据

            point_indices: 当前cell内的点索引

            cell_bounds: (min_xyz, max_xyz) with padding

        Returns:

            features: (N, 52) 归一化后的特征向量

        """
        xyz = gaussians['xyz'][point_indices]
        opacity = gaussians['opacity'][point_indices]
        dc = gaussians['dc'][point_indices]
        sh = gaussians['sh'][point_indices]
        
        cell_min, cell_max = cell_bounds
        cell_size_padded = cell_max - cell_min
        
        # 归一化位置: (xyz - cell_min) / padded_cell_size
        normalized_pos = (xyz - cell_min) / cell_size_padded
        
        # 组合SH特征: DC + 高阶SH
        sh_features = np.concatenate([dc, sh], axis=1)  # (N, 48)
        
        # 组合所有特征并加权
        features = np.concatenate([
            normalized_pos * self.feature_weights['position'],      # (N, 3)
            opacity * self.feature_weights['opacity'],              # (N, 1)
            sh_features * self.feature_weights['sh']                # (N, 48)
        ], axis=1)
        
        return features
    
    def quaternion_to_rotation_matrix(self, q):
        """

        四元数转旋转矩阵

        

        Args:

            q: (4,) [w, x, y, z] 或 (N, 4)

        Returns:

            R: (3, 3) 或 (N, 3, 3)

        """
        if q.ndim == 1:
            w, x, y, z = q
            R = np.array([
                [1-2*(y**2+z**2), 2*(x*y-w*z), 2*(x*z+w*y)],
                [2*(x*y+w*z), 1-2*(x**2+z**2), 2*(y*z-w*x)],
                [2*(x*z-w*y), 2*(y*z+w*x), 1-2*(x**2+y**2)]
            ])
            return R
        else:
            # 批量处理
            w, x, y, z = q[:, 0], q[:, 1], q[:, 2], q[:, 3]
            R = np.zeros((len(q), 3, 3))
            R[:, 0, 0] = 1 - 2*(y**2 + z**2)
            R[:, 0, 1] = 2*(x*y - w*z)
            R[:, 0, 2] = 2*(x*z + w*y)
            R[:, 1, 0] = 2*(x*y + w*z)
            R[:, 1, 1] = 1 - 2*(x**2 + z**2)
            R[:, 1, 2] = 2*(y*z - w*x)
            R[:, 2, 0] = 2*(x*z - w*y)
            R[:, 2, 1] = 2*(y*z + w*x)
            R[:, 2, 2] = 1 - 2*(x**2 + y**2)
            return R
    
    def compute_covariance(self, scale, rotation):
        """

        计算协方差矩阵: Σ = R·S·S^T·R^T

        

        Args:

            scale: (N, 3) 三个轴的尺度

            rotation: (N, 4) 四元数 [w,x,y,z]

        Returns:

            covariances: (N, 3, 3)

        """
        N = len(scale)
        R = self.quaternion_to_rotation_matrix(rotation)  # (N, 3, 3)
        
        # S 是对角矩阵
        S = np.zeros((N, 3, 3))
        S[:, 0, 0] = scale[:, 0]
        S[:, 1, 1] = scale[:, 1]
        S[:, 2, 2] = scale[:, 2]
        
        # Σ = R·S·S^T·R^T
        covariances = np.einsum('nij,njk,nlk,nli->nil', R, S, S, R)
        
        return covariances
    
    def moment_matching(self, means, covariances, opacities, scales):
        """

        矩匹配: 合并多个高斯分布

        

        公式:

        - 权重: wi = opacity_i * volume_i

        - 新均值: μ_new = Σ(wi * μi) / Σwi

        - 新协方差: Σ_new = Σ(wi * (Σi + (μi-μ_new)(μi-μ_new)^T)) / Σwi

        - 新不透明度: 质量守恒,Σ(opacity_i * volume_i) = opacity_new * volume_new

        

        Args:

            means: (K, 3) 各高斯均值

            covariances: (K, 3, 3) 各高斯协方差矩阵

            opacities: (K, 1) 不透明度

            scales: (K, 3) 尺度

        Returns:

            new_mean: (3,)

            new_covariance: (3, 3)

            new_opacity: float

            new_scale: (3,)

            new_rotation: (4,) 四元数

        """
        # 计算权重 wi = opacity * scale_volume
        scale_volumes = np.prod(scales, axis=1, keepdims=True)  # (K, 1)
        weights = opacities * scale_volumes  # (K, 1)
        total_weight = weights.sum()
        weights_normalized = weights / total_weight  # 归一化用于计算均值和协方差
        
        # 计算加权均值
        new_mean = np.sum(weights_normalized * means, axis=0)  # (3,)
        
        # 计算混合协方差
        mean_diff = means - new_mean  # (K, 3)
        outer_products = np.einsum('ki,kj->kij', mean_diff, mean_diff)  # (K, 3, 3)
        
        new_covariance = np.sum(
            weights_normalized[:, :, np.newaxis] * (covariances + outer_products), 
            axis=0
        )  # (3, 3)
        
        # 从协方差矩阵分解得到scale和rotation
        # 特征值分解: Σ = V·Λ·V^T,其中V是旋转矩阵,Λ是特征值对角阵
        eigenvalues, eigenvectors = np.linalg.eigh(new_covariance)
        
        # scale = sqrt(eigenvalues)
        new_scale = np.sqrt(np.abs(eigenvalues))
        new_scale_volume = np.prod(new_scale)
        
        # 质量守恒: Σ(opacity_i * volume_i) = opacity_new * volume_new
        # opacity_new = Σ(opacity_i * volume_i) / volume_new
        if new_scale_volume > 1e-10:
            new_opacity = total_weight / new_scale_volume
            new_opacity = np.clip(new_opacity, 0, 1)  # 限制在[0,1]
        else:
            new_opacity = np.mean(opacities)  # fallback
        
        # rotation matrix = eigenvectors
        R_new = eigenvectors
        
        # 旋转矩阵转四元数
        new_rotation = self.rotation_matrix_to_quaternion(R_new)
        
        return new_mean, new_covariance, new_opacity, new_scale, new_rotation
    
    def rotation_matrix_to_quaternion(self, R):
        """

        旋转矩阵转四元数 [w, x, y, z]

        使用Shepperd方法,数值稳定

        """
        trace = np.trace(R)
        
        if trace > 0:
            s = 0.5 / np.sqrt(trace + 1.0)
            w = 0.25 / s
            x = (R[2, 1] - R[1, 2]) * s
            y = (R[0, 2] - R[2, 0]) * s
            z = (R[1, 0] - R[0, 1]) * s
        elif R[0, 0] > R[1, 1] and R[0, 0] > R[2, 2]:
            s = 2.0 * np.sqrt(1.0 + R[0, 0] - R[1, 1] - R[2, 2])
            w = (R[2, 1] - R[1, 2]) / s
            x = 0.25 * s
            y = (R[0, 1] + R[1, 0]) / s
            z = (R[0, 2] + R[2, 0]) / s
        elif R[1, 1] > R[2, 2]:
            s = 2.0 * np.sqrt(1.0 + R[1, 1] - R[0, 0] - R[2, 2])
            w = (R[0, 2] - R[2, 0]) / s
            x = (R[0, 1] + R[1, 0]) / s
            y = 0.25 * s
            z = (R[1, 2] + R[2, 1]) / s
        else:
            s = 2.0 * np.sqrt(1.0 + R[2, 2] - R[0, 0] - R[1, 1])
            w = (R[1, 0] - R[0, 1]) / s
            x = (R[0, 2] + R[2, 0]) / s
            y = (R[1, 2] + R[2, 1]) / s
            z = 0.25 * s
        
        q = np.array([w, x, y, z])
        q = q / np.linalg.norm(q)  # 归一化
        return q
    
    def cluster_and_merge_cell(self, gaussians, point_indices, cell_info):
        """

        在单个cell内进行聚类和merge

        

        流程:

        1. 提取padding区域内的所有点

        2. 计算聚类特征(归一化位置+不透明度+SH)

        3. 使用AgglomerativeClustering聚类

        4. 对每个簇使用矩匹配合并

        5. 只保留中心在no-padding区域的簇

        

        Args:

            gaussians: 完整的高斯数据dict

            point_indices: 当前cell内的点索引 (包含padding区域)

            cell_info: cell的边界信息

        Returns:

            merged_gaussians: dict, merge后的高斯参数

        """
        if len(point_indices) == 0:
            return None
        
        # 提取cell内的数据
        xyz = gaussians['xyz'][point_indices]
        
        # 计算聚类特征
        cell_bounds = cell_info['bounds_with_padding']
        features = self.compute_features_for_clustering(gaussians, point_indices, cell_bounds)
        
        # 计算聚类数量: n_clusters = n_points // target_points_per_cluster
        n_clusters = max(1, len(point_indices) // self.target_points_per_cluster)
        
        # AgglomerativeClustering
        clustering = AgglomerativeClustering(
            n_clusters=n_clusters,
            metric='euclidean',
            linkage='ward'
        )
        labels = clustering.fit_predict(features)
        
        # 对每个簇进行merge
        merged_results = {
            'xyz': [],
            'opacity': [],
            'dc': [],
            'sh': [],
            'scale': [],
            'rotation': []
        }
        
        no_padding_min, no_padding_max = cell_info['bounds_no_padding']
        
        for cluster_id in range(n_clusters):
            cluster_mask = labels == cluster_id
            cluster_point_indices = point_indices[cluster_mask]
            
            if len(cluster_point_indices) == 0:
                continue
            
            # 提取簇内数据
            cluster_xyz = gaussians['xyz'][cluster_point_indices]
            cluster_opacity = gaussians['opacity'][cluster_point_indices]
            cluster_dc = gaussians['dc'][cluster_point_indices]
            cluster_sh = gaussians['sh'][cluster_point_indices]
            cluster_scale = gaussians['scale'][cluster_point_indices]
            cluster_rotation = gaussians['rotation'][cluster_point_indices]
            
            # 计算协方差矩阵
            cluster_covariances = self.compute_covariance(cluster_scale, cluster_rotation)
            
            # 矩匹配合并位置和协方差
            new_mean, new_cov, new_opacity, new_scale, new_rotation = self.moment_matching(
                cluster_xyz, cluster_covariances, cluster_opacity, cluster_scale
            )
            
            # 只保留中心在no-padding区域的簇
            if np.all(new_mean >= no_padding_min) and np.all(new_mean < no_padding_max):
                # DC和SH使用加权平均
                scale_volumes = np.prod(cluster_scale, axis=1, keepdims=True)
                weights = cluster_opacity * scale_volumes
                weights = weights / weights.sum()
                
                new_dc = np.sum(weights * cluster_dc, axis=0)
                new_sh = np.sum(weights * cluster_sh, axis=0)
                
                # 添加到结果
                merged_results['xyz'].append(new_mean)
                merged_results['opacity'].append([new_opacity])
                merged_results['dc'].append(new_dc)
                merged_results['sh'].append(new_sh)
                merged_results['scale'].append(new_scale)
                merged_results['rotation'].append(new_rotation)
        
        # 转换为numpy数组
        if len(merged_results['xyz']) == 0:
            return None
        
        for key in merged_results:
            merged_results[key] = np.array(merged_results[key])
        
        return merged_results
    
    def merge_all(self, gaussians):
        """

        对所有cell进行聚类merge

        

        Args:

            gaussians: 原始高斯数据

        Returns:

            merged_gaussians: merge后的高斯数据

        """
        # 空间划分
        cell_dict, cell_info = self.partition_space(gaussians['xyz'])
        
        # 对每个cell进行处理
        all_merged = {
            'xyz': [],
            'opacity': [],
            'dc': [],
            'sh': [],
            'scale': [],
            'rotation': []
        }
        
        total_cells = len(cell_dict)
        for idx, (cell_id, point_indices) in enumerate(cell_dict.items()):
            if (idx + 1) % 100 == 0:
                print(f"Processing cell {idx+1}/{total_cells}...")
            
            merged = self.cluster_and_merge_cell(gaussians, point_indices, cell_info[cell_id])
            
            if merged is not None:
                for key in all_merged:
                    all_merged[key].append(merged[key])
        
        # 合并所有cell的结果
        final_merged = {}
        for key in all_merged:
            final_merged[key] = np.concatenate(all_merged[key], axis=0)
        
        print(f"\nMerge Statistics:")
        print(f"  Original points: {len(gaussians['xyz'])}")
        print(f"  Merged points: {len(final_merged['xyz'])}")
        print(f"  Compression ratio: {len(gaussians['xyz']) / len(final_merged['xyz']):.2f}x")
        
        return final_merged


class ImageEvaluator:
    """

    图像质量评估

    支持: PSNR, SSIM, LPIPS, NIQE, FID, MEt3R

    """
    def __init__(self, device='cuda' if torch.cuda.is_available() else 'cpu'):
        self.device = device
        
        # 初始化LPIPS模型
        self.lpips_model = lpips.LPIPS(net='alex').to(device)
        
    def load_image(self, image_path):
        """

        加载图像,支持jpg和png

        Returns:

            img: (H, W, 3) numpy array, range [0, 1]

        """
        img = cv2.imread(image_path)
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        img = img.astype(np.float32) / 255.0
        return img
    
    def compute_psnr(self, img1, img2):
        """

        计算PSNR

        """
        return psnr(img1, img2, data_range=1.0)
    
    def compute_ssim(self, img1, img2):
        """

        计算SSIM

        """
        return ssim(img1, img2, multichannel=True, data_range=1.0, channel_axis=2)
    
    def compute_lpips(self, img1, img2):
        """

        计算LPIPS (需要转换为tensor)

        """
        # 转换为tensor: (H,W,3) -> (1,3,H,W)
        img1_t = torch.from_numpy(img1).permute(2, 0, 1).unsqueeze(0).to(self.device)
        img2_t = torch.from_numpy(img2).permute(2, 0, 1).unsqueeze(0).to(self.device)
        
        # LPIPS期望输入范围[-1, 1]
        img1_t = img1_t * 2 - 1
        img2_t = img2_t * 2 - 1
        
        with torch.no_grad():
            lpips_value = self.lpips_model(img1_t, img2_t).item()
        
        return lpips_value
    
    def compute_niqe(self, img):
        """

        计算NIQE (无参考图像质量评估)

        注意: 需要安装piq库或使用opencv实现

        这里使用简化版本

        """
        try:
            import piq
            img_t = torch.from_numpy(img).permute(2, 0, 1).unsqueeze(0).to(self.device)
            niqe_value = piq.niqe(img_t).item()
            return niqe_value
        except:
            print("Warning: NIQE requires 'piq' library. Returning 0.")
            return 0.0
    
    def compute_fid(self, real_images, fake_images):
        """

        计算FID (Frechet Inception Distance)

        需要多张图像,这里提供接口

        

        Args:

            real_images: list of image paths or numpy arrays

            fake_images: list of image paths or numpy arrays

        """
        try:
            from pytorch_fid import fid_score
            # FID需要使用目录路径或特征统计
            print("Warning: FID computation requires pytorch-fid library and image directories.")
            print("Please use fid_score.calculate_fid_given_paths() separately.")
            return 0.0
        except:
            print("Warning: FID computation not available. Install pytorch-fid.")
            return 0.0
    
    def compute_meter(self, img1, img2):
        """

        计算MEt3R (需要MEt3R模型)

        这是一个学习型指标,需要预训练模型

        """
        print("Warning: MEt3R computation requires specific model weights.")
        print("Please refer to MEt3R paper and implementation.")
        return 0.0
    
    def evaluate_image_pair(self, gt_path, rendered_path):
        """

        评估一对图像

        

        Args:

            gt_path: 高分辨率ground truth图像路径

            rendered_path: 渲染的图像路径

        Returns:

            dict: 包含所有评估指标

        """
        print(f"Evaluating: {rendered_path}")
        
        # 加载图像
        gt_img = self.load_image(gt_path)
        rendered_img = self.load_image(rendered_path)
        
        # 确保尺寸一致
        if gt_img.shape != rendered_img.shape:
            print(f"Warning: Image size mismatch. GT: {gt_img.shape}, Rendered: {rendered_img.shape}")
            # 调整rendered_img到gt_img的大小
            rendered_img = cv2.resize(rendered_img, (gt_img.shape[1], gt_img.shape[0]))
        
        # 计算所有指标
        metrics = {
            'PSNR': self.compute_psnr(gt_img, rendered_img),
            'SSIM': self.compute_ssim(gt_img, rendered_img),
            'LPIPS': self.compute_lpips(gt_img, rendered_img),
            'NIQE': self.compute_niqe(rendered_img),  # 无参考指标
        }
        
        return metrics
    
    def evaluate_multiple_views(self, gt_dir, rendered_dir):
        """

        评估多个视角

        

        Args:

            gt_dir: ground truth图像目录

            rendered_dir: 渲染图像目录

        Returns:

            dict: 平均指标

        """
        import glob
        
        # 获取所有图像
        gt_images = sorted(glob.glob(os.path.join(gt_dir, '*.jpg')) + 
                          glob.glob(os.path.join(gt_dir, '*.png')))
        rendered_images = sorted(glob.glob(os.path.join(rendered_dir, '*.jpg')) + 
                                glob.glob(os.path.join(rendered_dir, '*.png')))
        
        if len(gt_images) != len(rendered_images):
            print(f"Warning: Number of images mismatch. GT: {len(gt_images)}, Rendered: {len(rendered_images)}")
        
        all_metrics = []
        
        for gt_path, rendered_path in zip(gt_images, rendered_images):
            metrics = self.evaluate_image_pair(gt_path, rendered_path)
            all_metrics.append(metrics)
        
        # 计算平均值
        avg_metrics = {}
        for key in all_metrics[0].keys():
            avg_metrics[key] = np.mean([m[key] for m in all_metrics])
            avg_metrics[key + '_std'] = np.std([m[key] for m in all_metrics])
        
        return avg_metrics, all_metrics


# ==================== 使用示例 ====================

def main():
    """

    完整流程示例:

    1. 加载原始3DGS

    2. 执行聚类merge

    3. 保存merged模型

    4. 调用渲染(需要外部实现)

    5. 评估图像质量

    """
    
    # ============ Step 1: 配置参数 ============
    config = {
        'original_ply': 'path/to/original_3dgs.ply',
        'merged_ply': 'path/to/merged_3dgs.ply',
        'gt_image_dir': 'path/to/high_res_images',
        'rendered_image_dir': 'path/to/rendered_images',
        'cell_size': 1.0,  # 根据场景大小调整
        'padding_ratio': 0.1,
        'target_points_per_cluster': 3
    }
    
    # ============ Step 2: 执行Merge ============
    print("="*50)
    print("Step 1: Merging Gaussians")
    print("="*50)
    
    merger = GaussianMerger(
        cell_size=config['cell_size'],
        padding_ratio=config['padding_ratio'],
        target_points_per_cluster=config['target_points_per_cluster']
    )
    
    # 加载原始3DGS
    gaussians = merger.load_ply(config['original_ply'])
    
    # 执行merge
    merged_gaussians = merger.merge_all(gaussians)
    
    # 保存结果
    merger.save_ply(merged_gaussians, config['merged_ply'])
    
    # ============ Step 3: 渲染 (需要外部实现) ============
    print("\n" + "="*50)
    print("Step 2: Rendering (Please implement separately)")
    print("="*50)
    print(f"Please use your 3DGS renderer to render images from:")
    print(f"  Model: {config['merged_ply']}")
    print(f"  Output to: {config['rendered_image_dir']}")
    print("\nExample command (using gaussian-splatting):")
    print(f"  python render.py -m {config['merged_ply']} -s <scene_path>")
    
    # ============ Step 4: 评估 ============
    print("\n" + "="*50)
    print("Step 3: Evaluating Image Quality")
    print("="*50)
    
    evaluator = ImageEvaluator()
    
    # 评估多个视角
    avg_metrics, all_metrics = evaluator.evaluate_multiple_views(
        config['gt_image_dir'],
        config['rendered_image_dir']
    )
    
    # 打印结果
    print("\n" + "="*50)
    print("Evaluation Results")
    print("="*50)
    for metric_name, value in avg_metrics.items():
        if not metric_name.endswith('_std'):
            std = avg_metrics.get(metric_name + '_std', 0)
            print(f"{metric_name:10s}: {value:.4f} ± {std:.4f}")
    
    # 保存详细结果
    import json
    results = {
        'config': config,
        'merge_stats': {
            'original_points': len(gaussians['xyz']),
            'merged_points': len(merged_gaussians['xyz']),
            'compression_ratio': len(gaussians['xyz']) / len(merged_gaussians['xyz'])
        },
        'average_metrics': {k: float(v) for k, v in avg_metrics.items()},
        'per_view_metrics': [{k: float(v) for k, v in m.items()} for m in all_metrics]
    }
    
    with open('evaluation_results.json', 'w') as f:
        json.dump(results, f, indent=2)
    
    print(f"\nResults saved to: evaluation_results.json")


if __name__ == "__main__":
    main()