Skip to content
ImagineWorld

Fitting Deformable Mesh Models to Raw Point Clouds

node_idnode-book_3d-deep-learning-with-python_chapter-03-fitting-deformable-mesh-models-to-raw-point-clouds
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num3
chapter_titleFitting Deformable Mesh Models to Raw Point Clouds
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Fitting Deformable Mesh Models to Raw Point Clouds

Section titled “Fitting Deformable Mesh Models to Raw Point Clouds”

In this chapter, we are going to discuss a project for using deformable mesh models for fitting raw point cloud observations potentially coming from a raw depth camera sensing result. Raw point cloud observations from depth cameras are usually in the format of point clouds without any information on how these points are connected; that is, the point clouds don’t contain information about how surfaces can be formed from the points. This is contrary to a mesh, where the list of faces defined by the mesh shows us how the surfaces are. Such information on how points can be gathered into surfaces is important for downstream postprocessing, such as denoising and object detection. For example, if one point is isolated without any connection to any of the other points, then the point may likely be a false detection by the sensor.

Thus, reconstructing the surface information from point clouds is usually a standard step in 3D data processing pipelines. There exists a large body of prior-art literature on 3D surface reconstruction from points clouds, such as Poisson reconstruction. Using deformable mesh models for surface reconstruction is also among the frequently used methods. The method of fitting deformable mesh models for point clouds discussed in this chapter is a practical and simple baseline method. The method presented in this chapter is based on PyTorch optimization. The method is another perfect demonstration of how optimization using PyTorch works. We will explain the optimization in reasonable detail, so that you can further improve your understanding of PyTorch optimization.

Loss functions are very important in most deep learning algorithms. Here, we will also discuss which loss functions we should use and the loss functions that have conventionally been contained in PyTorch3D. Luckily, many well-known loss functions have been implemented in many modern 3D deep learning frameworks and libraries, such as PyTorch3D. In this chapter, we are going to learn about many such loss functions.

In this chapter, we’re going to cover the following main topics:

  • Fitting meshes to point clouds – the problem
  • Formulating the mesh model fitting problem as an optimization problem
  • Loss functions for regularization
  • Implementing the mesh fitting with PyTorch3D

To run the example code snippets in this book, you should ideally have a computer that has a GPU. However, running the code snippets with only CPUs is not impossible. The recommended computer configuration includes the following:

  • A GPU, for example, the GTX series or RTX series, with at least 8 GB of memory
  • Python 3
  • The PyTorch and PyTorch3D libraries

The code snippets with this chapter can be found at https://github.com/PacktPublishing/3D-Deep-Learning-with-Python.

Fitting meshes to point clouds – the problem

Section titled “Fitting meshes to point clouds – the problem”

Real-world depth cameras, such as LiDAR, time-of-flight cameras, and stereo vision cameras, usually output either depth images or point clouds. For example, in the case of time-of-flight cameras, a modulated light ray is projected from the camera to the world, and the depth at each pixel is measured from the phase of the reflected light rays received at the pixel. Thus, at each pixel, we can usually get one depth measurement and one reflected light amplitude measurement. However, other than the sampled depth information, we usually do not have direct measurements of the surfaces. For example, we cannot measure the smoothness or norm of the surface directly.

Similarly, in the case of stereo vision cameras, at each time slot, the camera can take two RGB images from the camera pair at roughly the same time. The camera then estimates the depth by finding the pixel correspondences between the two images. The output is thus a depth estimation at each pixel. Again, the camera cannot give us any direct measurements of surfaces.

However, in many real-world applications, surface information is sought. For example, in robotic picking tasks, usually, we need to find regions on an object such that the robotic hands can grasp firmly. In such a scenario, it is usually desirable that the regions are large in size and reasonably flat.

There are many other scenarios in which we want to fit a (deformable) mesh model to a point cloud. For example, there are some machine vision applications where we have the mesh model for an industrial part and the point cloud measurement from the depth camera has an unknown orientation and pose. In this case, finding a fitting of the mesh model to the point cloud would recover the unknown object pose. For another example, in human face tracking, sometimes, we want to fit a deformable face mesh model to point cloud measurements, such that we can recover the identity of the human being and/or facial expressions.+

Loss functions are central concepts in almost all optimizations. Essentially, to fit a point cloud, we need to design a loss function, such that when the loss function is minimized, the mesh as the optimization variable fits to the point cloud. Actually, selecting the right loss function is usually a critical design decision in many real-world projects. Different choices of loss function usually result in significantly different system performance. The requirements for a loss function usually include at least the following properties:

  • The loss function needs to have desirable numerical properties, such as smooth, convex, without the issue of vanishing gradients, and so on
  • The loss function (and its gradients) can be easily computed; for example, they can be efficiently computed on GPUs
  • The loss function is a good measurement of model fitting; that is, minimizing the loss function results in a satisfactory mesh model fitting for the input point clouds

Other than one primary loss function in such model fitting optimization problems, we usually also need to have other loss functions for regularizing the model fitting. For example, if we have some prior knowledge that the surfaces should be smooth, then we usually need to introduce an additional regularization loss function, such that not-smooth meshes would be penalized more.

An example of point cloud measurement using a pedestrian is shown in Figure 3.1. In the later sections of this chapter, we are going to discuss a deformable mesh-based approach for fitting a mesh model to point clouds. This point cloud is in the pedestrian.ply file, which can be downloaded from the book’s GitHub page. The point cloud can be visualized by using the provided code snippet in vis_input.py.

Figure 3.1: An example of a 3D point cloud as the output of a depth camera; note that the point density is relatively low

We have discussed the problem of fitting a mesh to a point cloud. Now, let us talk about how to formulate an optimization problem.

Formulating a deformable mesh fitting problem into an optimization problem

Section titled “Formulating a deformable mesh fitting problem into an optimization problem”

In this section, we are going to talk about how to formulate the mesh fitting problem into an optimization problem. One key observation here is that object surfaces such as pedestrians can always be continuously deformed into a sphere. Thus, the approach we are going to take will start from the surface of a sphere and deform the surface to minimize a cost function.

The cost function should be chosen such that it is a good measurement of how similar the point cloud is to the mesh. Here, we choose the major cost function to be the Chamfer set distance. The Chamfer distance is defined between two sets of points as follows:

CD(S1,S2)=1S1∑x∈S1min⁡y∈S2∥x−y∥22+1S2∑y∈S2min⁡y∈S2∥x−y∥22CD(S_1,S_2) = \frac{1}{S_1}\sum_{x\in S_1}\min_{y\in S_2}\lVert x-y\rVert_2^2 + \frac{1}{S_2}\sum_{y\in S_2}\min_{y\in S_2}\lVert x-y\rVert_2^2

The Chamfer distance is symmetric and is a sum of two terms. In the first term, for each point x in the first point cloud, the closest point y in the other point cloud is found. For each such pair x and y, their distance is obtained and the distances for all the pairs are summed up. Similarly, in the second term, for each y in the second point cloud, one x is found and the distances between such x and y pairs are summed up.

Generally speaking, the Chamfer distance is the distance between two point clouds. If the two point clouds are identical, or very similar, then the Chamfer distance can be zero or very small. If the two point clouds are far away, then their Chamfer distance can be large.

In PyTorch3D, an implementation of Chamfer distance is provided in pytorch3d.loss.chamfer_distance. Not only the forward loss function calculation is provided, but we can also compute gradients for back-propagation easily using this implementation.

For fitting meshes to point clouds, we first randomly sample some points from a mesh model and then optimize the Chamfer distances between the sampled points from the mesh model and the input point cloud. The random sampling is achieved by pytorch3d.ops.sample_points_from_meshes. Again, we can compute the gradients for back-propagation from pytorch3d.ops.sample_points_from_meshes.

Now, we have a basic version of the optimization problem. However, we may still need some loss functions for the regularization of this problem. We will dive into these issues in the next section.

In the previous section, we successfully formulated the deformable mesh fitting problem into an optimization problem. However, the approach of directly optimizing this primary loss function can be problematic. The issues lie in that there may exist multiple mesh models that can be good fits to the same point cloud. These mesh models that are good fits may include some mesh models that are far away from smooth meshes.

On the other hand, we usually have prior knowledge about pedestrians. For example, the surfaces of pedestrians are usually smooth, the surface norms are smooth also. Thus, even if a non-smooth mesh is close to the input point cloud in terms of Chamfer distance, we know with a certain level of confidence that it is far away from the ground truth.

Machine learning literature has provided solutions for excluding such undesirable non-smooth solutions for several decades. The solution is called regularization. Essentially, the loss we want to optimize is chosen to be a sum of multiple loss functions. Certainly, the first term of the sum will be the primary Chamfer distance. The other terms are for penalizing surface non-smoothness and norm non-smoothness.

In the next several subsections, we are going to discuss several such loss functions, including the following:

  • Mesh Laplacian smoothing loss
  • Mesh normal consistency loss
  • Mesh edge loss

The mesh Laplacian is a discrete version of the well-known Laplace-Beltrami operator. One version (usually called uniform Laplacian) is as follows:

δi=∑i,j are edgesvi−vj\delta_i = \sum_{i,j\ are\ edges} v_i - v_j

In the preceding definition, the Laplacian at the i-th vertex is just a sum of differences, where each difference is between the coordinates of the current vertex and those of a neighboring vertex.

The Laplacian is a measurement for smoothness. If the i-th vertex and its neighbors lie all within one plane, then the Laplacian should be zero. Here, we are using a uniform version of the Laplacian, where the contribution to the sum from each neighbor is equally weighted. There are more complicated versions of Laplacians, where the preceding contributions are weighted according to various schemes. Essentially, including this loss function in the optimization would result in smoother solutions. One implementation for the mesh Laplacian smoothing loss (including multiple other versions than the uniform one) can be found at pytorch3d.loss.mesh_laplacian_smoothing. Again, gradient computations for back-propagation are enabled.

The mesh normal consistency loss is a loss function for penalizing the distances between adjacent normal vectors on the mesh. One implementation can be found at pytorch3d.loss.mesh_normal_consistency.

Mesh edge loss is for penalizing long edges in meshes. For example, in the mesh model fitting problem we consider in this chapter, we want to eventually obtain a solution, such that the obtained mesh model fits the input point cloud uniformly. In other words, each local region of the point cloud is covered by small triangles of the mesh. Otherwise, the mesh model cannot capture the fine details of slowly varying surfaces, meaning the model may not be that accurate or trustworthy. The aforementioned problem can be easily avoided by including the mesh edge loss in the objective function. The mesh edge loss is essentially a sum of all the edge lengths in the mesh. One implementation of the mesh edge loss can be found at pytorch3d.loss.mesh_edge_loss.

Now, we have covered all the concepts and mathematics for this mesh fitting problem. Next, let us dive into how the problem can be coded by using Python and PyTorch3D.

Implementing the mesh fitting with PyTorch3D

Section titled “Implementing the mesh fitting with PyTorch3D”

The input point cloud is contained in pedestrian.ply. The mesh can be visualized using the vis_input.py code snippet. The main code snippet for fitting a mesh model to the point cloud is contained in deform1.py:

  1. We will start by importing the needed packages:
import os
import sys
import torch
from pytorch3d.io import load_ply, save_ply
from pytorch3d.io import load_obj, save_obj
from pytorch3d.structures import Meshes
from pytorch3d.utils import ico_sphere
from pytorch3d.ops import sample_points_from_meshes
from pytorch3d.loss import (
chamfer_distance,
`mesh_edge_loss`,
mesh_laplacian_smoothing,
mesh_normal_consistency,
)
import numpy as np
  1. We then declare a PyTorch device. If you have GPUs, then the device would be created to use GPUs. Otherwise, the device has to use CPUs:
if torch.cuda.is_available():
device = torch.device("cuda:0")
else:
device = torch.device("cpu")
print("WARNING: CPU only, this will be slow!")
  1. We will load the point cloud from pedestrian.ply. Now, load_ply is a PyTorch3D function that loads the .ply file and outputs verts and faces. In this case, verts is a PyTorch tensor. faces is an empty PyTorch tensor because pedestrian.ply actually does not contain any faces. The to member function moves the tensors to the device; if the device uses GPUs, then verts and faces are transmitted to the GPU memories:

verts, faces = load_ply(“pedestrian.ply”)

verts = verts.to(device)
faces = faces.to(device)
  1. We then run some normalization and change the tensor shapes for later processing:
center = verts.mean(0)
verts = verts - center
scale = max(verts.abs().max(0)[0])
verts = verts / scale
verts = verts[None, :, :]
  1. In the next step, we create a mesh variable called src_mesh by using the ico_sphere PyTorch3D function. The ico_sphere function essentially creates a mesh representing roughly a sphere. This src_mesh will be our optimization variable; it will start as a sphere and then be optimized to fit the point cloud:
src_mesh = ico_sphere(4, device)
  1. In the next step, we want to define a deform_verts variable. deform_verts is a tensor of vertex displacements, where for each vertex in src_mesh, there is a vertex displacement of the three-dimensional vector. We are going to optimize deform_verts for finding the optimal deformable mesh:
src_vert = src_mesh.verts_list()
deform_verts = torch.full(src_vert[0].shape, 0.0, device=device, requires_grad=True)
  1. We define an SGD optimizer with deform_verts as the optimization variable:
optimizer = torch.optim.SGD([deform_verts], lr=1.0, momentum=0.9)
  1. We define a batch of weights for different loss functions. As we have mentioned, we need multiple loss functions, including the primary one and the regularization loss functions. The final loss will be a weighted sum of the different loss functions. Here is where we define the weights:
w_chamfer = 1.0
w_edge = 1.0
w_normal = 0.01
w_laplacian = 0.1
  1. We are then ready for going into the major optimization iterations. We are going to iterate 2,000 times for computing the loss function, computing the gradients, and going along the gradient descent directions. Each iteration starts with optimizer.zero_grad(), which will reset all the gradients, the loss variable is then computed, and the gradient back-propagation is then computed in loss.backward(); the going along the gradient descent direction is done in optimizer.step().

For us to be able to compute the Chamfer distance, during each iteration, we randomly sample some points from the deformed mesh model by using a PyTorch3D function called sample_points_from_meshes. Note that the sample_points_from_meshes function supports gradient back-propagation computations.

We also use three other loss functions for regularization, mesh_edge_loss, mesh_normal_consistency, and mesh_laplacian_smooth. The final loss variable is actually the weighted sum of the four loss functions:

for i in range(0, 2000):
print("i = ", i)
optimizer.zero_grad()
new_src_mesh = src_mesh.offset_verts(deform_verts)
sample_trg = verts
sample_src = sample_points_from_meshes(new_src_mesh, verts.shape[1])
loss_chamfer, _ = chamfer_distance(sample_trg, sample_src)
loss_edge = `mesh_edge_loss`(new_src_mesh)
loss_normal = mesh_normal_consistency(new_src_mesh)
loss_laplacian = mesh_laplacian_smoothing(new_src_mesh, method="uniform")
loss = (
loss_chamfer * w_chamfer
+ loss_edge * w_edge
+ loss_normal * w_normal
+ loss_laplacian * w_laplacian
)
loss.backward()
optimizer.step()
  1. We then extract the obtained vertices and faces from the new_src_mesh variable and then resume its original center location and scale:

final_verts, final_faces = new_src_mesh.get_mesh_verts_faces(0)

final_verts = final_verts * scale + center
  1. Finally, the obtained mesh model is saved in the deform1.ply file:
final_obj = os.path.join("./", "deform1.ply")
save_ply(final_obj, final_verts, final_faces, ascii=True)

Figure 3.2: Optimized deformed mesh model. Note that we have far more points than the original input point cloud

The obtained mesh can be visualized on your screen by using vis1.py. One screenshot of the obtained mesh is shown in Figure 3.2. Note that compared to the original input point cloud, the optimized mesh model actually contains far more points (2,500 compared with 239). The obtained surfaces seem to be smoother than the original input points also.

The experiment of not using any regularization loss functions

Section titled “The experiment of not using any regularization loss functions”

What if we don’t use any of these regularization loss functions? We run an experiment using the code in deform2.py. The only difference between the code snippet in deform2.py and the one in deform1.py is the following lines:

w_chamfer = 1.0
w_edge = 0.0
w_normal = 0.00
w_laplacian = 0.0

Note that all the weights have been set to zero, except the one for the Chamfer loss function. Essentially, we are not using any loss functions for regularization. The resulting mesh can be visualized on your screen by running vis2.py. A screenshot is shown in Figure 3.3:

Figure 3.3: Mesh obtained without using any loss functions for regularization

Note that the obtained mesh in Figure 3.3 is not smooth and is unlikely to be close to the actual ground-truth surfaces.

The experiment of using only the mesh edge loss

Section titled “The experiment of using only the mesh edge loss”

This time, we are going to use the following set of weights. The code snippet is in deform3.py:

w_chamfer = 1.0
w_edge = 1.0
w_normal = 0.00
w_laplacian = 0.0

The obtained mesh model is in deform3.ply. The mesh can be visualized on your screen by using vis3.py. A screenshot of the mesh is shown in Figure 3.4:

Figure 3.4: Obtained mesh using only the mesh_edge_loss regularization

From Figure 3.4, we can observe that the obtained mesh is much smoother than the one in Figure 3.3. However, it seems that there are some rapid changes in the surface normal. Actually, you can try out other weights on your own to see how these loss functions affect the final outcomes.

In this chapter, we talked about an approach to fitting deformable mesh models to a point cloud. As we have discussed, obtaining meshes from point clouds is usually a standard step in many 3D computer vision pipelines. The fitting approach in this chapter can be used as a simple baseline approach in practice.

From this deformable mesh fitting approach, we learned how to use PyTorch optimization. We also learned about many loss functions and their PyTorch3D implementations, including Chamfer distances, mesh edge loss, mesh Laplacian smoothing loss, and mesh normal consistency loss.

We learned when these loss functions should be used and for what purposes. We saw several experiments for showing how the loss functions affect the final outcome. You are also encouraged to run your own experiments with different combinations of loss functions and weights.

In the next chapter, we will discuss a very exciting 3D deep learning technique called differentiable rendering. Actually, we will have several differentiable-rendering-related chapters in this book. The next chapter will be the first one of these chapters.