graphics_utils.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import torch
  2. import math
  3. import numpy as np
  4. from typing import NamedTuple
  5. class BasicPointCloud(NamedTuple):
  6. points : np.array
  7. colors : np.array
  8. normals : np.array
  9. def geom_transform_points(points, transf_matrix):
  10. P, _ = points.shape
  11. ones = torch.ones(P, 1, dtype=points.dtype, device=points.device)
  12. points_hom = torch.cat([points, ones], dim=1)
  13. points_out = torch.matmul(points_hom, transf_matrix.unsqueeze(0))
  14. denom = points_out[..., 3:] + 0.0000001
  15. return (points_out[..., :3] / denom).squeeze(dim=0)
  16. def getWorld2View(R, t):
  17. Rt = np.zeros((4, 4))
  18. Rt[:3, :3] = R.transpose()
  19. Rt[:3, 3] = t
  20. Rt[3, 3] = 1.0
  21. return np.float32(Rt)
  22. def getWorld2View2(R, t, translate=np.array([.0, .0, .0]), scale=1.0):
  23. Rt = np.zeros((4, 4))
  24. Rt[:3, :3] = R.transpose()
  25. Rt[:3, 3] = t
  26. Rt[3, 3] = 1.0
  27. C2W = np.linalg.inv(Rt)
  28. cam_center = C2W[:3, 3]
  29. cam_center = (cam_center + translate) * scale
  30. C2W[:3, 3] = cam_center
  31. Rt = np.linalg.inv(C2W)
  32. return np.float32(Rt)
  33. def getProjectionMatrix(znear, zfar, fovX, fovY):
  34. tanHalfFovY = math.tan((fovY / 2))
  35. tanHalfFovX = math.tan((fovX / 2))
  36. top = tanHalfFovY * znear
  37. bottom = -top
  38. right = tanHalfFovX * znear
  39. left = -right
  40. P = torch.zeros(4, 4)
  41. z_sign = 1.0
  42. P[0, 0] = 2.0 * znear / (right - left)
  43. P[1, 1] = 2.0 * znear / (top - bottom)
  44. P[0, 2] = (right + left) / (right - left)
  45. P[1, 2] = (top + bottom) / (top - bottom)
  46. P[3, 2] = z_sign
  47. P[2, 2] = z_sign * zfar / (zfar - znear)
  48. P[2, 3] = -(zfar * znear) / (zfar - znear)
  49. return P
  50. def fov2focal(fov, pixels):
  51. return pixels / (2 * math.tan(fov / 2))
  52. def focal2fov(focal, pixels):
  53. return 2*math.atan(pixels/(2*focal))