NeRF Ray Sampling
Implement ray generation for Neural Radiance Fields (NeRF), a technique used to represent 3D scenes as continuous functions. This involves generating one ray for each pixel in an image, given camera parameters such as position and orientation.
The process relies on projective geometry, where each pixel's direction is calculated using the camera's intrinsic matrix and the pixel's coordinates. The ray origin is the camera position, while the ray direction points from the camera through the pixel.
Inputs
- pose: a camera-to-world matrix , where () is the camera's rotation and is the camera position in world coordinates.
- K: the pinhole intrinsic matrix with focal lengths (diagonal) and principal point (last column).
- img_size: a tuple .
Key steps
- For the pixel in column and row , compute its camera-space direction. Use the NeRF (OpenGL) convention: the camera looks down and image points up:
- Transform the direction by the camera's rotation: (do not normalise it).
- The ray origin is for every pixel.
Points along each ray, used later for volume rendering, then follow (you return only origins and directions, not the sampled points):
Output
Return a tuple (rays_o, rays_d) of two float arrays, each of shape : one row per pixel in row-major order (row , column is row ).
This technique is widely used in computer vision and 3D reconstruction applications.
Example
Camera pose, K, image size
Ray origins and directions
- Inputs (the test case):
poseis the identity, so and the camera sits at .Khas and principal point .img_sizeis : pixels, so rays. - Top-left pixel (): . Rotating by changes nothing, so this is direction row 0.
- Other pixels: gives (row 1), so one column shifts by . The centre gives , straight down the optical axis; the bottom-right gives , row .
- Origins: every row is . With translation every origin becomes and the directions stay the same.
- Output: the ray origins and directions, two arrays of shape , which is why the test prints
(10000, 3). Notice the camera-space is always : directions are not unit length.
Constraints
- Input parameters: camera pose (3D numpy array), intrinsic matrix K (3x3 numpy array), image size (2-element tuple of integers)
- Valid ranges: camera pose and intrinsic matrix values are floating-point numbers, image size values are positive integers, pixel coordinates are in the range [0, image_size)
- Output format: return ray origins and ray directions as two 2D numpy arrays of shape (H*W, 3): one row per pixel, row-major (e.g. (10000, 3) for a 100×100 image), both with floating-point precision
- Special conditions: assume the input camera pose is in the format [x, y, z] and the intrinsic matrix K is in the standard pinhole camera format, with no lens distortion or other aberrations