Skip to content

Commit 06cdc31

Browse files
eyoung2015facebook-github-bot
authored andcommitted
PyTorch3D - Avoid flip in TexturesAtlas
Summary: Performance improvement: Use torch.lerp to map uv coordinates to the range needed for grid_sample (i.e. map [0, 1] to [-1, 1] and invert the y-axis) Reviewed By: bottler Differential Revision: D51961728 fbshipit-source-id: db19a5e3f482e9af7b96b20f88a1e5d0076dac43
1 parent 94da884 commit 06cdc31

File tree

2 files changed

+13
-5
lines changed

2 files changed

+13
-5
lines changed

pytorch3d/renderer/mesh/textures.py

+12-4
Original file line numberDiff line numberDiff line change
@@ -995,9 +995,13 @@ def sample_textures(self, fragments, **kwargs) -> torch.Tensor:
995995
# is the left-top pixel of input, and values x = 1, y = 1 is the
996996
# right-bottom pixel of input.
997997

998-
pixel_uvs = pixel_uvs * 2.0 - 1.0
998+
# map to a range of [-1, 1] and flip the y axis
999+
pixel_uvs = torch.lerp(
1000+
pixel_uvs.new_tensor([-1.0, 1.0]),
1001+
pixel_uvs.new_tensor([1.0, -1.0]),
1002+
pixel_uvs,
1003+
)
9991004

1000-
texture_maps = torch.flip(texture_maps, [2]) # flip y axis of the texture map
10011005
if texture_maps.device != pixel_uvs.device:
10021006
texture_maps = texture_maps.to(pixel_uvs.device)
10031007
texels = F.grid_sample(
@@ -1035,8 +1039,12 @@ def faces_verts_textures_packed(self) -> torch.Tensor:
10351039
texture_maps = self.maps_padded() # NxHxWxC
10361040
texture_maps = texture_maps.permute(0, 3, 1, 2) # NxCxHxW
10371041

1038-
faces_verts_uvs = faces_verts_uvs * 2.0 - 1.0
1039-
texture_maps = torch.flip(texture_maps, [2]) # flip y axis of the texture map
1042+
# map to a range of [-1, 1] and flip the y axis
1043+
faces_verts_uvs = torch.lerp(
1044+
faces_verts_uvs.new_tensor([-1.0, 1.0]),
1045+
faces_verts_uvs.new_tensor([1.0, -1.0]),
1046+
faces_verts_uvs,
1047+
)
10401048

10411049
textures = F.grid_sample(
10421050
texture_maps,

tests/test_render_meshes.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -932,7 +932,7 @@ def _join_uvs(self, rasterizer_type):
932932
)
933933
).save(DATA_DIR / f"DEBUG_test_joinuvs{i}_map3.png")
934934

935-
self.assertClose(output, merged)
935+
self.assertClose(output, merged, atol=0.005)
936936
self.assertClose(output, image_ref, atol=0.005)
937937
self.assertClose(mesh.textures.maps_padded()[0].cpu(), map_ref, atol=0.05)
938938

0 commit comments

Comments
 (0)