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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
    #!/usr/bin/env python
    # coding: utf-8

    # In[ ]:

import json
import os
import open3d as o3d
import numpy as np


mesh = o3d.io.read_triangle_mesh("./bottle.stl")
pointcloud = mesh.sample_points_poisson_disk(50000)
coord_frame = o3d.geometry.TriangleMesh.create_coordinate_frame(size=50.0, origin=[0, 0, 0])
mesh.compute_vertex_normals()
mesh_triangles = np.asarray(mesh.triangles)
vertex_positions = np.asarray(mesh.vertices)
triangle_normals = np.asarray(mesh.triangle_normals)
# 객체의 중심점 계산
centroid = mesh.get_center()


# 데이터셋 폴더와 JSON 파일 경로
folder = "./dataset"
json_path = "ply_files.json"

# 1. 각 카테고리에 해당하는 resolution 값을 딕셔너리로 정의합니다.
# 이 값을 조절하여 카테고리별 설정을 변경할 수 있습니다.
resolutions = {
    "100": 1.0,
    "75": 0.8,
    "50": 0.8,
    "25": 0.8,
    "0": 0.8
}

# 2. 분류된 파일 목록이 담긴 JSON 파일을 읽어옵니다.
try:
    with open(json_path, "r", encoding="utf-8") as f:
        categorized_files = json.load(f)
except FileNotFoundError:
    print(f"오류: '{json_path}' 파일을 찾을 수 없습니다. 먼저 파일 분류 코드를 실행해 주세요.")
    exit() # 파일이 없으면 프로그램 종료

# 3. 모든 카테고리와 파일을 순회하는 반복문
print("=== 데이터 처리 시작 ===")

# resolutions 딕셔너리를 기준으로 외부 루프를 실행합니다.
for category, resolution in resolutions.items():
    
    print(f"\n--- [카테고리: {category}, 해상도: {resolution}] 처리 시작 ---")
    
    # JSON에서 현재 카테고리에 해당하는 파일 리스트를 가져옵니다.
    # .get(category, [])를 사용하면 JSON에 해당 카테고리가 없어도 오류 없이 빈 리스트를 반환합니다.
    filenames_in_category = categorized_files.get(category, [])
    
    if not filenames_in_category:
        print("처리할 파일이 없습니다.")
        continue # 파일이 없으면 다음 카테고리로 넘어감

    # 내부 루프에서 해당 카테고리의 모든 파일을 하나씩 처리합니다.
    for filename in filenames_in_category:
        
        # 실제 파일 경로를 만듭니다. (JSON에는 확장자가 없으므로 .ply를 붙여줍니다)
        file_path = os.path.join(folder, f"{filename}.ply")
        
        print(f"  - 파일 처리 중: {file_path} (해상도: {resolution})")
        
        
        filename = filename
        # PLY 파일 로드
        pcd = o3d.io.read_point_cloud(f"./dataset/{filename}.ply")

        GT = False
        if GT==True:
            mesh = o3d.io.read_triangle_mesh("./bottle2.stl")
            pointcloud = mesh.sample_points_poisson_disk(50000)
            coord_frame = o3d.geometry.TriangleMesh.create_coordinate_frame(size=50.0, origin=[0, 0, 0])

            mesh.compute_vertex_normals()
            mesh_triangles = np.asarray(mesh.triangles)
            vertex_positions = np.asarray(mesh.vertices)
            triangle_normals = np.asarray(mesh.triangle_normals)

            # 객체의 중심점 계산
            centroid = mesh.get_center()
            filtered_triangles = []
            for i, triangle in enumerate(mesh_triangles):
                # 삼각형의 중심점 계산
                tri_center = vertex_positions[triangle].mean(axis=0)
                # 객체 중심에서 삼각형 중심으로 향하는 벡터
                vec_to_center = tri_center - centroid
                # 법선 벡터와 방향 벡터를 내적
                dot_product = np.dot(triangle_normals[i], vec_to_center)
                # 내적 값이 양수이면 바깥쪽 면으로 판단
                if dot_product > 0:
                    filtered_triangles.append(triangle)
            # 3. 필터링된 면으로 새로운 메쉬 생성
            outer_mesh = o3d.geometry.TriangleMesh()
            outer_mesh.vertices = mesh.vertices
            outer_mesh.triangles = o3d.utility.Vector3iVector(np.array(filtered_triangles))
            # 4. 새로운 메쉬에서 포인트 클라우드 샘플링
            # n_points는 샘플링할 포인트 개수
            pcd = outer_mesh.sample_points_uniformly(number_of_points=50000)
            # 결과 시각화
            # o3d.visualization.draw_geometries([pcd,coord_frame ])




            pcd_array = np.asarray(pcd.points)


        # In[160]:


        import open3d as o3d
        import numpy as np

    
        if not GT: 
            ply_path = f"./dataset/{filename}.ply"

            pcd = o3d.io.read_point_cloud(ply_path)
            print(ply_path)


        pcd_array = np.asarray(pcd.points)
        print(pcd_array.shape)

        coord_frame = o3d.geometry.TriangleMesh.create_coordinate_frame(size=50.0, origin=[0, 0, 0])
        # o3d.visualization.draw_geometries([pcd, coord_frame])


        # In[161]:


        if GT==False:

            new_pcd_array = np.unique(pcd_array, axis=0)

            # new_pcd_array = new_pcd_array[new_pcd_array[:, 2] < 580]
            new_pcd_array = new_pcd_array[new_pcd_array[:, 2] < 1000]

            # new_pcd_array = new_pcd_array[new_pcd_array[:, 1] > -100] 
            new_pcd_array = new_pcd_array[new_pcd_array[:, 1] > -1000] #diagonal
            new_pcd_array = new_pcd_array[new_pcd_array[:, 1] < 120]
            new_pcd_array = new_pcd_array[new_pcd_array[:, 0] > -1000]
            new_pcd_array = new_pcd_array[new_pcd_array[:, 0] < 1000] #diagonal
            # new_pcd_array = new_pcd_array[new_pcd_array[:, 0] < 100] 
            # new_pcd_array -= np.mean(new_pcd_array, axis=0)
            print(np.mean(new_pcd_array, axis=0))

            new_pcd = o3d.geometry.PointCloud()
            new_pcd.points = o3d.utility.Vector3dVector(new_pcd_array)

            theta = np.radians(90)
            # theta = np.radians(-90)


            new_pcd_array = np.asarray(new_pcd.points)

            coord_frame = o3d.geometry.TriangleMesh.create_coordinate_frame(size=50.0, origin=[0, 0, 0])
            # o3d.visualization.draw_geometries([new_pcd, coord_frame])


        # ## Delete ground plane  

        # In[162]:


        if GT==False:
            
            plane_model, inliers = new_pcd.segment_plane(distance_threshold=1,
                                                    ransac_n=10,
                                                    num_iterations=1000)
            [a, b, c, d] = plane_model
            print(f"Plane equation: {a:.2f}x + {b:.2f}y + {c:.2f}z + {d:.2f} = 0")
            
            
            
            inlier_cloud = new_pcd.select_by_index(inliers)
            inlier_cloud.paint_uniform_color([1.0, 0, 1.0])
            outlier_cloud = new_pcd.select_by_index(inliers, invert=True)
            # o3d.visualization.draw_geometries([inlier_cloud, outlier_cloud],
            #                                 zoom=0.8,
            #                                 front=[-0.4999, -0.1659, -0.8499],
            #                                 lookat=[2.1813, 2.0619, 2.0999],
            #                                 up=[0.1204, -0.9852, 0.1215])
            
            new_pcd = outlier_cloud

            new_pcd_array = np.asarray(new_pcd.points)
            
            


        # ### Changing the source position "gt_filtered"
        # 

        # In[163]:


        CHECK_PERTURB = GT

        def random_rotation_matrix():
            """
            Generate a random 3x3 rotation matrix (SO(3) matrix).
            
            Uses the method described by James Arvo in "Fast Random Rotation Matrices" (1992):
            1. Generate a random unit vector for rotation axis
            2. Generate a random angle
            3. Create rotation matrix using Rodriguez rotation formula
            
            Returns:
                numpy.ndarray: A 3x3 random rotation matrix
            """
            ## for ground target
            # Generate random angle π/2
            theta = 0

            
            # axis is -y
            axis = np.array([
                1,
                0,
                0,
            ])
            
            # for lying target
            # theta will be pi/2
            # theta = np.pi/2
            # axis = np.array([
            #     0,
            #     1,
            #     0,
            # ])
            



            # Normalize to ensure it's a unit vector
            axis = axis / np.linalg.norm(axis)
            


            # Create the cross-product matrix K  skew-symmetric
            K = np.array([
                [0, -axis[2], axis[1]],
                [axis[2], 0, -axis[0]],
                [-axis[1], axis[0], 0]
            ])
            
            # Rodriguez rotation formula: R = I + sin(θ)K + (1-cos(θ))K²
            R = (np.eye(3) + 
                np.sin(theta) * K + 
                (1 - np.cos(theta)) * np.dot(K, K))
            
            return R

        if CHECK_PERTURB:
            R_pert = random_rotation_matrix()
            print(R_pert)
            t_pert = np.array([
                0,
                0,
                0
            ])

            
            perturbed_pcd_array = np.dot(R_pert, pcd_array.T).T + t_pert.T


            perturbed_pcd = o3d.geometry.PointCloud()
            perturbed_pcd.points = o3d.utility.Vector3dVector(perturbed_pcd_array)
            coord_frame = o3d.geometry.TriangleMesh.create_coordinate_frame(size=50.0, origin=[0, 0, 0])
            # o3d.visualization.draw_geometries([perturbed_pcd, coord_frame])


        # ### Rotate randomly in Target "noisy filtered"

        # In[164]:


        CHECK_PERTURB = not GT


        if CHECK_PERTURB:
            # R_pert = random_rotation_matrix()
            # print(R_pert)
            # t_pert = np.random.rand(3, 1)*3 #* 10

            
            # perturbed_pcd_array = np.dot(R_pert, new_pcd_array.T).T + t_pert.T
            perturbed_pcd_array = new_pcd_array
            perturbed_pcd = o3d.geometry.PointCloud()
            perturbed_pcd.points = o3d.utility.Vector3dVector(perturbed_pcd_array)
            
                
            now_centeroid = perturbed_pcd.get_center()
            perturbed_pcd.translate(centroid, relative=False)
        
            ## get centeroid vector
           
            translation_vector = centroid - now_centeroid

            np.savetxt(f"./centroid/{filename}.txt",translation_vector)

            ##### changed

            perturbed_pcd_array = np.asarray(perturbed_pcd.points)
            coord_frame = o3d.geometry.TriangleMesh.create_coordinate_frame(size=50.0, origin=[0, 0, 0])





            # o3d.visualization.draw_geometries([perturbed_pcd, coord_frame])


        # In[165]:


        def write_ply(points, output_path):
            """
            Write points and parameters to a PLY file
            
            Parameters:
            points: numpy array of shape (N, 3) containing point coordinates
            output_path: path to save the PLY file
            """
            with open(output_path, 'w') as f:
                # Write header
                f.write("ply\n")
                f.write("format ascii 1.0\n")
                
                # Write vertex element
                f.write(f"element vertex {len(points)}\n")
                f.write("property float x\n")
                f.write("property float y\n")
                f.write("property float z\n")
                
                # Write camera element
                f.write("element camera 1\n")
                f.write("property float view_px\n")
                f.write("property float view_py\n")
                f.write("property float view_pz\n")
                f.write("property float x_axisx\n")
                f.write("property float x_axisy\n")
                f.write("property float x_axisz\n")
                f.write("property float y_axisx\n")
                f.write("property float y_axisy\n")
                f.write("property float y_axisz\n")
                f.write("property float z_axisx\n")
                f.write("property float z_axisy\n")
                f.write("property float z_axisz\n")
                
                # Write phoxi frame parameters
                f.write("element phoxi_frame_params 1\n")
                f.write("property uint32 frame_width\n")
                f.write("property uint32 frame_height\n")
                f.write("property uint32 frame_index\n")
                f.write("property float frame_start_time\n")
                f.write("property float frame_duration\n")
                f.write("property float frame_computation_duration\n")
                f.write("property float frame_transfer_duration\n")
                f.write("property int32 total_scan_count\n")
                
                # Write camera matrix
                f.write("element camera_matrix 1\n")
                for i in range(9):
                    f.write(f"property float cm{i}\n")
                
                # Write distortion matrix
                f.write("element distortion_matrix 1\n")
                for i in range(14):
                    f.write(f"property float dm{i}\n")
                
                # Write camera resolution
                f.write("element camera_resolution 1\n")
                f.write("property float width\n")
                f.write("property float height\n")
                
                # Write frame binning
                f.write("element frame_binning 1\n")
                f.write("property float horizontal\n")
                f.write("property float vertical\n")
                
                # End header
                f.write("end_header\n")
                
                # Write vertex data
                for point in points:
                    f.write(f"{point[0]} {point[1]} {point[2]}\n")

                print(True)

        if GT: write_ply(perturbed_pcd_array, f"gt_filtered.ply")
        else: 
            write_ply(perturbed_pcd_array, f"./noisy_result/noisy_filtered_{filename}.ply")
            write_ply(new_pcd_array,f"./noisy_raw/noisy_filtered_{filename}.ply")
        # write_ply(new_pcd_array, "gt_filtered.ply")

        #!/usr/bin/env python
        # coding: utf-8

        # ## PCD file transformation

        # In[18]:


        # PLY 파일 읽기
        pcd = o3d.io.read_point_cloud("./gt_filtered.ply")

        # PCD 파일로 저장 (바이너리 형식)
        o3d.io.write_point_cloud("./initialize_pcdfile/gt_filtered.pcd", pcd)

        # 만약 ASCII 형식으로 저장하고 싶다면:
        # o3d.io.write_point_cloud("output_ascii.pcd", pcd, write_ascii=True)

        print("PLY 파일이 PCD 파일로 성공적으로 변환되었습니다.")


        # In[19]:


        # PLY 파일 읽기
        pcd = o3d.io.read_point_cloud(f"./noisy_result/noisy_filtered_{filename}.ply")

        # PCD 파일로 저장 (바이너리 형식)
        o3d.io.write_point_cloud(f"./initialize_pcdfile/first_{filename}.pcd", pcd)

        # 만약 ASCII 형식으로 저장하고 싶다면:
        # o3d.io.write_point_cloud("output_ascii.pcd", pcd, write_ascii=True)

        print("PLY 파일이 PCD 파일로 성공적으로 변환되었습니다.")


        # ## Execute initial Guess

        # In[20]:


        # import os
        # print(os.getcwd())

        # import subprocess

        # cmd = [
        #     'python3',
        #     '../../../KISS-Matcher/python/examples/run_kiss_matcher.py',
        #     '--src_path',
        #     f'./initialize_pcdfile/first_{filename}.pcd',
        #     '--tgt_path',
        #     './initialize_pcdfile/gt_filtered.pcd',
        #     '--resolution',
        #     '1'

        # ]
        # try:
        #     result = subprocess.run(cmd, capture_output=True, text=True, check=True)

        #     print("--- STDOUT (표준 출력) ---")
        #     print("명령어가 성공적으로 실행되었습니다.")
        #     print(result.stdout)

        # except FileNotFoundError:
        #     print("--- 에러 발생! ---")
        #     print(f"'{cmd[0]}' 파일을 찾을 수 없습니다.")
        #     print("경로가 올바른지, 파일이 그 위치에 존재하는지 확인해 주세요.")

        # except subprocess.CalledProcessError as e:
        #     print("--- 에러 발생! ---")
        #     print(f"명령어 실행 중 오류가 발생했습니다. (종료 코드: {e.returncode})")
        #     print("\n--- STDERR (에러 원인) ---")
        #     print(e.stderr)


        # # ## Saving initialized data
        # # 

        # # In[21]:


        # import shutil
        # import os

        # transformed_path = "output.ply"
        # destination_path = f"./initialized_result/initial_{filename}.ply"


        # shutil.move(transformed_path, destination_path)
        # print(f"Successfully moved and renamed '{transformed_path}' to '{destination_path}'")