Introducing 3D Computer Vision and Geometry
local graph
In this chapter, we will learn about some basic concepts of 3D computer vision and geometry that will be especially useful for later chapters in this book. We will start by discussing what rendering, rasterization, and shading are. We will go through different lighting models and shading models, such as point light sources, directional light sources, ambient lighting, diffusion, highlights, and shininess. We will go through a coding example for rendering a mesh model using different lighting models and parameters.
We will then learn how to use PyTorch for solving optimization problems. Particularly, we will go through stochastic gradient descent over heterogeneous mini-batches, which becomes possible by using PyTorch3D. We will also learn about different formats for mini-batches in PyTorch3D, including the list, padded, and packed formats, and learn how to convert between the different formats. In the last part of the chapter, we will discuss some frequently used rotation representations and how to convert between these representations.
In this chapter, we’re going to cover the following topics:
- Exploring the basic concepts of rendering, rasterization, and shading
- Understanding the Lambertian shading and Phong shading models
- How to define a PyTorch tensor and optimize the tensor using an optimizer
- How to define a mini-batch and heterogeneous mini-batch and packed and padded tensors
- Rotations and different ways to describe rotations
- Exponential mapping and log mapping in the SE(3) space
Exploring the basic concepts of rendering, rasterization, and shading
Section titled “Exploring the basic concepts of rendering, rasterization, and shading”Rendering is a process that takes 3D data models of the world around our camera as input and output images. It is an approximation to the physical process where images are formed in our camera in the real world. Typically, the 3D data models are meshes. In this case, rendering is usually done using ray tracing:
Figure 2.1: Rendering by ray tracing (rays are generated from camera origins and go through the image pixels for finding relevant mesh faces)
An example of ray tracing processing is shown in Figure 2.1. In the example, the world model contains one 3D sphere, which is represented by a mesh model. To form the image of the 3D sphere, for each image pixel, we generate one ray, starting from the camera origin and going through the image pixel. If one ray intersects with one mesh face, then we know the mesh face can project its color to the image pixel. We also need to trace the depth of each intersection because a face with a smaller depth would occlude faces with larger depths.
Thus, the process of rendering can usually be divided into two stages – rasterization and shading. The ray tracing process is a typical rasterization process – that is, the process of finding relevant geometric objects for each image pixel. Shading is the process of taking the outputs of the rasterization and computing the pixel value for each image pixel.
The pytorch3d.renderer.mesh.rasterize_meshes.rasterize_meshes function in PyTorch3D usually computes the following four things for each image pixel:
pix_to_faceis a list of face indices that the ray may intersect.zbufis a list of depth values of these faces.bary_coordsis a list of barycentric coordinates of the intersection point of each face and the ray.pix_distsis a list of signed distances between pixels (x and y) and the nearest point on all the faces where the ray intersects. The values of this list can take negative values since it contains signed distances.
Note that usually, one face with the smallest depth would occlude all the mesh faces with larger depths. Thus, if all we need is the rendered image, then all we need in this list is the face with the smallest depth. However, with the more advanced setting of differentiable rendering (which we will cover in later chapters of this book), the pixel colors are usually fused from multiple mesh faces.
Understanding barycentric coordinates
Section titled “Understanding barycentric coordinates”For each point coplanar with a mesh face, the coordinates of the point can always be written as a linear combination of the coordinates of the three vertices of the mesh face. For example, as shown in the following diagram, the point p can be written as , where A, B, and C are the coordinates of the three vertices of the mesh face. Thus, we can represent each such point with the coefficients u, v, and w. This representation is called the barycentric coordinates of the point. For point lays within the mesh face triangle, and all u, v, w are positive numbers. Since barycentric coordinates define any point inside a face as a function of face vertices, we can use the same coefficients to interpolate other properties across the whole face as a function of the properties defined at the vertices of the face. For example, we can use it for shading as shown in Figure 2.2:
Figure 2.2: Definition of the barycentric coordinate system
Once we have a list of the pix_to_face, zbuf, bary_coords, and dists values, a shading process would mimic the physical process of image formation as in the real world. Thus, we are going to discuss several physical models for color formation.
Light source models
Section titled “Light source models”Light propagation in the real world can be a sophisticated process. Several approximations of light sources are usually used in shading to reduce computational costs:
- The first assumption is ambient lighting, where we assume that there is some background light radiation after sufficient reflections, such that they usually come from all directions with almost the same amplitude at all image pixels.
- Another assumption that we usually use is that some light sources can be considered point light sources. A point light source radiates lights from one single point and the radiations at all directions have the same color and amplitude.
- A third assumption that we usually use is that some light sources can be modeled as directional light sources. In such a case, the light directions from the light source are identical at all the 3D spatial locations. Directional lighting is a good approximation model for cases where the light sources are far away from the rendered objects – for example, sunlight.
Understanding the Lambertian shading model
Section titled “Understanding the Lambertian shading model”The first physical model that we will discuss is Lambert’s cosine law. Lambertian surfaces are types of objects that are not shiny at all, such as paper, unfinished wood, and unpolished stones:
Figure 2.3: Light diffusion on Lambertian surfaces
Figure 2.3 shows an example of how lights diffuse on a Lambertian surface. One basic idea of the Lambertian cosine law is that for Lambertian surfaces, the amplitude of the reflected light does not depend on the viewer’s angle, but only depends on the angle between the surface normal and the direction of the incident light. More precisely, the intensity of the reflected light is as follows:
Here, is the material’s reflected coefficient and is the amplitude of the incident light. If we further consider the ambient light, the amplitude of the reflected light is as follows:
Here, is the amplitude of the ambient light.
Understanding the Phong lighting model
Section titled “Understanding the Phong lighting model”For shiny surfaces, such as polished tile floors and glossy paint, the reflected light also contains a highlight component. The Phong lighting model is a frequently used model for these glossy components:
Figure 2.4: The Phong lighting model
An example of the Phong lighting model is shown in Figure 2.4. One basic principle of the Phong lighting model is that the shiny light component should be strongest in the direction of reflection of the incoming light. The component would become weaker as the angle between the direction of reflection and the viewing angle becomes larger. More precisely, the amplitude of the shiny light component is equal to the following:
Here, the exponent is a parameter of the model for controlling the speed at which the shiny components attenuate when the viewing angle is away from the direction of reflection. Finally, if we consider all three major components – ambient lighting, diffusion, and highlights – the final equation for the amplitude of light is as follows:
Note that the preceding equation applies to each color component. In other words, we will have one of these equations for each color channel (red, green, and blue) with a distinct set of values: Now, we have learned about the basic concepts of rendering, rasterization, and rendering. We have also learned about the different light source models and shading models. We are ready to perform some coding exercises to use these light sources and shading models.
Coding exercises for 3D rendering
Section titled “Coding exercises for 3D rendering”In this section, we will look at a concrete coding exercise using PyTorch3D for rendering a mesh model. We are going to learn how to define a camera model and how to define a light source in PyTorch3D. We will also learn how to change the incoming light components and material properties so that more realistic images can be rendered by controlling the three light components (ambient, diffusion, and glossy):
- First, we need to import all the Python modules that we need:
import open3dimport osimport sysimport torchimport matplotlib.pyplot as pltfrom pytorch3d.io import load_objs_as_meshesfrom pytorch3d.renderer import ( look_at_view_transform, PerspectiveCameras, PerspectiveCameras, PointLights, Materials, RasterizationSettings, MeshRenderer, MeshRasterizer)from pytorch3d.renderer.mesh.shader import HardPhongShadersys.path.append(os.path.abspath(''))- Then, we need to load the mesh that we are going to use. The
cow.objfile contains a mesh model for a toy cow object:
DATA_DIR = "./data"obj_filename = os.path.join(DATA_DIR, "cow_mesh/cow.obj")device = torch.device('cuda')mesh = load_objs_as_meshes([obj_filename], device=device)- We will define the cameras and light sources next. We use the
look_at_view_transformfunction to map easy-to-understand parameters, such as the distance from the camera, elevation angle, and azimuth angle to obtain the rotation (R) and translation (T) matrices. TheRandTvariables define where we are going to place our camera. Thelightsvariable is a point light source placed at[0.0, 0.0, -3.0]as its location:
R, T = look_at_view_transform(2.7, 0, 180)cameras = PerspectiveCameras(device=device, R=R, T=T)lights = PointLights(device=device, location=[[0.0, 0.0, -3.0]])- We will define a
renderervariable of theMeshRenderertype. Arenderervariable is a callable object, which can take a mesh as input and output the rendered images. Note that the renderer takes two inputs in its initialization – one rasterizer and one shader. PyTorch3D has defined several different types of rasterizers and shaders. Here, we are going to useMeshRasterizerandHardPhongShader. Note that we can also specify the setting of the rasterizer.image_sizeis equal to512here, which implies the rendered images would be 512 x 512 pixels.blur_radiusis set to0andfaces_per_pixelis set to1. Theblur_radiusandfaces_per_pixelsettings are the most useful for differentiable rendering, whereblur_radiusshould be greater than0andfaces_per_pixelshould be greater than1:
raster_settings = RasterizationSettings( image_size=512, blur_radius=0.0, faces_per_pixel=1,)renderer = MeshRenderer( rasterizer=MeshRasterizer( cameras=cameras, raster_settings=raster_settings ), shader = HardPhongShader( device = device, cameras = cameras, lights = lights ))- We are therefore ready to run our first rendering results by calling the renderer and passing the mesh model. The rendered image is shown in Figure 2.5:
images = renderer(mesh)plt.figure(figsize=(10, 10))plt.imshow(images[0, ..., :3].cpu().numpy())plt.axis("off")plt.savefig('light_at_front.png')plt.show()Figure 2.5: The rendered image when the light source is placed in front
- Next, we will change the location of the light source to the back of the mesh and see what will happen. The rendered image is shown in Figure 2.6. In this case, the light from the point light source cannot intersect with any mesh faces that are facing us. Thus, all the colors that we can observe here are due to ambient light:
lights.location = torch.tensor([0.0, 0.0, +1.0], device=device)[None]images = renderer(mesh, lights=lights, )plt.figure(figsize=(10, 10))plt.imshow(images[0, ..., :3].cpu().numpy())plt.axis("off")plt.savefig('light_at_back.png')plt.show()Figure 2.6: The rendered image when the light source is placed behind the toy cow
- In the next experiment, we are going to define a
materialsdata structure. Here, we change the configuration so that the ambient components are close to 0 (indeed, being0.01). Because the point light source is behind the object and the ambient light is also turned off, the rendered object does not reflect any light now. The rendered image is shown in Figure 2.7:
materials = Materials( device=device, specular_color=[[0.0, 1.0, 0.0]], shininess=10.0, ambient_color=((0.01, 0.01, 0.01),),)images = renderer(mesh, lights=lights, materials = materials)plt.figure(figsize=(10, 10))plt.imshow(images[0, ..., :3].cpu().numpy())plt.axis("off")plt.savefig('dark.png')plt.show()Figure 2.7: The rendered image without ambient light and the point light source behind the toy cow
- In the next experiment, we will rotate the camera again and redefine the light source location so that the light can shine on the cow’s face. Note that when we define the material, we set
shininessto10.0. Thisshininessparameter is precisely thepparameter in the Phong lighting model.specular_coloris[0.0, 1.0, 0.0], which implies that the surface is shiny mainly in the green component. The rendered results are shown in Figure 2.8:
R, T = look_at_view_transform(dist=2.7, elev=10, azim=-150)cameras = PerspectiveCameras(device=device, R=R, T=T)lights.location = torch.tensor([[2.0, 2.0, -2.0]], device=device)materials = Materials( device=device, specular_color=[[0.0, 1.0, 0.0]], shininess=10.0)images = renderer(mesh, lights=lights, materials=materials, cameras=cameras)plt.figure(figsize=(10, 10))plt.imshow(images[0, ..., :3].cpu().numpy())plt.axis("off")plt.savefig('green.png')plt.show()Figure 2.8: The rendered image with specular lighting components
- In the next experiment, we are going to change
specular_colortoredand increase theshininessvalue. The results are shown in Figure 2.9:
materials = Materials( device=device, specular_color=[[1.0, 0.0, 0.0]], shininess=20.0)images = renderer(mesh, lights=lights, materials=materials, cameras=cameras)plt.figure(figsize=(10, 10))plt.imshow(images[0, ..., :3].cpu().numpy())plt.savefig('red.png')plt.axis("off")plt.show()Figure 2.9: The rendered image with a red specular color
- Finally, we turn off the shininess and the results are shown in Figure 2.10:
materials = Materials( device=device, specular_color=[[0.0, 0.0, 0.0]], shininess=0.0)images = renderer(mesh, lights=lights, materials=materials, cameras=cameras)plt.figure(figsize=(10, 10))plt.imshow(images[0, ..., :3].cpu().numpy())plt.savefig('blue.png')plt.axis("off")plt.show()Figure 2.10: The rendered image without specular components
In the first part of this chapter, we mainly discussed rendering and shading, which are super important for 3D computer vision. Next, we will discuss another very important topic for 3D deep learning, which is the heterogeneous batch issue for optimization.
Using PyTorch3D heterogeneous batches and PyTorch optimizers
Section titled “Using PyTorch3D heterogeneous batches and PyTorch optimizers”In this section, we are going to learn how to use the PyTorch optimizer on PyTorch3D heterogeneous mini-batches. In deep learning, we are usually given a list of data examples, such as the following ones – .. Here, are the observations and are the prediction values. For example, may be some images and the ground-truth classification results – for example, “cat” or “dog”. A deep neural network is then trained so that the outputs of the neural networks are as close to as possible. Usually, a loss function between the neural network outputs and is defined so that the loss function values decrease as the neural network outputs become closer to .
Thus, training a deep learning network is usually done by minimizing the loss function that is evaluated on all training data examples, and . A straightforward method used in many optimization algorithms is computing the gradients first, as shown in the following equation, and then modifying the parameters of the neural network along the direction of the negative gradient. In the equation, f represents the neural network that takes as its input and has parameters Ɵ; loss is the loss function between the neural network outputs and the ground-truth prediction :
However, computing this gradient is expensive, as the computational cost is proportional to the size of the training dataset. In reality, a Stochastic Gradient Descent (SGD) algorithm is used instead of the original gradient descent algorithm. In the SGD algorithm, the descent direction is computed as in the following equation:
In the equation, the so-called mini-batch D is a small subset of all the training data examples. The mini-batch D is randomly sampled from the whole training data examples in each iteration. The SGD algorithm has a much lower computational cost than the gradient descent algorithm. Due to the law of large numbers, the computed descent directions in SGD are approximately close to the gradient descent directions. It is also widely believed that SGD introduces certain implicit regularization, which may contribute to the nice generalization properties of deep learning. The method for choosing the size of the mini-batch is an important hyperparameter that needs to be considered carefully. Nevertheless, the SGD algorithm and its variants have been the methods of choice for training deep learning models.
For many data types, such as images, the data can easily be made homogeneous. We can form a mini-batch of images all with the same widths, heights, and channels. For example, a mini-batch of eight images with three channels (the three colors red, green, and blue), a height of 256, and a width of 256 can be made into a PyTorch tensor with the dimensions 8 x 3 x 256 x 256. Usually, the first dimension of the tensor represents the data sample indices within the mini-batch. Usually, computations on this kind of homogeneous data can be done efficiently using GPUs. On the other hand, 3D data is usually heterogeneous. For example, meshes within one mini-batch may contain different numbers of vertices and faces. Processing this heterogeneous data on GPUs efficiently is not a trivial issue. Coding for the heterogeneous mini-batch processing can also be tedious. Luckily, PyTorch3D has the capacity to handle heterogeneous mini-batches very efficiently. We will go over a coding exercise involving these PyTorch3D capacities in the next section.
A coding exercise for a heterogeneous mini-batch
Section titled “A coding exercise for a heterogeneous mini-batch”In this section, we are going to learn how to use the PyTorch optimizer and PyTorch3D heterogeneous mini-batch capacities by looking at a toy example. In this example, we will consider a problem where a depth camera is placed at an unknown location and we want to estimate the unknown location using the sensing results of the camera. To simplify the problem, we assume that the orientation of the camera is known and the only unknown is the 3D displacement.
More specifically, we assume that the camera observes three objects in the scene and we know the ground-truth mesh models of the three objects. Let us look at the code using PyTorch and PyTorch3D to solve the problem as follows:
- In the first step, we are going to import all the packages that we are going to use:
import open3dimport osimport torchfrom pytorch3d.io import load_objs_as_meshesfrom pytorch3d.structures.meshes import join_meshes_as_batchfrom pytorch3d.ops import sample_points_from_meshesfrom pytorch3d.loss import chamfer_distanceimport numpy as np- In the next step, we will define a
torchdevice using either a CPU or CUDA:
if torch.cuda.is_available(): device = torch.device("cuda:0")else: device = torch.device("cpu") print("WARNING: CPU only, this will be slow!")- The mesh models that you are going to use in this toy example are included in the code repository and are under the
datasubfolder. We are going to use three mesh models contained in thecube.obj,diamond.objanddodecahedron.objfiles. In the following code snippet, we are using theOpen3Dlibrary to load these mesh models and visualize them:
mesh_names = ['cube.obj', 'diamond.obj', 'dodecahedron.obj']data_path = './data'for mesh_name in mesh_names: mesh = open3d.io.read_triangle_mesh(os.path.join(data_path, mesh_name)) open3d.visualization.draw_geometries([mesh], mesh_show_wireframe = True, mesh_show_back_face = True, )- Next, we are going to use PyTorch3D to load the same meshes and build a list of meshes, which is the
mesh_listvariable:
mesh_list = list()device = torch.device('cuda')for mesh_name in mesh_names: mesh = load_objs_as_meshes([os.path.join(data_path, mesh_name)], device=device) mesh_list.append(mesh)- Finally, we can create a PyTorch3D mini-batch of meshes by using the
join_meshes_as_batchPyTorch3D function. The function takes a list of meshes and returns a mini-batch of meshes:
mesh_batch = join_meshes_as_batch(mesh_list, include_textures = False)In each PyTorch3D mini-batch, there are three ways to represent vertices and faces:
- List format: The vertices are represented by a list of tensors where each tensor represents the vertices or faces of one mesh within the mini-batch.
- Padded format: All the vertices are represented by one tensor and the data of the smaller meshes are zero-padded so that all the meshes now have the same numbers of vertices and faces.
- Packed format: All the vertices or faces are packed into one tensor. For each vertex or face, which mesh it belongs to is tracked internally.
The three representations all have their pros and cons. Nevertheless, the formats can be converted between each other efficiently by using the PyTorch3D API.
- The next code snippet shows an example of how to return vertices and faces in a list format from a mini-batch:
vertex_list = mesh_batch.verts_list()print('vertex_list = ', vertex_list)face_list = mesh_batch.faces_list()print('face_list = ', face_list)- To return vertices and faces in the padded format, we can use the following PyTorch3D API:
vertex_padded = mesh_batch.verts_padded()print('vertex_padded = ', vertex_padded)face_padded = mesh_batch.faces_padded()print('face_padded = ', face_padded)- To get vertices and faces in the packed format, we can use the following code snippet:
vertex_packed = mesh_batch.verts_packed()print('vertex_packed = ', vertex_packed)face_packed = mesh_batch.faces_packed()print('face_packed = ', face_packed)num_vertices = vertex_packed.shape[0]print('num_vertices = ', num_vertices)- In this coding example, we consider the
mesh_batchvariable as the ground-truth mesh model for the three objects. We will then simulate a noisy and displaced version of the three meshes. In the first step, we want to clone the ground truth mesh models:
mesh_batch_noisy = mesh_batch.clone()- We then define a
motion_gtvariable to represent the displacement between the camera location and the origin:
motion_gt = np.array([3, 4, 5])motion_gt = torch.as_tensor(motion_gt)print('motion ground truth = ', motion_gt)motion_gt = motion_gt[None, :]motion_gt = motion_gt.to(device)- To simulate the noisy depth camera observations, we generate some random Gaussian noise with a mean equal to
motion_gt. The noises are added tomesh_batch_noisyusing theoffset_vertsPyTorch3D function:
noise = (0.1**0.5)*torch.randn(mesh_batch_noisy.verts_packed().shape).to(device)motion_gt = np.array([3, 4, 5])motion_gt = torch.as_tensor(motion_gt)noise = noise + motion_gtmesh_batch_noisy = mesh_batch_noisy.offset_verts(noise).detach()- To estimate the unknown displacement between the camera and the origin, we will formulate an optimization problem. First, we will define the
motion_estimateoptimization variable. Thetorch.zerosfunction will create an all zero PyTorch tensor. Note that we setrequires_gradtotrue. What that means is that when we run gradient backpropagation from thelossfunction, we want the gradient for this variable to be automatically computed by PyTorch for us:
motion_estimate = torch.zeros(motion_gt.shape, device = device, requires_grad=True)- Next, we are going to define a PyTorch optimizer with a learning rate of
0.1. By passing a list of variables to the optimizer, we specify the optimization variables for this optimization problem. Here, the optimization variable is themotion_estimatevariable:
optimizer = torch.optim.SGD([motion_estimate], lr=0.1, momentum=0.9)- The major optimization procedure is then shown as follows. Basically, we run the stochastic gradient descent for 200 iterations. The resulting
motion_estimateshould be very close to the ground truth after the 200 iterations.
Each optimization iteration can be divided into the following four steps:
- In the first step,
optimizer.zero_grad()resets all the gradient values from the values computed in the last iteration to zero. - In the second step, we compute the
lossfunction. Note that PyTorch retains a dynamic computational graph. In other words, all the computation procedures toward thelossfunction are recorded and will be used in the backpropagation. - In the third step,
loss.backward()computes all the gradients from thelossfunction to the optimization variables in the PyTorch optimizer. - In the fourth and final step,
optimizer.stepmoves all the optimization variables one step in the direction of decreasing thelossfunction.
In the process of computing the loss function, we randomly sample 5,000 points from the two meshes and compute their Chamfer distances. The Chamfer distance is a distance between two sets of points. We will have a more detailed discussion of this distance function in later chapters:
for i in range(0, 200): optimizer.zero_grad() current_mesh_batch = mesh_batch.offset_verts(motion_estimate.repeat(num_vertices,1)) sample_trg = sample_points_from_meshes(current_mesh_batch, 5000) sample_src = sample_points_from_meshes(mesh_batch_noisy, 5000) loss, _ = chamfer_distance(sample_trg, sample_src) loss.backward() optimizer.step() print('i = ', i, ', motion_estimation = ', motion_estimate)We can check that the optimization process here would converge to the [3,4,5] ground-truth location very quickly.
In this coding exercise, we learned how to use heterogenous mini-batches in PyTorch3D. Next, we will discuss another important concept in 3D computer vision.
Understanding transformations and rotations
Section titled “Understanding transformations and rotations”In 3D deep learning and computer vision, we usually need to work with 3D transformations, such as rotations and 3D rigid motions. PyTorch3D provides a high-level encapsulation of these transformations in its pytorch3d.transforms.Transform3d class. One advantage of the Transform3d class is that it is mini-batch based. Thus, as frequently needed in 3D deep learning, it is possible to apply a mini-batch of transformations on a mini-batch of meshes only within several lines of code. Another advantage of Transform3d is that gradient backpropagation can straightforwardly pass through Transform3d.
PyTorch3D also provides many lower-level APIs for computations in the Lie groups SO(3) and SE(3). Here, SO(3) denotes the special orthogonal group in 3D and SE(3) denotes the special Euclidean group in 3D. Informally speaking, SO(3) denotes the set of all the rotation transformations and SE(3) denotes the set of all the rigid transformations in 3D. Many low-level APIs on SE(3) and SO(3) are provided in PyTorch3D.
In 3D computer vision, multiple representations exist for rotations. One representation is the rotation matrices .
In this equation, x is a 3D vector and R is a 3 x 3 matrix. To be a rotation matrix, R needs to be an orthogonal matrix and has a determinant of +1. Thus, not all 3 x 3 matrices can be a rotation matrix. The degree of freedom for rotation matrices is 3. A 3D rotation can also be represented by a 3D vector v, where the direction of v is the rotation axis. That is, the rotation would keep v fixed and rotate all the other things around v. It is also conventional to use the amplitude of v to represent the angle of rotation.
There are various mathematical connections between the two representations of rotation. If we consider a constant speed rotation around the axis v, then the rotation matrices become a matrix-valued function of the time t, R(t). In this case, the gradient of R(t) is always a skew-symmetric matrix, in the form shown in the following equation:
Here, the following applies:
As we can see from these two equations, the skew-symmetric matrix of the gradient is uniquely determined by the vector v and vice versa. This mapping from the vector v to its skew-symmetric matrix form is usually called the hat operator. A closed-form formula from the skew-symmetric matrix gradient to the rotation matrix exists as follows. The mapping is called the exponential map for :
Certainly, the inverse mapping of the exponential map also exists:
The mapping is called the logarithmic map for .
All the hat, inverse hat, exponential, and logarithmic operations have already been implemented in PyTorch3D. PyTorch3D also implements many other frequently used 3D operations, such as quaternion operations and Euler angles.
A coding exercise for transformation and rotation
Section titled “A coding exercise for transformation and rotation”In this section, we will go through a coding exercise on how to use some of PyTorch3D’s low-level APIs:
- We begin by importing the necessary packages:
import torchfrom pytorch3d.transforms.so3 import so3_exp_map, so3_log_map, hat_inv, hat- We then define a PyTorch device using either a CPU or CUDA:
if torch.cuda.is_available(): device = torch.device("cuda:0")else: device = torch.device("cpu") print("WARNING: CPU only, this will be slow!")- Next, we will define a mini-batch of four rotations. Here, each rotation is represented by one 3D vector. The direction of the vector represents the rotation axis and the amplitude of the vector represents the angle of rotation:
log_rot = torch.zeros([4, 3], device = device)log_rot[0, 0] = 0.001log_rot[0, 1] = 0.0001log_rot[0, 2] = 0.0002log_rot[1, 0] = 0.0001log_rot[1, 1] = 0.001log_rot[1, 2] = 0.0002log_rot[2, 0] = 0.0001log_rot[2, 1] = 0.0002log_rot[2, 2] = 0.001log_rot[3, 0] = 0.001log_rot[3, 1] = 0.002log_rot[3, 2] = 0.003- The shape of
log_rotis[4, 3], where4is the batch size and each rotation is represented by a 3D vector. We can use the hat operator in PyTorch3D to convert them into the 3 x 3 skew-symmetric matrix representation as follows:
log_rot_hat = hat(log_rot)print('log_rot_hat shape = ', log_rot_hat.shape)print('log_rot_hat = ', log_rot_hat)- The backward conversion from the skew-symmetric matrix form to the 3D vector form is also possible using the
hat_invoperator:
log_rot_copy = hat_inv(log_rot_hat)print('log_rot_copy shape = ', log_rot_copy.shape)print('log_rot_copy = ', log_rot_copy)- From the gradient matrix, we can compute the rotation matrix by using the PyTorch3D
so3_exp_mapfunction:
rotation_matrices = so3_exp_map(log_rot)print('rotation_matrices = ', rotation_matrices)- The inverse conversation is
so3_log_map, which would map the rotation matrix back to the gradient matrix again:
log_rot_again = so3_log_map(rotation_matrices)print('log_rot_again = ', log_rot_again)These coding exercises show the most frequently used PyTorch3D APIs for transformations and rotations. These APIs can be very useful for real-world 3D computer vision projects.
Summary
Section titled “Summary”In this chapter, we learned about the basic concepts of rendering, rasterization, and shading, including light source models, the Lambertian shading model, and the Phong lighting model. We learned how to implement rendering, rasterization, and shading using PyTorch3D. We also learned how to change the parameters in the rendering process, such as ambient lighting, shininess, and specular colors, and how these parameters would affect the rendering results.
We then learned how to use the PyTorch optimizer. We went through a coding example, where the PyTorch optimizer was used on a PyTorch3D mini-batch. In the last part of the chapter, we learned how to use the PyTorch3D APIs for converting between the different representations or rotations and transformations. In the next chapter, we will learn some more advanced techniques for using deformable mesh models for fitting real-world 3D data.