test_rasterize_rectangle_images.py 30.4 KB
Newer Older
1
# Copyright (c) Meta Platforms, Inc. and affiliates.
Patrick Labatut's avatar
Patrick Labatut committed
2
3
4
5
# 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.
6

Jeremy Reizenstein's avatar
lint  
Jeremy Reizenstein committed
7
import re
8
9
10
11
12
13
14
import unittest
from itertools import product

import numpy as np
import torch
from PIL import Image
from pytorch3d.io import load_obj
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
15
from pytorch3d.renderer import (
16
    BlendParams,
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
17
18
19
    FoVPerspectiveCameras,
    look_at_view_transform,
    Materials,
20
21
    MeshRasterizer,
    MeshRenderer,
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
22
    PointLights,
23
24
    RasterizationSettings,
    SoftPhongShader,
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
25
    SplatterPhongShader,
26
27
    TexturesUV,
)
28
29
30
31
from pytorch3d.renderer.mesh.rasterize_meshes import (
    rasterize_meshes,
    rasterize_meshes_python,
)
32
from pytorch3d.renderer.mesh.rasterizer import Fragments
33
from pytorch3d.renderer.opengl import MeshRasterizerOpenGL
34
35
36
37
38
39
40
41
42
from pytorch3d.renderer.points import (
    AlphaCompositor,
    PointsRasterizationSettings,
    PointsRasterizer,
    PointsRenderer,
)
from pytorch3d.renderer.points.rasterize_points import (
    rasterize_points,
    rasterize_points_python,
43
)
44
45
46
47
from pytorch3d.renderer.points.rasterizer import PointFragments
from pytorch3d.structures import Meshes, Pointclouds
from pytorch3d.transforms.transform3d import Transform3d
from pytorch3d.utils import torus
48

Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
49
50
51
52
53
54
55
from .common_testing import (
    get_pytorch3d_dir,
    get_tests_dir,
    load_rgb_image,
    TestCaseMixin,
)

56
57

DEBUG = False
58
DATA_DIR = get_tests_dir() / "data"
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73

# Verts/Faces for a simple mesh with two faces.
verts0 = torch.tensor(
    [
        [-0.7, -0.70, 1.0],
        [0.0, -0.1, 1.0],
        [0.7, -0.7, 1.0],
        [-0.7, 0.1, 1.0],
        [0.0, 0.7, 1.0],
        [0.7, 0.1, 1.0],
    ],
    dtype=torch.float32,
)
faces0 = torch.tensor([[1, 0, 2], [4, 3, 5]], dtype=torch.int64)

Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
74
# Points for a simple point cloud. Get the vertices from a
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
# torus and apply rotations such that the points are no longer
# symmerical in X/Y.
torus_mesh = torus(r=0.25, R=1.0, sides=5, rings=2 * 5)
t = (
    Transform3d()
    .rotate_axis_angle(angle=90, axis="Y")
    .rotate_axis_angle(angle=45, axis="Z")
    .scale(0.3)
)
torus_points = t.transform_points(torus_mesh.verts_padded()).squeeze()


def _save_debug_image(idx, image_size, bin_size, blur):
    """
    Save a mask image from the rasterization output for debugging.
    """
    H, W = image_size
    # Save out the last image for debugging
    rgb = (idx[-1, ..., :3].cpu() > -1).squeeze()
    suffix = "square" if H == W else "non_square"
    filename = "%s_bin_size_%s_blur_%.3f_%dx%d.png"
    filename = filename % (suffix, str(bin_size), blur, H, W)
    if DEBUG:
        filename = "DEBUG_%s" % filename
        Image.fromarray((rgb.numpy() * 255).astype(np.uint8)).save(DATA_DIR / filename)


class TestRasterizeRectangleImagesErrors(TestCaseMixin, unittest.TestCase):
    def test_mesh_image_size_arg(self):
104
105
        meshes = Meshes(verts=[verts0], faces=[faces0])

Jeremy Reizenstein's avatar
lint  
Jeremy Reizenstein committed
106
        with self.assertRaisesRegex(ValueError, re.escape("tuple/list of (H, W)")):
107
108
109
110
111
112
113
            rasterize_meshes(
                meshes,
                (100, 200, 3),
                0.0001,
                faces_per_pixel=1,
            )

Jeremy Reizenstein's avatar
lint  
Jeremy Reizenstein committed
114
        with self.assertRaisesRegex(ValueError, "sizes must be greater than 0"):
115
116
117
118
119
120
121
            rasterize_meshes(
                meshes,
                (0, 10),
                0.0001,
                faces_per_pixel=1,
            )

Jeremy Reizenstein's avatar
lint  
Jeremy Reizenstein committed
122
        with self.assertRaisesRegex(ValueError, "sizes must be integers"):
123
124
125
126
127
128
129
            rasterize_meshes(
                meshes,
                (100.5, 120.5),
                0.0001,
                faces_per_pixel=1,
            )

130
131
132
    def test_points_image_size_arg(self):
        points = Pointclouds([verts0])

Jeremy Reizenstein's avatar
lint  
Jeremy Reizenstein committed
133
        with self.assertRaisesRegex(ValueError, re.escape("tuple/list of (H, W)")):
134
135
136
137
138
139
140
            rasterize_points(
                points,
                (100, 200, 3),
                0.0001,
                points_per_pixel=1,
            )

Jeremy Reizenstein's avatar
lint  
Jeremy Reizenstein committed
141
        with self.assertRaisesRegex(ValueError, "sizes must be greater than 0"):
142
143
144
145
146
147
148
            rasterize_points(
                points,
                (0, 10),
                0.0001,
                points_per_pixel=1,
            )

Jeremy Reizenstein's avatar
lint  
Jeremy Reizenstein committed
149
        with self.assertRaisesRegex(ValueError, "sizes must be integers"):
150
151
152
153
154
155
156
            rasterize_points(
                points,
                (100.5, 120.5),
                0.0001,
                points_per_pixel=1,
            )

157

158
class TestRasterizeRectangleImagesMeshes(TestCaseMixin, unittest.TestCase):
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
    @staticmethod
    def _clone_mesh(verts0, faces0, device, batch_size):
        """
        Helper function to detach and clone the verts/faces.
        This is needed in order to set up the tensors for
        gradient computation in different tests.
        """
        verts = verts0.detach().clone()
        verts.requires_grad = True
        meshes = Meshes(verts=[verts], faces=[faces0])
        meshes = meshes.to(device).extend(batch_size)
        return verts, meshes

    def _rasterize(self, meshes, image_size, bin_size, blur):
        """
        Simple wrapper around the rasterize function to return
        the fragment data.
        """
        face_idxs, zbuf, bary_coords, pix_dists = rasterize_meshes(
            meshes,
            image_size,
            blur,
            faces_per_pixel=1,
            bin_size=bin_size,
        )
        return Fragments(
            pix_to_face=face_idxs,
            zbuf=zbuf,
            bary_coords=bary_coords,
            dists=pix_dists,
        )

    @staticmethod
    def _save_debug_image(fragments, image_size, bin_size, blur):
        """
        Save a mask image from the rasterization output for debugging.
        """
        H, W = image_size
        # Save out the last image for debugging
        rgb = (fragments.pix_to_face[-1, ..., :3].cpu() > -1).squeeze()
        suffix = "square" if H == W else "non_square"
        filename = "triangle_%s_bin_size_%s_blur_%.3f_%dx%d.png"
        filename = filename % (suffix, str(bin_size), blur, H, W)
        if DEBUG:
            filename = "DEBUG_%s" % filename
            Image.fromarray((rgb.numpy() * 255).astype(np.uint8)).save(
                DATA_DIR / filename
            )

    def _check_fragments(self, frag_1, frag_2):
        """
        Helper function to check that the tensors in
        the Fragments frag_1 and frag_2 are the same.
        """
        self.assertClose(frag_1.pix_to_face, frag_2.pix_to_face)
        self.assertClose(frag_1.dists, frag_2.dists)
        self.assertClose(frag_1.bary_coords, frag_2.bary_coords)
        self.assertClose(frag_1.zbuf, frag_2.zbuf)

    def _compare_square_with_nonsq(
        self,
        image_size,
        blur,
        device,
        verts0,
        faces0,
        nonsq_fragment_gradtensor_list,
        batch_size=1,
    ):
        """
        Calculate the output from rasterizing a square image with the minimum of (H, W).
        Then compare this with the same square region in the non square image.
        The input mesh faces given by faces0 and verts0 are contained within the
        [-1, 1] range of the image so all the relevant pixels will be within the square region.

        `nonsq_fragment_gradtensor_list` is a list of fragments and verts grad tensors
        from rasterizing non square images.
        """
        # Rasterize the square version of the image
        H, W = image_size
        S = min(H, W)
        verts_square, meshes_sq = self._clone_mesh(verts0, faces0, device, batch_size)
        square_fragments = self._rasterize(
            meshes_sq, image_size=(S, S), bin_size=0, blur=blur
        )
        # Save debug image
245
        _save_debug_image(square_fragments.pix_to_face, (S, S), 0, blur)
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323

        # Extract the values in the square image which are non zero.
        square_mask = square_fragments.pix_to_face > -1
        square_dists = square_fragments.dists[square_mask]
        square_zbuf = square_fragments.zbuf[square_mask]
        square_bary = square_fragments.bary_coords[square_mask]

        # Retain gradients on the output of fragments to check
        # intermediate values with the non square outputs.
        square_fragments.dists.retain_grad()
        square_fragments.bary_coords.retain_grad()
        square_fragments.zbuf.retain_grad()

        # Calculate gradient for the square image
        torch.manual_seed(231)
        grad_zbuf = torch.randn_like(square_zbuf)
        grad_dist = torch.randn_like(square_dists)
        grad_bary = torch.randn_like(square_bary)
        loss0 = (
            (grad_dist * square_dists).sum()
            + (grad_zbuf * square_zbuf).sum()
            + (grad_bary * square_bary).sum()
        )
        loss0.backward()

        # Now compare against the non square outputs provided
        # in the nonsq_fragment_gradtensor_list list
        for fragments, grad_tensor, _name in nonsq_fragment_gradtensor_list:
            # Check that there are the same number of non zero pixels
            # in both the square and non square images.
            non_square_mask = fragments.pix_to_face > -1
            self.assertEqual(non_square_mask.sum().item(), square_mask.sum().item())

            # Check dists, zbuf and bary match the square image
            non_square_dists = fragments.dists[non_square_mask]
            non_square_zbuf = fragments.zbuf[non_square_mask]
            non_square_bary = fragments.bary_coords[non_square_mask]
            self.assertClose(square_dists, non_square_dists)
            self.assertClose(square_zbuf, non_square_zbuf)
            self.assertClose(
                square_bary,
                non_square_bary,
                atol=2e-7,
            )

            # Retain gradients to compare values with outputs from
            # square image
            fragments.dists.retain_grad()
            fragments.bary_coords.retain_grad()
            fragments.zbuf.retain_grad()
            loss1 = (
                (grad_dist * non_square_dists).sum()
                + (grad_zbuf * non_square_zbuf).sum()
                + (grad_bary * non_square_bary).sum()
            )
            loss1.sum().backward()

            # Get the non zero values in the intermediate gradients
            # and compare with the values from the square image
            non_square_grad_dists = fragments.dists.grad[non_square_mask]
            non_square_grad_bary = fragments.bary_coords.grad[non_square_mask]
            non_square_grad_zbuf = fragments.zbuf.grad[non_square_mask]

            self.assertClose(
                non_square_grad_dists,
                square_fragments.dists.grad[square_mask],
            )
            self.assertClose(
                non_square_grad_bary,
                square_fragments.bary_coords.grad[square_mask],
            )
            self.assertClose(
                non_square_grad_zbuf,
                square_fragments.zbuf.grad[square_mask],
            )

            # Finally check the gradients of the input vertices for
            # the square and non square case
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
324
            self.assertClose(verts_square.grad, grad_tensor.grad, rtol=3e-4, atol=5e-3)
325
326
327
328
329
330
331
332

    def test_gpu(self):
        """
        Test that the output of rendering non square images
        gives the same result as square images. i.e. the
        dists, zbuf, bary are all the same for the square
        region which is present in both images.
        """
333
334
335
        # Test both cases: (W > H), (H > W) as well as the case where
        # H and W are not integer multiples of each other (i.e. float aspect ratio)
        image_sizes = [(64, 128), (128, 64), (128, 256), (256, 128), (600, 1110)]
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365

        devices = ["cuda:0"]
        blurs = [0.0, 0.001]
        batch_sizes = [1, 4]
        test_cases = product(image_sizes, blurs, devices, batch_sizes)

        for image_size, blur, device, batch_size in test_cases:
            # Initialize the verts grad tensor and the meshes objects
            verts_nonsq_naive, meshes_nonsq_naive = self._clone_mesh(
                verts0, faces0, device, batch_size
            )
            verts_nonsq_binned, meshes_nonsq_binned = self._clone_mesh(
                verts0, faces0, device, batch_size
            )

            # Get the outputs for both naive and coarse to fine rasterization
            fragments_naive = self._rasterize(
                meshes_nonsq_naive,
                image_size,
                blur=blur,
                bin_size=0,
            )
            fragments_binned = self._rasterize(
                meshes_nonsq_binned,
                image_size,
                blur=blur,
                bin_size=None,
            )

            # Save out debug images if needed
366
367
            _save_debug_image(fragments_naive.pix_to_face, image_size, 0, blur)
            _save_debug_image(fragments_binned.pix_to_face, image_size, None, blur)
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401

            # Check naive and binned fragments give the same outputs
            self._check_fragments(fragments_naive, fragments_binned)

            # Here we want to compare the square image with the naive and the
            # coarse to fine methods outputs
            nonsq_fragment_gradtensor_list = [
                (fragments_naive, verts_nonsq_naive, "naive"),
                (fragments_binned, verts_nonsq_binned, "coarse-to-fine"),
            ]

            self._compare_square_with_nonsq(
                image_size,
                blur,
                device,
                verts0,
                faces0,
                nonsq_fragment_gradtensor_list,
                batch_size,
            )

    def test_cpu(self):
        """
        Test that the output of rendering non square images
        gives the same result as square images. i.e. the
        dists, zbuf, bary are all the same for the square
        region which is present in both images.

        In this test we compare between the naive C++ implementation
        and the naive python implementation as the Coarse/Fine
        method is not fully implemented in C++
        """
        # Test both when (W > H) and (H > W).
        # Using smaller image sizes here as the Python rasterizer is really slow.
402
        image_sizes = [(32, 64), (64, 32), (60, 110)]
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
        devices = ["cpu"]
        blurs = [0.0, 0.001]
        batch_sizes = [1]
        test_cases = product(image_sizes, blurs, devices, batch_sizes)

        for image_size, blur, device, batch_size in test_cases:
            # Initialize the verts grad tensor and the meshes objects
            verts_nonsq_naive, meshes_nonsq_naive = self._clone_mesh(
                verts0, faces0, device, batch_size
            )
            verts_nonsq_python, meshes_nonsq_python = self._clone_mesh(
                verts0, faces0, device, batch_size
            )

            # Compare Naive CPU with Python as Coarse/Fine rasteriztation
            # is not implemented for CPU
            fragments_naive = self._rasterize(
                meshes_nonsq_naive, image_size, bin_size=0, blur=blur
            )
            face_idxs, zbuf, bary_coords, pix_dists = rasterize_meshes_python(
                meshes_nonsq_python,
                image_size,
                blur,
                faces_per_pixel=1,
            )
            fragments_python = Fragments(
                pix_to_face=face_idxs,
                zbuf=zbuf,
                bary_coords=bary_coords,
                dists=pix_dists,
            )

            # Save debug images if DEBUG is set to true at the top of the file.
436
437
            _save_debug_image(fragments_naive.pix_to_face, image_size, 0, blur)
            _save_debug_image(fragments_python.pix_to_face, image_size, "python", blur)
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454

            # List of non square outputs to compare with the square output
            nonsq_fragment_gradtensor_list = [
                (fragments_naive, verts_nonsq_naive, "naive"),
                (fragments_python, verts_nonsq_python, "python"),
            ]
            self._compare_square_with_nonsq(
                image_size,
                blur,
                device,
                verts0,
                faces0,
                nonsq_fragment_gradtensor_list,
                batch_size,
            )

    def test_render_cow(self):
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
455
456
457
458
459
460
        self._render_cow(MeshRasterizer)

    def test_render_cow_opengl(self):
        self._render_cow(MeshRasterizerOpenGL)

    def _render_cow(self, rasterizer_type):
461
462
463
464
        """
        Test a larger textured mesh is rendered correctly in a non square image.
        """
        device = torch.device("cuda:0")
465
        obj_dir = get_pytorch3d_dir() / "docs/tutorials/data"
466
467
468
469
470
471
472
473
474
475
476
477
478
479
        obj_filename = obj_dir / "cow_mesh/cow.obj"

        # Load mesh + texture
        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)

        # Init rasterizer settings
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
480
        R, T = look_at_view_transform(1.2, 0, 90)
481
482
483
        cameras = FoVPerspectiveCameras(device=device, R=R, T=T)

        raster_settings = RasterizationSettings(
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
484
            image_size=(500, 800), blur_radius=0.0, faces_per_pixel=1
485
486
487
488
489
490
491
492
        )

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

        # Init renderer
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
493
494
495
496
497
498
499
500
        rasterizer = rasterizer_type(cameras=cameras, raster_settings=raster_settings)
        if rasterizer_type == MeshRasterizer:
            blend_params = BlendParams(
                sigma=1e-1,
                gamma=1e-4,
                background_color=torch.tensor([1.0, 1.0, 1.0], device=device),
            )
            shader = SoftPhongShader(
501
502
503
504
                lights=lights,
                cameras=cameras,
                materials=materials,
                blend_params=blend_params,
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
505
506
507
508
509
510
511
512
513
514
515
516
517
518
            )
        else:
            blend_params = BlendParams(
                sigma=0.5,
                background_color=torch.tensor([1.0, 1.0, 1.0], device=device),
            )
            shader = SplatterPhongShader(
                lights=lights,
                cameras=cameras,
                materials=materials,
                blend_params=blend_params,
            )

        renderer = MeshRenderer(rasterizer=rasterizer, shader=shader)
519
520

        # Load reference image
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
521
522
523
        image_ref = load_rgb_image(
            f"test_cow_image_rectangle_{rasterizer_type.__name__}.png", DATA_DIR
        )
524
525

        for bin_size in [0, None]:
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
526
527
528
            if bin_size == 0 and rasterizer_type == MeshRasterizerOpenGL:
                continue

529
530
531
532
533
534
535
            # 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()

            if DEBUG:
                Image.fromarray((rgb.numpy() * 255).astype(np.uint8)).save(
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
536
537
                    DATA_DIR
                    / f"DEBUG_cow_image_rectangle_{rasterizer_type.__name__}.png"
538
539
540
541
542
                )

            # NOTE some pixels can be flaky
            cond1 = torch.allclose(rgb, image_ref, atol=0.05)
            self.assertTrue(cond1)
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
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
585
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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680


class TestRasterizeRectangleImagesPointclouds(TestCaseMixin, unittest.TestCase):
    @staticmethod
    def _clone_pointcloud(verts0, device, batch_size):
        """
        Helper function to detach and clone the verts.
        This is needed in order to set up the tensors for
        gradient computation in different tests.
        """
        verts = verts0.detach().clone()
        verts.requires_grad = True
        pointclouds = Pointclouds(points=[verts])
        pointclouds = pointclouds.to(device).extend(batch_size)
        return verts, pointclouds

    def _rasterize(self, meshes, image_size, bin_size, blur):
        """
        Simple wrapper around the rasterize function to return
        the fragment data.
        """
        idxs, zbuf, dists = rasterize_points(
            meshes,
            image_size,
            blur,
            points_per_pixel=1,
            bin_size=bin_size,
        )
        return PointFragments(
            idx=idxs,
            zbuf=zbuf,
            dists=dists,
        )

    def _check_fragments(self, frag_1, frag_2):
        """
        Helper function to check that the tensors in
        the Fragments frag_1 and frag_2 are the same.
        """
        self.assertClose(frag_1.idx, frag_2.idx)
        self.assertClose(frag_1.dists, frag_2.dists)
        self.assertClose(frag_1.zbuf, frag_2.zbuf)

    def _compare_square_with_nonsq(
        self,
        image_size,
        blur,
        device,
        points,
        nonsq_fragment_gradtensor_list,
        batch_size=1,
    ):
        """
        Calculate the output from rasterizing a square image with the minimum of (H, W).
        Then compare this with the same square region in the non square image.
        The input points are contained within the [-1, 1] range of the image
        so all the relevant pixels will be within the square region.

        `nonsq_fragment_gradtensor_list` is a list of fragments and verts grad tensors
        from rasterizing non square images.
        """
        # Rasterize the square version of the image
        H, W = image_size
        S = min(H, W)
        points_square, pointclouds_sq = self._clone_pointcloud(
            points, device, batch_size
        )
        square_fragments = self._rasterize(
            pointclouds_sq, image_size=(S, S), bin_size=0, blur=blur
        )
        # Save debug image
        _save_debug_image(square_fragments.idx, (S, S), 0, blur)

        # Extract the values in the square image which are non zero.
        square_mask = square_fragments.idx > -1
        square_dists = square_fragments.dists[square_mask]
        square_zbuf = square_fragments.zbuf[square_mask]

        # Retain gradients on the output of fragments to check
        # intermediate values with the non square outputs.
        square_fragments.dists.retain_grad()
        square_fragments.zbuf.retain_grad()

        # Calculate gradient for the square image
        torch.manual_seed(231)
        grad_zbuf = torch.randn_like(square_zbuf)
        grad_dist = torch.randn_like(square_dists)
        loss0 = (grad_dist * square_dists).sum() + (grad_zbuf * square_zbuf).sum()
        loss0.backward()

        # Now compare against the non square outputs provided
        # in the nonsq_fragment_gradtensor_list list
        for fragments, grad_tensor, _name in nonsq_fragment_gradtensor_list:
            # Check that there are the same number of non zero pixels
            # in both the square and non square images.
            non_square_mask = fragments.idx > -1
            self.assertEqual(non_square_mask.sum().item(), square_mask.sum().item())

            # Check dists, zbuf and bary match the square image
            non_square_dists = fragments.dists[non_square_mask]
            non_square_zbuf = fragments.zbuf[non_square_mask]
            self.assertClose(square_dists, non_square_dists)
            self.assertClose(square_zbuf, non_square_zbuf)

            # Retain gradients to compare values with outputs from
            # square image
            fragments.dists.retain_grad()
            fragments.zbuf.retain_grad()
            loss1 = (grad_dist * non_square_dists).sum() + (
                grad_zbuf * non_square_zbuf
            ).sum()
            loss1.sum().backward()

            # Get the non zero values in the intermediate gradients
            # and compare with the values from the square image
            non_square_grad_dists = fragments.dists.grad[non_square_mask]
            non_square_grad_zbuf = fragments.zbuf.grad[non_square_mask]

            self.assertClose(
                non_square_grad_dists,
                square_fragments.dists.grad[square_mask],
            )
            self.assertClose(
                non_square_grad_zbuf,
                square_fragments.zbuf.grad[square_mask],
            )

            # Finally check the gradients of the input vertices for
            # the square and non square case
            self.assertClose(points_square.grad, grad_tensor.grad, rtol=2e-4)

    def test_gpu(self):
        """
        Test that the output of rendering non square images
        gives the same result as square images. i.e. the
        dists, zbuf, idx are all the same for the square
        region which is present in both images.
        """
681
682
683
        # Test both cases: (W > H), (H > W) as well as the case where
        # H and W are not integer multiples of each other (i.e. float aspect ratio)
        image_sizes = [(64, 128), (128, 64), (128, 256), (256, 128), (600, 1110)]
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748

        devices = ["cuda:0"]
        blurs = [5e-2]
        batch_sizes = [1, 4]
        test_cases = product(image_sizes, blurs, devices, batch_sizes)

        for image_size, blur, device, batch_size in test_cases:
            # Initialize the verts grad tensor and the meshes objects
            verts_nonsq_naive, pointcloud_nonsq_naive = self._clone_pointcloud(
                torus_points, device, batch_size
            )
            verts_nonsq_binned, pointcloud_nonsq_binned = self._clone_pointcloud(
                torus_points, device, batch_size
            )

            # Get the outputs for both naive and coarse to fine rasterization
            fragments_naive = self._rasterize(
                pointcloud_nonsq_naive,
                image_size,
                blur=blur,
                bin_size=0,
            )
            fragments_binned = self._rasterize(
                pointcloud_nonsq_binned,
                image_size,
                blur=blur,
                bin_size=None,
            )

            # Save out debug images if needed
            _save_debug_image(fragments_naive.idx, image_size, 0, blur)
            _save_debug_image(fragments_binned.idx, image_size, None, blur)

            # Check naive and binned fragments give the same outputs
            self._check_fragments(fragments_naive, fragments_binned)

            # Here we want to compare the square image with the naive and the
            # coarse to fine methods outputs
            nonsq_fragment_gradtensor_list = [
                (fragments_naive, verts_nonsq_naive, "naive"),
                (fragments_binned, verts_nonsq_binned, "coarse-to-fine"),
            ]

            self._compare_square_with_nonsq(
                image_size,
                blur,
                device,
                torus_points,
                nonsq_fragment_gradtensor_list,
                batch_size,
            )

    def test_cpu(self):
        """
        Test that the output of rendering non square images
        gives the same result as square images. i.e. the
        dists, zbuf, idx are all the same for the square
        region which is present in both images.

        In this test we compare between the naive C++ implementation
        and the naive python implementation as the Coarse/Fine
        method is not fully implemented in C++
        """
        # Test both when (W > H) and (H > W).
        # Using smaller image sizes here as the Python rasterizer is really slow.
749
        image_sizes = [(32, 64), (64, 32), (60, 110)]
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
        devices = ["cpu"]
        blurs = [5e-2]
        batch_sizes = [1]
        test_cases = product(image_sizes, blurs, devices, batch_sizes)

        for image_size, blur, device, batch_size in test_cases:
            # Initialize the verts grad tensor and the meshes objects
            verts_nonsq_naive, pointcloud_nonsq_naive = self._clone_pointcloud(
                torus_points, device, batch_size
            )
            verts_nonsq_python, pointcloud_nonsq_python = self._clone_pointcloud(
                torus_points, device, batch_size
            )

            # Compare Naive CPU with Python as Coarse/Fine rasteriztation
            # is not implemented for CPU
            fragments_naive = self._rasterize(
                pointcloud_nonsq_naive, image_size, bin_size=0, blur=blur
            )
            idxs, zbuf, pix_dists = rasterize_points_python(
                pointcloud_nonsq_python,
                image_size,
                blur,
                points_per_pixel=1,
            )
            fragments_python = PointFragments(
                idx=idxs,
                zbuf=zbuf,
                dists=pix_dists,
            )

            # Save debug images if DEBUG is set to true at the top of the file.
            _save_debug_image(fragments_naive.idx, image_size, 0, blur)
            _save_debug_image(fragments_python.idx, image_size, "python", blur)

            # List of non square outputs to compare with the square output
            nonsq_fragment_gradtensor_list = [
                (fragments_naive, verts_nonsq_naive, "naive"),
                (fragments_python, verts_nonsq_python, "python"),
            ]
            self._compare_square_with_nonsq(
                image_size,
                blur,
                device,
                torus_points,
                nonsq_fragment_gradtensor_list,
                batch_size,
            )

    def test_render_pointcloud(self):
        """
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
801
        Test a textured point cloud is rendered correctly in a non square image.
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
        """
        device = torch.device("cuda:0")
        pointclouds = Pointclouds(
            points=[torus_points * 2.0],
            features=torch.ones_like(torus_points[None, ...]),
        ).to(device)
        R, T = look_at_view_transform(2.7, 0.0, 0.0)
        cameras = FoVPerspectiveCameras(device=device, R=R, T=T)
        raster_settings = PointsRasterizationSettings(
            image_size=(512, 1024), radius=5e-2, points_per_pixel=1
        )
        rasterizer = PointsRasterizer(cameras=cameras, raster_settings=raster_settings)
        compositor = AlphaCompositor()
        renderer = PointsRenderer(rasterizer=rasterizer, compositor=compositor)

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

        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(pointclouds)
            rgb = images[0, ..., :3].squeeze().cpu()

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

            # NOTE some pixels can be flaky
            cond1 = torch.allclose(rgb, image_ref, atol=0.05)
            self.assertTrue(cond1)