scene.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # LICENSE HEADER MANAGED BY add-license-header
  2. #
  3. # Copyright 2018 Kornia Team
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. #
  17. """Module to generate synthetic 3d scenes."""
  18. import math
  19. from typing import Dict
  20. import torch
  21. from kornia.core import rand, stack, where
  22. from kornia.geometry.conversions import axis_angle_to_rotation_matrix
  23. from kornia.geometry.linalg import transform_points
  24. from .projection import projection_from_KRt, random_intrinsics
  25. def generate_scene(num_views: int, num_points: int) -> Dict[str, torch.Tensor]:
  26. """Generate 3d scene."""
  27. # Generate the 3d points
  28. points3d = rand(1, num_points, 3) # NxMx3
  29. # Create random camera matrix
  30. K = random_intrinsics(0.0, 100.0) # 1x3x3
  31. # Create random rotation per view
  32. ang = torch.rand(num_views, 1) * math.pi * 2.0
  33. rvec = torch.rand(num_views, 3)
  34. rvec = ang * rvec / torch.norm(rvec, dim=1, keepdim=True) # Nx3
  35. rot_mat = axis_angle_to_rotation_matrix(rvec) # Nx3x3
  36. # matches with cv2.Rodrigues -> yay !
  37. # Create random translation per view
  38. tx = torch.empty(num_views).uniform_(-0.5, 0.5)
  39. ty = torch.empty(num_views).uniform_(-0.5, 0.5)
  40. tz = torch.empty(num_views).uniform_(-1.0, 2.0)
  41. tvec = stack([tx, ty, tz], dim=1)[..., None]
  42. # Make sure the shape is in front of the camera
  43. points3d_trans = (rot_mat @ points3d.transpose(-2, -1)) + tvec
  44. min_dist = torch.min(points3d_trans[:, 2], dim=1)[0]
  45. tvec[:, 2, 0] = where(min_dist < 0, tz - min_dist + 1.0, tz)
  46. # compute projection matrices
  47. P = projection_from_KRt(K, rot_mat, tvec)
  48. # project points3d and backproject to image plane
  49. points2d = transform_points(P, points3d.expand(num_views, -1, -1))
  50. return {"K": K, "R": rot_mat, "t": tvec, "P": P, "points3d": points3d, "points2d": points2d}