test_render_meshes.py 23.4 KB
Newer Older
facebook-github-bot's avatar
facebook-github-bot committed
1
2
3
4
5
6
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.


"""
Sanity checks for output images from the renderer.
"""
Georgia Gkioxari's avatar
Georgia Gkioxari committed
7
import os
facebook-github-bot's avatar
facebook-github-bot committed
8
9
import unittest
from pathlib import Path
10
11

import numpy as np
facebook-github-bot's avatar
facebook-github-bot committed
12
import torch
Nikhila Ravi's avatar
Nikhila Ravi committed
13
from common_testing import TestCaseMixin, load_rgb_image
facebook-github-bot's avatar
facebook-github-bot committed
14
from PIL import Image
Nikhila Ravi's avatar
Nikhila Ravi committed
15
from pytorch3d.io import load_obj
Georgia Gkioxari's avatar
Georgia Gkioxari committed
16
17
18
19
20
21
22
from pytorch3d.renderer.cameras import (
    FoVOrthographicCameras,
    FoVPerspectiveCameras,
    OrthographicCameras,
    PerspectiveCameras,
    look_at_view_transform,
)
facebook-github-bot's avatar
facebook-github-bot committed
23
24
from pytorch3d.renderer.lighting import PointLights
from pytorch3d.renderer.materials import Materials
Nikhila Ravi's avatar
Nikhila Ravi committed
25
from pytorch3d.renderer.mesh import TexturesAtlas, TexturesUV, TexturesVertex
26
from pytorch3d.renderer.mesh.rasterizer import MeshRasterizer, RasterizationSettings
facebook-github-bot's avatar
facebook-github-bot committed
27
28
29
from pytorch3d.renderer.mesh.renderer import MeshRenderer
from pytorch3d.renderer.mesh.shader import (
    BlendParams,
30
    HardFlatShader,
Patrick Labatut's avatar
Patrick Labatut committed
31
    HardGouraudShader,
32
33
34
    HardPhongShader,
    SoftSilhouetteShader,
    TexturedSoftPhongShader,
facebook-github-bot's avatar
facebook-github-bot committed
35
)
36
from pytorch3d.structures.meshes import Meshes, join_mesh
facebook-github-bot's avatar
facebook-github-bot committed
37
38
from pytorch3d.utils.ico_sphere import ico_sphere

39

Nikhila Ravi's avatar
Nikhila Ravi committed
40
# If DEBUG=True, save out images generated in the tests for debugging.
facebook-github-bot's avatar
facebook-github-bot committed
41
42
43
44
45
# All saved images have prefix DEBUG_
DEBUG = False
DATA_DIR = Path(__file__).resolve().parent / "data"


Nikhila Ravi's avatar
Nikhila Ravi committed
46
class TestRenderMeshes(TestCaseMixin, unittest.TestCase):
facebook-github-bot's avatar
facebook-github-bot committed
47
48
    def test_simple_sphere(self, elevated_camera=False):
        """
Patrick Labatut's avatar
Patrick Labatut committed
49
        Test output of phong and gouraud shading matches a reference image using
facebook-github-bot's avatar
facebook-github-bot committed
50
51
52
53
54
55
56
57
58
59
60
61
        the default values for the light sources.

        Args:
            elevated_camera: Defines whether the camera observing the scene should
                           have an elevation of 45 degrees.
        """
        device = torch.device("cuda:0")

        # Init mesh
        sphere_mesh = ico_sphere(5, device)
        verts_padded = sphere_mesh.verts_padded()
        faces_padded = sphere_mesh.faces_padded()
Nikhila Ravi's avatar
Nikhila Ravi committed
62
63
        feats = torch.ones_like(verts_padded, device=device)
        textures = TexturesVertex(verts_features=feats)
64
        sphere_mesh = Meshes(verts=verts_padded, faces=faces_padded, textures=textures)
facebook-github-bot's avatar
facebook-github-bot committed
65
66
67

        # Init rasterizer settings
        if elevated_camera:
68
69
            # Elevated and rotated camera
            R, T = look_at_view_transform(dist=2.7, elev=45.0, azim=45.0)
Georgia Gkioxari's avatar
Georgia Gkioxari committed
70
            postfix = "_elevated_"
71
72
            # If y axis is up, the spot of light should
            # be on the bottom left of the sphere.
facebook-github-bot's avatar
facebook-github-bot committed
73
        else:
74
            # No elevation or azimuth rotation
facebook-github-bot's avatar
facebook-github-bot committed
75
            R, T = look_at_view_transform(2.7, 0.0, 0.0)
Georgia Gkioxari's avatar
Georgia Gkioxari committed
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
            postfix = "_"
        for cam_type in (
            FoVPerspectiveCameras,
            FoVOrthographicCameras,
            PerspectiveCameras,
            OrthographicCameras,
        ):
            cameras = cam_type(device=device, R=R, T=T)

            # Init shader settings
            materials = Materials(device=device)
            lights = PointLights(device=device)
            lights.location = torch.tensor([0.0, 0.0, +2.0], device=device)[None]

            raster_settings = RasterizationSettings(
                image_size=512, blur_radius=0.0, faces_per_pixel=1
            )
            rasterizer = MeshRasterizer(
                cameras=cameras, raster_settings=raster_settings
            )
            blend_params = BlendParams(1e-4, 1e-4, (0, 0, 0))

            # Test several shaders
            shaders = {
                "phong": HardPhongShader,
                "gouraud": HardGouraudShader,
                "flat": HardFlatShader,
            }
            for (name, shader_init) in shaders.items():
                shader = shader_init(
                    lights=lights,
                    cameras=cameras,
                    materials=materials,
                    blend_params=blend_params,
                )
                renderer = MeshRenderer(rasterizer=rasterizer, shader=shader)
                images = renderer(sphere_mesh)
                rgb = images[0, ..., :3].squeeze().cpu()
                filename = "simple_sphere_light_%s%s%s.png" % (
                    name,
                    postfix,
                    cam_type.__name__,
                )
facebook-github-bot's avatar
facebook-github-bot committed
119

Georgia Gkioxari's avatar
Georgia Gkioxari committed
120
121
                image_ref = load_rgb_image("test_%s" % filename, DATA_DIR)
                self.assertClose(rgb, image_ref, atol=0.05)
122

Georgia Gkioxari's avatar
Georgia Gkioxari committed
123
124
125
126
127
                if DEBUG:
                    filename = "DEBUG_%s" % filename
                    Image.fromarray((rgb.numpy() * 255).astype(np.uint8)).save(
                        DATA_DIR / filename
                    )
Nikhila Ravi's avatar
Nikhila Ravi committed
128

Georgia Gkioxari's avatar
Georgia Gkioxari committed
129
130
131
132
133
134
135
            ########################################################
            # Move the light to the +z axis in world space so it is
            # behind the sphere. Note that +Z is in, +Y up,
            # +X left for both world and camera space.
            ########################################################
            lights.location[..., 2] = -2.0
            phong_shader = HardPhongShader(
136
137
138
139
140
                lights=lights,
                cameras=cameras,
                materials=materials,
                blend_params=blend_params,
            )
Georgia Gkioxari's avatar
Georgia Gkioxari committed
141
142
            phong_renderer = MeshRenderer(rasterizer=rasterizer, shader=phong_shader)
            images = phong_renderer(sphere_mesh, lights=lights)
Nikhila Ravi's avatar
Nikhila Ravi committed
143
144
            rgb = images[0, ..., :3].squeeze().cpu()
            if DEBUG:
Georgia Gkioxari's avatar
Georgia Gkioxari committed
145
146
147
148
                filename = "DEBUG_simple_sphere_dark%s%s.png" % (
                    postfix,
                    cam_type.__name__,
                )
Nikhila Ravi's avatar
Nikhila Ravi committed
149
150
151
                Image.fromarray((rgb.numpy() * 255).astype(np.uint8)).save(
                    DATA_DIR / filename
                )
facebook-github-bot's avatar
facebook-github-bot committed
152

Georgia Gkioxari's avatar
Georgia Gkioxari committed
153
154
155
            image_ref_phong_dark = load_rgb_image(
                "test_simple_sphere_dark%s%s.png" % (postfix, cam_type.__name__),
                DATA_DIR,
facebook-github-bot's avatar
facebook-github-bot committed
156
            )
Georgia Gkioxari's avatar
Georgia Gkioxari committed
157
            self.assertClose(rgb, image_ref_phong_dark, atol=0.05)
facebook-github-bot's avatar
facebook-github-bot committed
158
159
160

    def test_simple_sphere_elevated_camera(self):
        """
Patrick Labatut's avatar
Patrick Labatut committed
161
        Test output of phong and gouraud shading matches a reference image using
facebook-github-bot's avatar
facebook-github-bot committed
162
163
164
165
166
167
        the default values for the light sources.

        The rendering is performed with a camera that has non-zero elevation.
        """
        self.test_simple_sphere(elevated_camera=True)

Georgia Gkioxari's avatar
Georgia Gkioxari committed
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
    def test_simple_sphere_screen(self):

        """
        Test output when rendering with PerspectiveCameras & OrthographicCameras
        in NDC vs screen space.
        """
        device = torch.device("cuda:0")

        # Init mesh
        sphere_mesh = ico_sphere(5, device)
        verts_padded = sphere_mesh.verts_padded()
        faces_padded = sphere_mesh.faces_padded()
        feats = torch.ones_like(verts_padded, device=device)
        textures = TexturesVertex(verts_features=feats)
        sphere_mesh = Meshes(verts=verts_padded, faces=faces_padded, textures=textures)

        R, T = look_at_view_transform(2.7, 0.0, 0.0)

        # Init shader settings
        materials = Materials(device=device)
        lights = PointLights(device=device)
        lights.location = torch.tensor([0.0, 0.0, +2.0], device=device)[None]

        raster_settings = RasterizationSettings(
            image_size=512, blur_radius=0.0, faces_per_pixel=1
        )
        for cam_type in (PerspectiveCameras, OrthographicCameras):
            cameras = cam_type(
                device=device,
                R=R,
                T=T,
                principal_point=((256.0, 256.0),),
                focal_length=((256.0, 256.0),),
                image_size=((512, 512),),
            )
            rasterizer = MeshRasterizer(
                cameras=cameras, raster_settings=raster_settings
            )
            blend_params = BlendParams(1e-4, 1e-4, (0, 0, 0))

            shader = HardPhongShader(
                lights=lights,
                cameras=cameras,
                materials=materials,
                blend_params=blend_params,
            )
            renderer = MeshRenderer(rasterizer=rasterizer, shader=shader)
            images = renderer(sphere_mesh)
            rgb = images[0, ..., :3].squeeze().cpu()
            filename = "test_simple_sphere_light_phong_%s.png" % cam_type.__name__

            image_ref = load_rgb_image(filename, DATA_DIR)
            self.assertClose(rgb, image_ref, atol=0.05)

facebook-github-bot's avatar
facebook-github-bot committed
222
223
    def test_simple_sphere_batched(self):
        """
Nikhila Ravi's avatar
Nikhila Ravi committed
224
225
        Test a mesh with vertex textures can be extended to form a batch, and
        is rendered correctly with Phong, Gouraud and Flat Shaders.
facebook-github-bot's avatar
facebook-github-bot committed
226
        """
Nikhila Ravi's avatar
Nikhila Ravi committed
227
        batch_size = 5
facebook-github-bot's avatar
facebook-github-bot committed
228
229
        device = torch.device("cuda:0")

Nikhila Ravi's avatar
Nikhila Ravi committed
230
        # Init mesh with vertex textures.
facebook-github-bot's avatar
facebook-github-bot committed
231
232
233
        sphere_meshes = ico_sphere(5, device).extend(batch_size)
        verts_padded = sphere_meshes.verts_padded()
        faces_padded = sphere_meshes.faces_padded()
Nikhila Ravi's avatar
Nikhila Ravi committed
234
235
        feats = torch.ones_like(verts_padded, device=device)
        textures = TexturesVertex(verts_features=feats)
facebook-github-bot's avatar
facebook-github-bot committed
236
237
238
239
240
241
242
243
244
        sphere_meshes = Meshes(
            verts=verts_padded, faces=faces_padded, textures=textures
        )

        # Init rasterizer settings
        dist = torch.tensor([2.7]).repeat(batch_size).to(device)
        elev = torch.zeros_like(dist)
        azim = torch.zeros_like(dist)
        R, T = look_at_view_transform(dist, elev, azim)
Georgia Gkioxari's avatar
Georgia Gkioxari committed
245
        cameras = FoVPerspectiveCameras(device=device, R=R, T=T)
facebook-github-bot's avatar
facebook-github-bot committed
246
        raster_settings = RasterizationSettings(
Nikhila Ravi's avatar
Nikhila Ravi committed
247
            image_size=512, blur_radius=0.0, faces_per_pixel=1
facebook-github-bot's avatar
facebook-github-bot committed
248
249
250
251
252
        )

        # Init shader settings
        materials = Materials(device=device)
        lights = PointLights(device=device)
253
        lights.location = torch.tensor([0.0, 0.0, +2.0], device=device)[None]
254
        blend_params = BlendParams(1e-4, 1e-4, (0, 0, 0))
facebook-github-bot's avatar
facebook-github-bot committed
255
256

        # Init renderer
257
        rasterizer = MeshRasterizer(cameras=cameras, raster_settings=raster_settings)
Nikhila Ravi's avatar
Nikhila Ravi committed
258
        shaders = {
259
            "phong": HardPhongShader,
Nikhila Ravi's avatar
Nikhila Ravi committed
260
261
262
263
            "gouraud": HardGouraudShader,
            "flat": HardFlatShader,
        }
        for (name, shader_init) in shaders.items():
264
265
266
267
268
269
            shader = shader_init(
                lights=lights,
                cameras=cameras,
                materials=materials,
                blend_params=blend_params,
            )
Nikhila Ravi's avatar
Nikhila Ravi committed
270
271
            renderer = MeshRenderer(rasterizer=rasterizer, shader=shader)
            images = renderer(sphere_meshes)
Nikhila Ravi's avatar
Nikhila Ravi committed
272
            image_ref = load_rgb_image(
Georgia Gkioxari's avatar
Georgia Gkioxari committed
273
274
                "test_simple_sphere_light_%s_%s.png" % (name, type(cameras).__name__),
                DATA_DIR,
Nikhila Ravi's avatar
Nikhila Ravi committed
275
            )
Nikhila Ravi's avatar
Nikhila Ravi committed
276
277
            for i in range(batch_size):
                rgb = images[i, ..., :3].squeeze().cpu()
Nikhila Ravi's avatar
Nikhila Ravi committed
278
                if i == 0 and DEBUG:
Georgia Gkioxari's avatar
Georgia Gkioxari committed
279
280
281
282
                    filename = "DEBUG_simple_sphere_batched_%s_%s.png" % (
                        name,
                        type(cameras).__name__,
                    )
Nikhila Ravi's avatar
Nikhila Ravi committed
283
284
285
                    Image.fromarray((rgb.numpy() * 255).astype(np.uint8)).save(
                        DATA_DIR / filename
                    )
Nikhila Ravi's avatar
Nikhila Ravi committed
286
                self.assertClose(rgb, image_ref, atol=0.05)
facebook-github-bot's avatar
facebook-github-bot committed
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301

    def test_silhouette_with_grad(self):
        """
        Test silhouette blending. Also check that gradient calculation works.
        """
        device = torch.device("cuda:0")
        sphere_mesh = ico_sphere(5, device)
        verts, faces = sphere_mesh.get_mesh_verts_faces(0)
        sphere_mesh = Meshes(verts=[verts], faces=[faces])

        blend_params = BlendParams(sigma=1e-4, gamma=1e-4)
        raster_settings = RasterizationSettings(
            image_size=512,
            blur_radius=np.log(1.0 / 1e-4 - 1.0) * blend_params.sigma,
            faces_per_pixel=80,
302
            clip_barycentric_coords=True,
facebook-github-bot's avatar
facebook-github-bot committed
303
304
305
        )

        # Init rasterizer settings
306
        R, T = look_at_view_transform(2.7, 0, 0)
Georgia Gkioxari's avatar
Georgia Gkioxari committed
307
308
309
310
311
312
313
314
315
316
317
318
319
320
        for cam_type in (
            FoVPerspectiveCameras,
            FoVOrthographicCameras,
            PerspectiveCameras,
            OrthographicCameras,
        ):
            cameras = cam_type(device=device, R=R, T=T)

            # Init renderer
            renderer = MeshRenderer(
                rasterizer=MeshRasterizer(
                    cameras=cameras, raster_settings=raster_settings
                ),
                shader=SoftSilhouetteShader(blend_params=blend_params),
facebook-github-bot's avatar
facebook-github-bot committed
321
            )
Georgia Gkioxari's avatar
Georgia Gkioxari committed
322
323
324
325
326
327
328
329
330
            images = renderer(sphere_mesh)
            alpha = images[0, ..., 3].squeeze().cpu()
            if DEBUG:
                filename = os.path.join(
                    DATA_DIR, "DEBUG_%s_silhouette.png" % (cam_type.__name__)
                )
                Image.fromarray((alpha.detach().numpy() * 255).astype(np.uint8)).save(
                    filename
                )
facebook-github-bot's avatar
facebook-github-bot committed
331

Georgia Gkioxari's avatar
Georgia Gkioxari committed
332
333
334
335
            ref_filename = "test_%s_silhouette.png" % (cam_type.__name__)
            image_ref_filename = DATA_DIR / ref_filename
            with Image.open(image_ref_filename) as raw_image_ref:
                image_ref = torch.from_numpy(np.array(raw_image_ref))
Nikhila Ravi's avatar
Nikhila Ravi committed
336

Georgia Gkioxari's avatar
Georgia Gkioxari committed
337
338
            image_ref = image_ref.to(dtype=torch.float32) / 255.0
            self.assertClose(alpha, image_ref, atol=0.055)
facebook-github-bot's avatar
facebook-github-bot committed
339

Georgia Gkioxari's avatar
Georgia Gkioxari committed
340
341
342
343
344
345
            # Check grad exist
            verts.requires_grad = True
            sphere_mesh = Meshes(verts=[verts], faces=[faces])
            images = renderer(sphere_mesh)
            images[0, ...].sum().backward()
            self.assertIsNotNone(verts.grad)
facebook-github-bot's avatar
facebook-github-bot committed
346
347
348

    def test_texture_map(self):
        """
349
350
        Test a mesh with a texture map is loaded and rendered correctly.
        The pupils in the eyes of the cow should always be looking to the left.
facebook-github-bot's avatar
facebook-github-bot committed
351
352
        """
        device = torch.device("cuda:0")
Nikhila Ravi's avatar
Nikhila Ravi committed
353
354
        obj_dir = Path(__file__).resolve().parent.parent / "docs/tutorials/data"
        obj_filename = obj_dir / "cow_mesh/cow.obj"
facebook-github-bot's avatar
facebook-github-bot committed
355
356

        # Load mesh + texture
Nikhila Ravi's avatar
Nikhila Ravi committed
357
358
359
360
361
362
363
364
365
        verts, faces, aux = load_obj(
            obj_filename, device=device, load_textures=True, texture_wrap=None
        )
        tex_map = list(aux.texture_images.values())[0]
        tex_map = tex_map[None, ...].to(faces.textures_idx.device)
        textures = TexturesUV(
            maps=tex_map, faces_uvs=[faces.textures_idx], verts_uvs=[aux.verts_uvs]
        )
        mesh = Meshes(verts=[verts], faces=[faces.verts_idx], textures=textures)
facebook-github-bot's avatar
facebook-github-bot committed
366
367

        # Init rasterizer settings
368
        R, T = look_at_view_transform(2.7, 0, 0)
Georgia Gkioxari's avatar
Georgia Gkioxari committed
369
        cameras = FoVPerspectiveCameras(device=device, R=R, T=T)
Nikhila Ravi's avatar
Nikhila Ravi committed
370

facebook-github-bot's avatar
facebook-github-bot committed
371
        raster_settings = RasterizationSettings(
Nikhila Ravi's avatar
Nikhila Ravi committed
372
            image_size=512, blur_radius=0.0, faces_per_pixel=1
facebook-github-bot's avatar
facebook-github-bot committed
373
374
375
376
377
        )

        # Init shader settings
        materials = Materials(device=device)
        lights = PointLights(device=device)
378
379
380
381

        # Place light behind the cow in world space. The front of
        # the cow is facing the -z direction.
        lights.location = torch.tensor([0.0, 0.0, 2.0], device=device)[None]
facebook-github-bot's avatar
facebook-github-bot committed
382

383
384
385
386
387
        blend_params = BlendParams(
            sigma=1e-1,
            gamma=1e-4,
            background_color=torch.tensor([1.0, 1.0, 1.0], device=device),
        )
facebook-github-bot's avatar
facebook-github-bot committed
388
389
        # Init renderer
        renderer = MeshRenderer(
390
            rasterizer=MeshRasterizer(cameras=cameras, raster_settings=raster_settings),
391
            shader=TexturedSoftPhongShader(
392
393
394
395
                lights=lights,
                cameras=cameras,
                materials=materials,
                blend_params=blend_params,
facebook-github-bot's avatar
facebook-github-bot committed
396
397
398
399
            ),
        )

        # Load reference image
Nikhila Ravi's avatar
Nikhila Ravi committed
400
        image_ref = load_rgb_image("test_texture_map_back.png", DATA_DIR)
facebook-github-bot's avatar
facebook-github-bot committed
401

Nikhila Ravi's avatar
Nikhila Ravi committed
402
403
404
405
406
        for bin_size in [0, None]:
            # Check both naive and coarse to fine produce the same output.
            renderer.rasterizer.raster_settings.bin_size = bin_size
            images = renderer(mesh)
            rgb = images[0, ..., :3].squeeze().cpu()
facebook-github-bot's avatar
facebook-github-bot committed
407

Nikhila Ravi's avatar
Nikhila Ravi committed
408
409
410
411
412
413
414
415
416
417
            if DEBUG:
                Image.fromarray((rgb.numpy() * 255).astype(np.uint8)).save(
                    DATA_DIR / "DEBUG_texture_map_back.png"
                )

            # NOTE some pixels can be flaky and will not lead to
            # `cond1` being true. Add `cond2` and check `cond1 or cond2`
            cond1 = torch.allclose(rgb, image_ref, atol=0.05)
            cond2 = ((rgb - image_ref).abs() > 0.05).sum() < 5
            self.assertTrue(cond1 or cond2)
facebook-github-bot's avatar
facebook-github-bot committed
418
419

        # Check grad exists
420
        [verts] = mesh.verts_list()
facebook-github-bot's avatar
facebook-github-bot committed
421
        verts.requires_grad = True
422
        mesh2 = Meshes(verts=[verts], faces=mesh.faces_list(), textures=mesh.textures)
423
        images = renderer(mesh2)
facebook-github-bot's avatar
facebook-github-bot committed
424
425
        images[0, ...].sum().backward()
        self.assertIsNotNone(verts.grad)
426

427
428
429
430
431
        ##########################################
        # Check rendering of the front of the cow
        ##########################################

        R, T = look_at_view_transform(2.7, 0, 180)
Georgia Gkioxari's avatar
Georgia Gkioxari committed
432
        cameras = FoVPerspectiveCameras(device=device, R=R, T=T)
433
434
435
436
437

        # Move light to the front of the cow in world space
        lights.location = torch.tensor([0.0, 0.0, -2.0], device=device)[None]

        # Load reference image
Nikhila Ravi's avatar
Nikhila Ravi committed
438
        image_ref = load_rgb_image("test_texture_map_front.png", DATA_DIR)
439

Nikhila Ravi's avatar
Nikhila Ravi committed
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
        for bin_size in [0, None]:
            # Check both naive and coarse to fine produce the same output.
            renderer.rasterizer.raster_settings.bin_size = bin_size

            images = renderer(mesh, cameras=cameras, lights=lights)
            rgb = images[0, ..., :3].squeeze().cpu()

            if DEBUG:
                Image.fromarray((rgb.numpy() * 255).astype(np.uint8)).save(
                    DATA_DIR / "DEBUG_texture_map_front.png"
                )

            # NOTE some pixels can be flaky and will not lead to
            # `cond1` being true. Add `cond2` and check `cond1 or cond2`
            cond1 = torch.allclose(rgb, image_ref, atol=0.05)
            cond2 = ((rgb - image_ref).abs() > 0.05).sum() < 5
            self.assertTrue(cond1 or cond2)
457

458
459
460
        #################################
        # Add blurring to rasterization
        #################################
461
        R, T = look_at_view_transform(2.7, 0, 180)
Georgia Gkioxari's avatar
Georgia Gkioxari committed
462
        cameras = FoVPerspectiveCameras(device=device, R=R, T=T)
463
464
465
466
467
        blend_params = BlendParams(sigma=5e-4, gamma=1e-4)
        raster_settings = RasterizationSettings(
            image_size=512,
            blur_radius=np.log(1.0 / 1e-4 - 1.0) * blend_params.sigma,
            faces_per_pixel=100,
468
            clip_barycentric_coords=True,
469
470
471
        )

        # Load reference image
Nikhila Ravi's avatar
Nikhila Ravi committed
472
        image_ref = load_rgb_image("test_blurry_textured_rendering.png", DATA_DIR)
473

Nikhila Ravi's avatar
Nikhila Ravi committed
474
475
476
477
478
479
480
481
482
        for bin_size in [0, None]:
            # Check both naive and coarse to fine produce the same output.
            renderer.rasterizer.raster_settings.bin_size = bin_size

            images = renderer(
                mesh.clone(),
                cameras=cameras,
                raster_settings=raster_settings,
                blend_params=blend_params,
483
            )
Nikhila Ravi's avatar
Nikhila Ravi committed
484
485
486
487
488
489
            rgb = images[0, ..., :3].squeeze().cpu()

            if DEBUG:
                Image.fromarray((rgb.numpy() * 255).astype(np.uint8)).save(
                    DATA_DIR / "DEBUG_blurry_textured_rendering.png"
                )
490

Nikhila Ravi's avatar
Nikhila Ravi committed
491
            self.assertClose(rgb, image_ref, atol=0.05)
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517

    def test_joined_spheres(self):
        """
        Test a list of Meshes can be joined as a single mesh and
        the single mesh is rendered correctly with Phong, Gouraud
        and Flat Shaders.
        """
        device = torch.device("cuda:0")

        # Init mesh with vertex textures.
        # Initialize a list containing two ico spheres of different sizes.
        sphere_list = [ico_sphere(3, device), ico_sphere(4, device)]
        # [(42 verts, 80 faces), (162 verts, 320 faces)]
        # The scale the vertices need to be set at to resize the spheres
        scales = [0.25, 1]
        # The distance the spheres ought to be offset horizontally to prevent overlap.
        offsets = [1.2, -0.3]
        # Initialize a list containing the adjusted sphere meshes.
        sphere_mesh_list = []
        for i in range(len(sphere_list)):
            verts = sphere_list[i].verts_padded() * scales[i]
            verts[0, :, 0] += offsets[i]
            sphere_mesh_list.append(
                Meshes(verts=verts, faces=sphere_list[i].faces_padded())
            )
        joined_sphere_mesh = join_mesh(sphere_mesh_list)
Nikhila Ravi's avatar
Nikhila Ravi committed
518
519
        joined_sphere_mesh.textures = TexturesVertex(
            verts_features=torch.ones_like(joined_sphere_mesh.verts_padded())
520
521
522
523
        )

        # Init rasterizer settings
        R, T = look_at_view_transform(2.7, 0.0, 0.0)
Georgia Gkioxari's avatar
Georgia Gkioxari committed
524
        cameras = FoVPerspectiveCameras(device=device, R=R, T=T)
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
        raster_settings = RasterizationSettings(
            image_size=512, blur_radius=0.0, faces_per_pixel=1
        )

        # Init shader settings
        materials = Materials(device=device)
        lights = PointLights(device=device)
        lights.location = torch.tensor([0.0, 0.0, +2.0], device=device)[None]
        blend_params = BlendParams(1e-4, 1e-4, (0, 0, 0))

        # Init renderer
        rasterizer = MeshRasterizer(cameras=cameras, raster_settings=raster_settings)
        shaders = {
            "phong": HardPhongShader,
            "gouraud": HardGouraudShader,
            "flat": HardFlatShader,
        }
        for (name, shader_init) in shaders.items():
            shader = shader_init(
                lights=lights,
                cameras=cameras,
                materials=materials,
                blend_params=blend_params,
            )
            renderer = MeshRenderer(rasterizer=rasterizer, shader=shader)
            image = renderer(joined_sphere_mesh)
            rgb = image[..., :3].squeeze().cpu()
            if DEBUG:
                file_name = "DEBUG_joined_spheres_%s.png" % name
                Image.fromarray((rgb.numpy() * 255).astype(np.uint8)).save(
                    DATA_DIR / file_name
                )
            image_ref = load_rgb_image("test_joined_spheres_%s.png" % name, DATA_DIR)
            self.assertClose(rgb, image_ref, atol=0.05)
Nikhila Ravi's avatar
Nikhila Ravi committed
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584

    def test_texture_map_atlas(self):
        """
        Test a mesh with a texture map as a per face atlas is loaded and rendered correctly.
        """
        device = torch.device("cuda:0")
        obj_dir = Path(__file__).resolve().parent.parent / "docs/tutorials/data"
        obj_filename = obj_dir / "cow_mesh/cow.obj"

        # Load mesh and texture as a per face texture atlas.
        verts, faces, aux = load_obj(
            obj_filename,
            device=device,
            load_textures=True,
            create_texture_atlas=True,
            texture_atlas_size=8,
            texture_wrap=None,
        )
        mesh = Meshes(
            verts=[verts],
            faces=[faces.verts_idx],
            textures=TexturesAtlas(atlas=[aux.texture_atlas]),
        )

        # Init rasterizer settings
        R, T = look_at_view_transform(2.7, 0, 0)
Georgia Gkioxari's avatar
Georgia Gkioxari committed
585
        cameras = FoVPerspectiveCameras(device=device, R=R, T=T)
Nikhila Ravi's avatar
Nikhila Ravi committed
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616

        raster_settings = RasterizationSettings(
            image_size=512, blur_radius=0.0, faces_per_pixel=1, cull_backfaces=True
        )

        # Init shader settings
        materials = Materials(device=device, specular_color=((0, 0, 0),), shininess=0.0)
        lights = PointLights(device=device)

        # Place light behind the cow in world space. The front of
        # the cow is facing the -z direction.
        lights.location = torch.tensor([0.0, 0.0, 2.0], device=device)[None]

        # The HardPhongShader can be used directly with atlas textures.
        renderer = MeshRenderer(
            rasterizer=MeshRasterizer(cameras=cameras, raster_settings=raster_settings),
            shader=HardPhongShader(lights=lights, cameras=cameras, materials=materials),
        )

        images = renderer(mesh)
        rgb = images[0, ..., :3].squeeze().cpu()

        # Load reference image
        image_ref = load_rgb_image("test_texture_atlas_8x8_back.png", DATA_DIR)

        if DEBUG:
            Image.fromarray((rgb.numpy() * 255).astype(np.uint8)).save(
                DATA_DIR / "DEBUG_texture_atlas_8x8_back.png"
            )

        self.assertClose(rgb, image_ref, atol=0.05)