Skip to content

Instantly share code, notes, and snippets.

@Ajk4
Last active August 7, 2024 16:12
Show Gist options
  • Save Ajk4/a0d66f7edf72601c99ec55f856aa0729 to your computer and use it in GitHub Desktop.
Save Ajk4/a0d66f7edf72601c99ec55f856aa0729 to your computer and use it in GitHub Desktop.
Convert point cloud to depth map
import numpy as np
def pointcloud_to_depth_map(pointcloud: np.ndarray, theta_res=150, phi_res=32, max_depth=50, phi_min_degrees=60,
phi_max_degrees=100) -> np.ndarray:
"""
All params are set so they match default carla lidar settings
"""
assert pointcloud.shape[1] == 3, 'Must have (N, 3) shape'
assert len(pointcloud.shape) == 2, 'Must have (N, 3) shape'
xs = pointcloud[:, 0]
ys = pointcloud[:, 1]
zs = pointcloud[:, 2]
rs = np.sqrt(np.square(xs) + np.square(ys) + np.square(zs))
phi_min = np.deg2rad(phi_min_degrees)
phi_max = np.deg2rad(phi_max_degrees)
phi_range = phi_max - phi_min
phis = np.arccos(zs / rs)
THETA_MIN = -np.pi
THETA_MAX = np.pi
THETA_RANGE = THETA_MAX - THETA_MIN
thetas = np.arctan2(xs, ys)
phi_indices = ((phis - phi_min) / phi_range) * (phi_res - 1)
phi_indices = np.rint(phi_indices).astype(np.int16)
theta_indices = ((thetas - THETA_MIN) / THETA_RANGE) * theta_res
theta_indices = np.rint(theta_indices).astype(np.int16)
theta_indices[theta_indices == theta_res] = 0
normalized_r = rs / max_depth
canvas = np.ones(shape=(theta_res, phi_res), dtype=np.float32)
# We might need to filter out out-of-bound phi values, if min-max degrees doesnt match lidar settings
canvas[theta_indices, phi_indices] = normalized_r
return canvas
import numpy as np
import matplotlib.pyplot as plt
from pointcloud_to_depthmap import pointcloud_to_depth_map
pointcloud = np.load("lidar.npy")
depth_map = pointcloud_to_depth_map(pointcloud)
depth_map = depth_map * 256
depth_map = np.flip(depth_map, axis=1) # so floor is down
depth_map = np.swapaxes(depth_map, 0, 1)
plt.imshow(depth_map, cmap='gray_r')
plt.show()
@theotziol
Copy link

I'm new to this topic and i have a few questions. I need for a project to convert pointclouds from 2 differents cameras to depth maps and i don't know default settings. I want to do an orthographic projection with every z point, a grey scale value. Anyway i was wondering if you had implemented something similar that i can look at. Your code is very good and clean by the way. I lost it with the geometry, so for begginer as me if you could add some geometry comments or post a link of references for explanations it would be awesome. Thank you

@balamuruganky
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment