pcd2clolor_init.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import os
  2. import cv2
  3. import numpy as np
  4. import open3d as o3d
  5. from glob import glob
  6. from tifffile import imwrite as tif_write
  7. # 相机内参矩阵
  8. K = np.array([
  9. [1.30449e3, 0, 5.2602e2],
  10. [0, 1.30449e3, 1.07432e3],
  11. [0, 0, 1]
  12. ])
  13. fx, fy = K[0, 0], K[1, 1]
  14. cx, cy = K[0, 2], K[1, 2]
  15. # 目标图像尺寸
  16. height, width = 2000, 2000
  17. def pointscloud2colorimg(points):
  18. color_image = np.zeros((height, width, 3), dtype=np.float32)
  19. for point in points:
  20. X, Y, Z, r, g, b = point
  21. if Z > 0:
  22. u = int((X * fx) / Z + cx)
  23. v = int((Y * fy) / Z + cy)
  24. if 0 <= u < width and 0 <= v < height:
  25. color_image[v, u] = [r * 255, g * 255, b * 255]
  26. return color_image
  27. def pointscloud2depthmap(points):
  28. depth_map = np.zeros((height, width), dtype=np.float32)
  29. for point in points:
  30. X, Y, Z, *_ = point
  31. if Z > 0:
  32. u = int((X * fx) / Z + cx)
  33. v = int((Y * fy) / Z + cy)
  34. if 0 <= u < width and 0 <= v < height:
  35. depth_map[v, u] = Z
  36. return depth_map
  37. def process_pcd_file(pcd_path, color_dir, depth_dir):
  38. filename = os.path.splitext(os.path.basename(pcd_path))[0]
  39. print(f"Processing: {filename}")
  40. pcd = o3d.io.read_point_cloud(pcd_path)
  41. points = np.asarray(pcd.points) #xyz
  42. colors = np.asarray(pcd.colors) #rgb
  43. if points.shape[0] == 0 or colors.shape[0] == 0:
  44. print(f"Skipping empty or invalid PCD: {filename}")
  45. return
  46. points_colored = np.hstack((points, colors))
  47. color_img = pointscloud2colorimg(points_colored)
  48. depth_map = pointscloud2depthmap(points_colored)
  49. # 保存图像
  50. color_img_u8 = np.clip(color_img, 0, 255).astype(np.uint8)
  51. cv2.imwrite(os.path.join(color_dir, f"{filename}_color.jpg"), color_img_u8)
  52. depth_map_mm = (depth_map ).astype(np.float32)
  53. tif_write(os.path.join(depth_dir, f"{filename}_depth.tiff"), depth_map_mm)
  54. print(f"Saved color and depth images for {filename}")
  55. # 设置输入输出路径
  56. input_dir = r"G:\python_ws_g\data\2025-05-22-11-40-20_LaserData_Hi221518(1)"
  57. output_base = r"G:\python_ws_g\data\pcd2color_result"
  58. color_dir = os.path.join(output_base, "color_jpg")
  59. depth_dir = os.path.join(output_base, "depth_tiff")
  60. os.makedirs(color_dir, exist_ok=True)
  61. os.makedirs(depth_dir, exist_ok=True)
  62. # 获取所有 PCD 文件
  63. pcd_files = glob(os.path.join(input_dir, "*.pcd"))
  64. print(f"Found {len(pcd_files)} PCD files.")
  65. # 批量处理
  66. for pcd_path in pcd_files:
  67. process_pcd_file(pcd_path, color_dir, depth_dir)