forked from facebookresearch/pytorch3d
-
Notifications
You must be signed in to change notification settings - Fork 2
/
sample_points_from_meshes.py
292 lines (247 loc) · 10.8 KB
/
sample_points_from_meshes.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
"""
This module implements utility functions for sampling points from
batches of meshes.
"""
import sys
from typing import Tuple, Union
import torch
from pytorch3d.ops.mesh_face_areas_normals import mesh_face_areas_normals
from pytorch3d.ops.packed_to_padded import packed_to_padded
from pytorch3d.renderer.mesh.rasterizer import Fragments as MeshFragments
from pytorch3d.structures import Meshes
def sample_points_from_meshes(
meshes,
num_samples: int = 10000,
return_normals: bool = False,
return_textures: bool = False,
return_mappers: bool = False,
) -> Union[
torch.Tensor,
Tuple[torch.Tensor, torch.Tensor],
Tuple[torch.Tensor, torch.Tensor, torch.Tensor],
]:
"""
Convert a batch of meshes to a batch of pointclouds by uniformly sampling
points on the surface of the mesh with probability proportional to the
face area.
Args:
meshes: A Meshes object with a batch of N meshes.
num_samples: Integer giving the number of point samples per mesh.
return_normals: If True, return normals for the sampled points.
return_textures: If True, return textures for the sampled points.
return_mappers: If True, return a mapping of each point to its origin face.
Returns:
4-element tuple containing
- **samples**: FloatTensor of shape (N, num_samples, 3) giving the
coordinates of sampled points for each mesh in the batch. For empty
meshes the corresponding row in the samples array will be filled with 0.
- **normals**: FloatTensor of shape (N, num_samples, 3) giving a normal vector
to each sampled point. Only returned if return_normals is True.
For empty meshes the corresponding row in the normals array will
be filled with 0.
- **textures**: FloatTensor of shape (N, num_samples, C) giving a C-dimensional
texture vector to each sampled point. Only returned if return_textures is True.
For empty meshes the corresponding row in the textures array will
be filled with 0.
- **mappers**: IntTensor of shape (N, num_samples) providing a point to face
mapping for each point's origin face in the sample.
Note that in a future releases, we will replace the 4-element tuple output
with a `Pointclouds` datastructure, as follows
.. code-block:: python
Pointclouds(samples, normals=normals, features=textures)
"""
if meshes.isempty():
raise ValueError("Meshes are empty.")
# initialize all return values
samples, normals, textures, mappers = None, None, None, None
verts = meshes.verts_packed()
if not torch.isfinite(verts).all():
raise ValueError("Meshes contain nan or inf.")
if return_textures and meshes.textures is None:
raise ValueError("Meshes do not contain textures.")
faces = meshes.faces_packed()
mesh_to_face = meshes.mesh_to_faces_packed_first_idx()
num_valid_meshes = torch.sum(meshes.valid) # Non empty meshes.
# Only compute samples for non empty meshes
with torch.no_grad():
areas, _ = mesh_face_areas_normals(verts, faces) # Face areas can be zero.
max_faces = meshes.num_faces_per_mesh().max().item()
areas_padded = packed_to_padded(
areas, mesh_to_face[meshes.valid], max_faces
) # (N, F)
# TODO (gkioxari) Confirm multinomial bug is not present with real data.
sample_face_idxs = areas_padded.multinomial(
num_samples, replacement=True
) # (N, num_samples)
if return_mappers:
# for each mesh, a mapping of each point to its origin face by the face index
mappers = sample_face_idxs.clone()
sample_face_idxs += mesh_to_face[meshes.valid].view(num_valid_meshes, 1)
(samples, (v0, v1, v2), (w0, w1, w2)) = _sample_points(
meshes,
num_samples,
sample_face_idxs,
verts,
faces,
)
if return_normals:
normals = _sample_normals(meshes, num_samples, sample_face_idxs, v0, v1, v2)
if return_textures:
textures = _sample_textures(meshes, num_samples, sample_face_idxs, w0, w1, w2)
# return
# TODO(gkioxari) consider returning a Pointclouds instance [breaking]
if return_mappers:
# return a 4-element tuple
return samples, normals, textures, mappers
if return_normals and return_textures:
# pyre-fixme[61]: `normals` may not be initialized here.
# pyre-fixme[61]: `textures` may not be initialized here.
return samples, normals, textures
if return_normals: # return_textures is False
# pyre-fixme[61]: `normals` may not be initialized here.
return samples, normals
if return_textures: # return_normals is False
# pyre-fixme[61]: `textures` may not be initialized here.
return samples, textures
return samples
def _rand_barycentric_coords(
size1, size2, dtype: torch.dtype, device: torch.device
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""
Helper function to generate random barycentric coordinates which are uniformly
distributed over a triangle.
Args:
size1, size2: The number of coordinates generated will be size1*size2.
Output tensors will each be of shape (size1, size2).
dtype: Datatype to generate.
device: A torch.device object on which the outputs will be allocated.
Returns:
w0, w1, w2: Tensors of shape (size1, size2) giving random barycentric
coordinates
"""
uv = torch.rand(2, size1, size2, dtype=dtype, device=device)
u, v = uv[0], uv[1]
u_sqrt = u.sqrt()
w0 = 1.0 - u_sqrt
w1 = u_sqrt * (1.0 - v)
w2 = u_sqrt * v
return w0, w1, w2
def _sample_points(
meshes: Meshes,
num_samples: int,
sample_face_idxs: torch.Tensor,
verts: torch.Tensor,
faces: torch.Tensor,
) -> Tuple[
torch.Tensor,
Tuple[torch.Tensor, torch.Tensor, torch.Tensor],
Tuple[torch.Tensor, torch.Tensor, torch.Tensor],
]:
"""This is a helper function that re-packages the core sampling function for points.
Args:
meshes: A Meshes object to sample points from.
num_samples: Integer number of samples to generate per mesh.
num_valid_meshes: Integer value, typically the value equal to torch.sum(meshes.valid).
sample_face_idxs: An array of face indices to sample from Meshes.
verts: torch.Tensor of verts, typically meshes.verts_packed().
faces: torch.Tensor of faces, typically meshes.faces_packed().
Returns:
A 3-Tuple of sampled points array, face_verts arrays as a 3-Tuple, and
barycentric coordinate arrays as a 3-Tuple.
"""
# Initialize samples tensor with fill value 0 for empty meshes.
samples = _empty_sample(len(meshes), num_samples, verts.device, verts.dtype)
# Get the vertex coordinates of the sampled faces.
face_verts = verts[faces]
v0, v1, v2 = face_verts[:, 0], face_verts[:, 1], face_verts[:, 2]
# Randomly generate barycentric coords.
w0, w1, w2 = _rand_barycentric_coords(
torch.sum(meshes.valid), num_samples, verts.dtype, verts.device
)
# Use the barycentric coords to get a point on each sampled face.
a = v0[sample_face_idxs] # (N, num_samples, 3)
b = v1[sample_face_idxs]
c = v2[sample_face_idxs]
samples[meshes.valid] = w0[:, :, None] * a + w1[:, :, None] * b + w2[:, :, None] * c
return samples, (v0, v1, v2), (w0, w1, w2)
def _sample_normals(
meshes: Meshes,
num_samples: int,
sample_face_idxs: torch.Tensor,
v0: torch.Tensor,
v1: torch.Tensor,
v2: torch.Tensor,
) -> torch.Tensor:
"""This is a helper function that implements the core sampling function for point normals.
Args:
meshes: A Meshes object to sample points from.
num_samples: Integer number of samples to generate per mesh.
sample_face_idxs: An array of face indices to sample from Meshes.
v0, v1, v2: torch.Tensors of face_verts.
Returns:
a torch.Tensor of normals
"""
# Initialize normals tensor with fill value 0 for empty meshes.
# Normals for the sampled points are face normals computed from
# the vertices of the face in which the sampled point lies.
normals = torch.zeros(
(len(meshes), num_samples, 3), device=meshes.device, dtype=v0.dtype
)
vert_normals = (v1 - v0).cross(v2 - v1, dim=1)
vert_normals = vert_normals / vert_normals.norm(dim=1, p=2, keepdim=True).clamp(
min=sys.float_info.epsilon
)
vert_normals = vert_normals[sample_face_idxs]
normals[meshes.valid] = vert_normals
return normals
def _sample_textures(
meshes: Meshes,
num_samples: int,
sample_face_idxs: torch.Tensor,
w0: torch.Tensor,
w1: torch.Tensor,
w2: torch.Tensor,
) -> torch.Tensor:
"""This is a helper function that implements the core sampling function for point textures.
Args:
meshes: A Meshes object from which to sample textures.
num_samples: Integer value for number of texture samples.
sample_face_idxs: An array of face indices to sample from Meshes.
w0, w1, w2: Tensors giving random barycentric coordinates from _sample_points.
Returns:
A torch.Tensor of sampled textures for Meshes.
"""
# fragment data are of shape NxHxWxK. Here H=S, W=1 & K=1.
pix_to_face = sample_face_idxs.view(len(meshes), num_samples, 1, 1) # NxSx1x1
bary = torch.stack((w0, w1, w2), dim=2).unsqueeze(2).unsqueeze(2) # NxSx1x1x3
# zbuf and dists are not used in `sample_textures` so we initialize them with dummy
dummy = torch.zeros(
(len(meshes), num_samples, 1, 1), device=meshes.device, dtype=bary.dtype
) # NxSx1x1
fragments = MeshFragments(
pix_to_face=pix_to_face, zbuf=dummy, bary_coords=bary, dists=dummy
)
textures = meshes.sample_textures(fragments) # NxSx1x1xC
textures = textures[:, :, 0, 0, :] # NxSxC
return textures
def _empty_sample(
num_meshes: int, num_samples: int, device: torch.device, dtype: torch.dtype = None
) -> torch.Tensor:
"""This is a helper function that returns an empty (zeros) tensor to initialize a point sample.
Args:
num_meshes: Integer value for dim 0 of the array.
num_samples: Integer value for dim 1 of the array.
device: torch.device
dtype: Optionally specify the torch.dtype to force a specific type.
Returns:
A torch.zeros Tensor in the shape of (num_meshes x num_samples x 3)
"""
if dtype is not None:
return torch.zeros((num_meshes, num_samples, 3), device=device, dtype=dtype)
else:
return torch.zeros((num_meshes, num_samples, 3), device=device)