pcd2tiff.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import os
  2. import numpy as np
  3. import open3d as o3d
  4. from tifffile import tifffile
  5. # 相机内参矩阵
  6. K = np.array([
  7. [1.30449e3, 0, 5.2602e2],
  8. [0, 1.30449e3, 1.07432e3],
  9. [0, 0, 1]
  10. ])
  11. fx, fy = K[0, 0], K[1, 1]
  12. cx, cy = K[0, 2], K[1, 2]
  13. # 目标图像尺寸
  14. height, width = 2000, 2000
  15. def pointscloud2depthmap(points):
  16. """将点云投影为深度图"""
  17. point_image = np.zeros((height, width, 3), dtype=np.float32)
  18. for point in points:
  19. X, Y, Z = point
  20. if Z > 0:
  21. u = int((X * fx) / Z + cx)
  22. v = int((Y * fy) / Z + cy)
  23. if 0 <= u < width and 0 <= v < height:
  24. point_image[v, u, :] = point
  25. return point_image
  26. def process_pcd_folder(folder_path, output_folder, mode='f32'):
  27. """
  28. 批量处理PCD文件,生成深度图并保存为TIFF格式。
  29. mode: 'f32' | 'int8' | 'all32'
  30. """
  31. if not os.path.exists(output_folder):
  32. os.makedirs(output_folder)
  33. for filename in os.listdir(folder_path):
  34. if filename.lower().endswith('.pcd'):
  35. full_path = os.path.join(folder_path, filename)
  36. print(f"Processing: {full_path}")
  37. try:
  38. # 读取点云
  39. pcd = o3d.io.read_point_cloud(full_path)
  40. points = np.asarray(pcd.points)
  41. # 投影为图像
  42. point_image = pointscloud2depthmap(points)
  43. if mode == 'f32':
  44. depth_map = point_image[:, :, 2].astype(np.float32)
  45. elif mode == 'int8':
  46. depth_map = point_image[:, :, 2].astype(np.int8)
  47. elif mode == 'all32':
  48. depth_map = point_image.astype(np.float32)
  49. else:
  50. raise ValueError(f"Unsupported mode: {mode}")
  51. # 输出路径
  52. output_name = os.path.splitext(filename)[0] + ".tiff"
  53. output_path = os.path.join(output_folder, output_name)
  54. # 保存TIFF
  55. tifffile.imwrite(output_path, depth_map)
  56. print(f"Saved depth map to: {output_path}")
  57. except Exception as e:
  58. print(f"Error processing {filename}: {e}")
  59. def main():
  60. input_folder = r"G:\python_ws_g\data\2025-05-22-11-40-20_LaserData_Hi221518(1)"
  61. # 定义各输出路径
  62. output_f32 = r"G:\python_ws_g\data\process_pcd_folder_f32"
  63. output_int8 = r"G:\python_ws_g\data\process_pcd_folder_int8"
  64. output_all32 = r"G:\python_ws_g\data\process_pcd_folder_all32"
  65. # 执行处理
  66. process_pcd_folder(input_folder, output_f32, mode='f32')
  67. process_pcd_folder(input_folder, output_int8, mode='int8')
  68. process_pcd_folder(input_folder, output_all32, mode='all32')
  69. if __name__ == '__main__':
  70. main()