render_textured_meshes.ipynb 23.8 KB
Newer Older
facebook-github-bot's avatar
facebook-github-bot committed
1
2
3
4
{
 "cells": [
  {
   "cell_type": "code",
5
   "execution_count": null,
6
7
8
9
10
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "_Ip8kp4TfBLZ"
   },
facebook-github-bot's avatar
facebook-github-bot committed
11
12
   "outputs": [],
   "source": [
13
    "# Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved."
facebook-github-bot's avatar
facebook-github-bot committed
14
15
16
17
   ]
  },
  {
   "cell_type": "markdown",
18
19
20
21
   "metadata": {
    "colab_type": "text",
    "id": "kuXHJv44fBLe"
   },
facebook-github-bot's avatar
facebook-github-bot committed
22
23
24
25
26
27
28
29
30
31
32
33
34
   "source": [
    "# Render a textured mesh\n",
    "\n",
    "This tutorial shows how to:\n",
    "- load a mesh and textures from an `.obj` file. \n",
    "- set up a renderer \n",
    "- render the mesh \n",
    "- vary the rendering settings such as lighting and camera position\n",
    "- use the batching features of the pytorch3d API to render the mesh from different viewpoints"
   ]
  },
  {
   "cell_type": "markdown",
35
36
37
38
   "metadata": {
    "colab_type": "text",
    "id": "Bnj3THhzfBLf"
   },
facebook-github-bot's avatar
facebook-github-bot committed
39
   "source": [
40
41
42
43
44
45
46
47
48
49
    "## 0. Install and Import modules"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "okLalbR_g7NS"
   },
   "source": [
50
    "Ensure `torch` and `torchvision` are installed. If `pytorch3d` is not installed, install it using the following cell:"
facebook-github-bot's avatar
facebook-github-bot committed
51
52
53
54
   ]
  },
  {
   "cell_type": "code",
55
   "execution_count": null,
56
57
58
59
60
61
62
63
64
65
66
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 717
    },
    "colab_type": "code",
    "id": "musUWTglgxSB",
    "outputId": "16d1a1b2-3f7f-43ed-ca28-a4d236cc0572"
   },
   "outputs": [],
   "source": [
67
    "import os\n",
68
    "import sys\n",
69
    "import torch\n",
70
71
72
73
74
75
    "need_pytorch3d=False\n",
    "try:\n",
    "    import pytorch3d\n",
    "except ModuleNotFoundError:\n",
    "    need_pytorch3d=True\n",
    "if need_pytorch3d:\n",
76
    "    if torch.__version__.startswith(\"1.10.\") and sys.platform.startswith(\"linux\"):\n",
77
    "        # We try to install PyTorch3D via a released wheel.\n",
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
78
    "        pyt_version_str=torch.__version__.split(\"+\")[0].replace(\".\", \"\")\n",
79
80
81
    "        version_str=\"\".join([\n",
    "            f\"py3{sys.version_info.minor}_cu\",\n",
    "            torch.version.cuda.replace(\".\",\"\"),\n",
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
82
    "            f\"_pyt{pyt_version_str}\"\n",
83
84
85
86
    "        ])\n",
    "        !pip install pytorch3d -f https://dl.fbaipublicfiles.com/pytorch3d/packaging/wheels/{version_str}/download.html\n",
    "    else:\n",
    "        # We try to install PyTorch3D from source.\n",
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
87
    "        !curl -LO https://github.com/NVIDIA/cub/archive/1.10.0.tar.gz\n",
88
89
90
    "        !tar xzf 1.10.0.tar.gz\n",
    "        os.environ[\"CUB_HOME\"] = os.getcwd() + \"/cub-1.10.0\"\n",
    "        !pip install 'git+https://github.com/facebookresearch/pytorch3d.git@stable'"
91
92
93
94
   ]
  },
  {
   "cell_type": "code",
95
   "execution_count": null,
96
97
98
99
100
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "nX99zdoffBLg"
   },
facebook-github-bot's avatar
facebook-github-bot committed
101
102
103
104
105
106
107
   "outputs": [],
   "source": [
    "import os\n",
    "import torch\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "# Util function for loading meshes\n",
Nikhila Ravi's avatar
Nikhila Ravi committed
108
    "from pytorch3d.io import load_objs_as_meshes, load_obj\n",
facebook-github-bot's avatar
facebook-github-bot committed
109
110
    "\n",
    "# Data structures and functions for rendering\n",
111
    "from pytorch3d.structures import Meshes\n",
112
113
    "from pytorch3d.vis.plotly_vis import AxisArgs, plot_batch_individually, plot_scene\n",
    "from pytorch3d.vis.texture_vis import texturesuv_image_matplotlib\n",
facebook-github-bot's avatar
facebook-github-bot committed
114
115
    "from pytorch3d.renderer import (\n",
    "    look_at_view_transform,\n",
Georgia Gkioxari's avatar
Georgia Gkioxari committed
116
    "    FoVPerspectiveCameras, \n",
facebook-github-bot's avatar
facebook-github-bot committed
117
118
119
120
121
122
    "    PointLights, \n",
    "    DirectionalLights, \n",
    "    Materials, \n",
    "    RasterizationSettings, \n",
    "    MeshRenderer, \n",
    "    MeshRasterizer,  \n",
123
    "    SoftPhongShader,\n",
124
125
    "    TexturesUV,\n",
    "    TexturesVertex\n",
facebook-github-bot's avatar
facebook-github-bot committed
126
127
    ")\n",
    "\n",
128
    "# add path for demo utils functions \n",
facebook-github-bot's avatar
facebook-github-bot committed
129
130
    "import sys\n",
    "import os\n",
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
    "sys.path.append(os.path.abspath(''))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "Lxmehq6Zhrzv"
   },
   "source": [
    "If using **Google Colab**, fetch the utils file for plotting image grids:"
   ]
  },
  {
   "cell_type": "code",
146
   "execution_count": null,
147
148
149
150
151
152
153
154
155
156
157
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 204
    },
    "colab_type": "code",
    "id": "HZozr3Pmho-5",
    "outputId": "be5eb60d-5f65-4db1-cca0-44ee68c8f5fd"
   },
   "outputs": [],
   "source": [
158
    "!wget https://raw.githubusercontent.com/facebookresearch/pytorch3d/main/docs/tutorials/utils/plot_image_grid.py\n",
159
    "from plot_image_grid import image_grid"
facebook-github-bot's avatar
facebook-github-bot committed
160
161
162
163
164
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
165
166
    "colab_type": "text",
    "id": "g4B62MzYiJUM"
facebook-github-bot's avatar
facebook-github-bot committed
167
168
   },
   "source": [
169
170
171
172
173
    "OR if running **locally** uncomment and run the following cell:"
   ]
  },
  {
   "cell_type": "code",
174
   "execution_count": null,
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "paJ4Im8ahl7O"
   },
   "outputs": [],
   "source": [
    "# from utils import image_grid"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "5jGq772XfBLk"
   },
   "source": [
    "### 1. Load a mesh and texture file\n",
facebook-github-bot's avatar
facebook-github-bot committed
193
    "\n",
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
194
    "Load an `.obj` file and its associated `.mtl` file and create a **Textures** and **Meshes** object. \n",
facebook-github-bot's avatar
facebook-github-bot committed
195
    "\n",
196
    "**Meshes** is a unique datastructure provided in PyTorch3D for working with batches of meshes of different sizes. \n",
facebook-github-bot's avatar
facebook-github-bot committed
197
    "\n",
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
198
    "**TexturesUV** is an auxiliary datastructure for storing vertex uv and texture maps for meshes. \n",
facebook-github-bot's avatar
facebook-github-bot committed
199
200
201
202
    "\n",
    "**Meshes** has several class methods which are used throughout the rendering pipeline."
   ]
  },
203
204
205
206
207
208
209
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "a8eU4zo5jd_H"
   },
   "source": [
Nikhila Ravi's avatar
Nikhila Ravi committed
210
211
    "If running this notebook using **Google Colab**, run the following cell to fetch the mesh obj and texture files and save it at the path `data/cow_mesh`:\n",
    "If running locally, the data is already available at the correct path. "
212
213
   ]
  },
facebook-github-bot's avatar
facebook-github-bot committed
214
215
  {
   "cell_type": "code",
216
   "execution_count": null,
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 578
    },
    "colab_type": "code",
    "id": "tTm0cVuOjb1W",
    "outputId": "6cd7e2ec-65e1-4dcc-99e8-c347bc504f0a"
   },
   "outputs": [],
   "source": [
    "!mkdir -p data/cow_mesh\n",
    "!wget -P data/cow_mesh https://dl.fbaipublicfiles.com/pytorch3d/data/cow_mesh/cow.obj\n",
    "!wget -P data/cow_mesh https://dl.fbaipublicfiles.com/pytorch3d/data/cow_mesh/cow.mtl\n",
    "!wget -P data/cow_mesh https://dl.fbaipublicfiles.com/pytorch3d/data/cow_mesh/cow_texture.png"
   ]
  },
  {
   "cell_type": "code",
236
   "execution_count": null,
237
238
239
240
241
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "gi5Kd0GafBLl"
   },
facebook-github-bot's avatar
facebook-github-bot committed
242
243
244
   "outputs": [],
   "source": [
    "# Setup\n",
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
245
246
247
248
249
    "if torch.cuda.is_available():\n",
    "    device = torch.device(\"cuda:0\")\n",
    "    torch.cuda.set_device(device)\n",
    "else:\n",
    "    device = torch.device(\"cpu\")\n",
facebook-github-bot's avatar
facebook-github-bot committed
250
251
252
253
254
255
    "\n",
    "# Set paths\n",
    "DATA_DIR = \"./data\"\n",
    "obj_filename = os.path.join(DATA_DIR, \"cow_mesh/cow.obj\")\n",
    "\n",
    "# Load obj file\n",
256
    "mesh = load_objs_as_meshes([obj_filename], device=device)"
facebook-github-bot's avatar
facebook-github-bot committed
257
258
259
260
   ]
  },
  {
   "cell_type": "markdown",
261
262
263
264
   "metadata": {
    "colab_type": "text",
    "id": "5APAQs6-fBLp"
   },
facebook-github-bot's avatar
facebook-github-bot committed
265
266
267
268
269
270
   "source": [
    "#### Let's visualize the texture map"
   ]
  },
  {
   "cell_type": "code",
271
   "execution_count": null,
272
273
274
275
276
277
278
279
280
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 428
    },
    "colab_type": "code",
    "id": "YipUhrIHfBLq",
    "outputId": "48987b1d-5cc1-4c2a-cb3c-713d64f6a38d"
   },
281
   "outputs": [],
facebook-github-bot's avatar
facebook-github-bot committed
282
283
   "source": [
    "plt.figure(figsize=(7,7))\n",
284
    "texture_image=mesh.textures.maps_padded()\n",
facebook-github-bot's avatar
facebook-github-bot committed
285
    "plt.imshow(texture_image.squeeze().cpu().numpy())\n",
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
    "plt.axis(\"off\");"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "PyTorch3D has a built-in way to view the texture map with matplotlib along with the points on the map corresponding to vertices. There is also a method, texturesuv_image_PIL, to get a similar image which can be saved to a file."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.figure(figsize=(7,7))\n",
    "texturesuv_image_matplotlib(mesh.textures, subsample=None)\n",
    "plt.axis(\"off\");"
facebook-github-bot's avatar
facebook-github-bot committed
305
306
307
308
   ]
  },
  {
   "cell_type": "markdown",
309
310
311
312
   "metadata": {
    "colab_type": "text",
    "id": "GcnG6XJ6fBLu"
   },
facebook-github-bot's avatar
facebook-github-bot committed
313
   "source": [
314
    "## 2. Create a renderer\n",
facebook-github-bot's avatar
facebook-github-bot committed
315
    "\n",
316
    "A renderer in PyTorch3D is composed of a **rasterizer** and a **shader** which each have a number of subcomponents such as a **camera** (orthographic/perspective). Here we initialize some of these components and use default values for the rest.\n",
facebook-github-bot's avatar
facebook-github-bot committed
317
    "\n",
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
318
    "In this example we will first create a **renderer** which uses a **perspective camera**, a **point light** and applies **Phong shading**. Then we learn how to vary different components using the modular API.  "
facebook-github-bot's avatar
facebook-github-bot committed
319
320
321
322
   ]
  },
  {
   "cell_type": "code",
323
   "execution_count": null,
324
325
326
327
328
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "dX466mWnfBLv"
   },
facebook-github-bot's avatar
facebook-github-bot committed
329
330
   "outputs": [],
   "source": [
Georgia Gkioxari's avatar
Georgia Gkioxari committed
331
    "# Initialize a camera.\n",
332
333
334
    "# With world coordinates +Y up, +X left and +Z in, the front of the cow is facing the -Z direction. \n",
    "# So we move the camera by 180 in the azimuth direction so it is facing the front of the cow. \n",
    "R, T = look_at_view_transform(2.7, 0, 180) \n",
Georgia Gkioxari's avatar
Georgia Gkioxari committed
335
    "cameras = FoVPerspectiveCameras(device=device, R=R, T=T)\n",
facebook-github-bot's avatar
facebook-github-bot committed
336
337
338
    "\n",
    "# Define the settings for rasterization and shading. Here we set the output image to be of size\n",
    "# 512x512. As we are rendering images for visualization purposes only we will set faces_per_pixel=1\n",
Nikhila Ravi's avatar
Nikhila Ravi committed
339
340
341
342
    "# and blur_radius=0.0. We also set bin_size and max_faces_per_bin to None which ensure that \n",
    "# the faster coarse-to-fine rasterization method is used. Refer to rasterize_meshes.py for \n",
    "# explanations of these parameters. Refer to docs/notes/renderer.md for an explanation of \n",
    "# the difference between naive and coarse-to-fine rasterization. \n",
facebook-github-bot's avatar
facebook-github-bot committed
343
344
345
346
347
348
    "raster_settings = RasterizationSettings(\n",
    "    image_size=512, \n",
    "    blur_radius=0.0, \n",
    "    faces_per_pixel=1, \n",
    ")\n",
    "\n",
349
350
351
    "# Place a point light in front of the object. As mentioned above, the front of the cow is facing the \n",
    "# -z direction. \n",
    "lights = PointLights(device=device, location=[[0.0, 0.0, -3.0]])\n",
facebook-github-bot's avatar
facebook-github-bot committed
352
    "\n",
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
353
    "# Create a Phong renderer by composing a rasterizer and a shader. The textured Phong shader will \n",
facebook-github-bot's avatar
facebook-github-bot committed
354
355
356
357
358
359
360
    "# interpolate the texture uv coordinates for each vertex, sample from a texture image and \n",
    "# apply the Phong lighting model\n",
    "renderer = MeshRenderer(\n",
    "    rasterizer=MeshRasterizer(\n",
    "        cameras=cameras, \n",
    "        raster_settings=raster_settings\n",
    "    ),\n",
Nikhila Ravi's avatar
Nikhila Ravi committed
361
    "    shader=SoftPhongShader(\n",
facebook-github-bot's avatar
facebook-github-bot committed
362
363
364
365
366
367
368
369
370
    "        device=device, \n",
    "        cameras=cameras,\n",
    "        lights=lights\n",
    "    )\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
371
372
373
374
   "metadata": {
    "colab_type": "text",
    "id": "KyOY5qXvfBLz"
   },
facebook-github-bot's avatar
facebook-github-bot committed
375
   "source": [
376
    "## 3. Render the mesh"
facebook-github-bot's avatar
facebook-github-bot committed
377
378
379
380
   ]
  },
  {
   "cell_type": "markdown",
381
382
383
384
   "metadata": {
    "colab_type": "text",
    "id": "8VkRA4qJfBL0"
   },
facebook-github-bot's avatar
facebook-github-bot committed
385
386
387
388
389
390
   "source": [
    "The light is in front of the object so it is bright and the image has specular highlights."
   ]
  },
  {
   "cell_type": "code",
391
   "execution_count": null,
392
393
394
395
396
397
398
399
400
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 592
    },
    "colab_type": "code",
    "id": "gBLZH8iUfBL1",
    "outputId": "cc3cd3f0-189e-4497-ce47-e64b4da542e8"
   },
401
   "outputs": [],
facebook-github-bot's avatar
facebook-github-bot committed
402
403
404
405
   "source": [
    "images = renderer(mesh)\n",
    "plt.figure(figsize=(10, 10))\n",
    "plt.imshow(images[0, ..., :3].cpu().numpy())\n",
406
    "plt.axis(\"off\");"
facebook-github-bot's avatar
facebook-github-bot committed
407
408
409
410
   ]
  },
  {
   "cell_type": "markdown",
411
412
413
414
   "metadata": {
    "colab_type": "text",
    "id": "k161XF3sfBL5"
   },
facebook-github-bot's avatar
facebook-github-bot committed
415
   "source": [
416
    "## 4. Move the light behind the object and re-render\n",
facebook-github-bot's avatar
facebook-github-bot committed
417
    "\n",
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
418
    "We can pass arbitrary keyword arguments to the `rasterizer`/`shader` via the call to the `renderer` so the renderer does not need to be reinitialized if any of the settings change/\n",
facebook-github-bot's avatar
facebook-github-bot committed
419
420
421
422
423
424
425
426
    "\n",
    "In this case, we can simply update the location of the lights and pass them into the call to the renderer. \n",
    "\n",
    "The image is now dark as there is only ambient lighting, and there are no specular highlights."
   ]
  },
  {
   "cell_type": "code",
427
   "execution_count": null,
428
429
430
431
432
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "BdWkkeibfBL6"
   },
facebook-github-bot's avatar
facebook-github-bot committed
433
434
   "outputs": [],
   "source": [
435
    "# Now move the light so it is on the +Z axis which will be behind the cow. \n",
facebook-github-bot's avatar
facebook-github-bot committed
436
437
438
439
440
441
    "lights.location = torch.tensor([0.0, 0.0, +1.0], device=device)[None]\n",
    "images = renderer(mesh, lights=lights)"
   ]
  },
  {
   "cell_type": "code",
442
   "execution_count": null,
443
444
445
446
447
448
449
450
451
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 592
    },
    "colab_type": "code",
    "id": "UmV3j1YffBL9",
    "outputId": "2e8edca0-5bd8-4a2f-a160-83c4b0520123"
   },
452
   "outputs": [],
facebook-github-bot's avatar
facebook-github-bot committed
453
454
455
   "source": [
    "plt.figure(figsize=(10, 10))\n",
    "plt.imshow(images[0, ..., :3].cpu().numpy())\n",
456
    "plt.axis(\"off\");"
facebook-github-bot's avatar
facebook-github-bot committed
457
458
459
460
   ]
  },
  {
   "cell_type": "markdown",
461
462
463
464
   "metadata": {
    "colab_type": "text",
    "id": "t93aVotMfBMB"
   },
facebook-github-bot's avatar
facebook-github-bot committed
465
   "source": [
466
    "## 5. Rotate the object, modify the material properties or light properties\n",
facebook-github-bot's avatar
facebook-github-bot committed
467
468
469
470
471
472
473
474
475
476
    "\n",
    "We can also change many other settings in the rendering pipeline. Here we:\n",
    "\n",
    "- change the **viewing angle** of the camera\n",
    "- change the **position** of the point light\n",
    "- change the **material reflectance** properties of the mesh"
   ]
  },
  {
   "cell_type": "code",
477
   "execution_count": null,
478
479
480
481
482
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "4mYXYziefBMB"
   },
facebook-github-bot's avatar
facebook-github-bot committed
483
484
   "outputs": [],
   "source": [
485
486
    "# Rotate the object by increasing the elevation and azimuth angles\n",
    "R, T = look_at_view_transform(dist=2.7, elev=10, azim=-150)\n",
Georgia Gkioxari's avatar
Georgia Gkioxari committed
487
    "cameras = FoVPerspectiveCameras(device=device, R=R, T=T)\n",
facebook-github-bot's avatar
facebook-github-bot committed
488
    "\n",
489
490
    "# Move the light location so the light is shining on the cow's face.  \n",
    "lights.location = torch.tensor([[2.0, 2.0, -2.0]], device=device)\n",
facebook-github-bot's avatar
facebook-github-bot committed
491
492
493
494
495
496
497
498
499
500
501
502
503
504
    "\n",
    "# Change specular color to green and change material shininess \n",
    "materials = Materials(\n",
    "    device=device,\n",
    "    specular_color=[[0.0, 1.0, 0.0]],\n",
    "    shininess=10.0\n",
    ")\n",
    "\n",
    "# Re render the mesh, passing in keyword arguments for the modified components.\n",
    "images = renderer(mesh, lights=lights, materials=materials, cameras=cameras)"
   ]
  },
  {
   "cell_type": "code",
505
   "execution_count": null,
506
507
508
509
510
511
512
513
514
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 592
    },
    "colab_type": "code",
    "id": "rHIxIfh5fBME",
    "outputId": "1ca2d337-2983-478f-b3c9-d64b84ba1a31"
   },
515
   "outputs": [],
facebook-github-bot's avatar
facebook-github-bot committed
516
517
518
   "source": [
    "plt.figure(figsize=(10, 10))\n",
    "plt.imshow(images[0, ..., :3].cpu().numpy())\n",
519
    "plt.axis(\"off\");"
facebook-github-bot's avatar
facebook-github-bot committed
520
521
522
523
   ]
  },
  {
   "cell_type": "markdown",
524
525
526
527
   "metadata": {
    "colab_type": "text",
    "id": "17c4xmtyfBMH"
   },
facebook-github-bot's avatar
facebook-github-bot committed
528
   "source": [
529
    "## 6. Batched Rendering\n",
facebook-github-bot's avatar
facebook-github-bot committed
530
    "\n",
531
    "One of the core design choices of the PyTorch3D API is to support **batched inputs for all components**. \n",
facebook-github-bot's avatar
facebook-github-bot committed
532
533
534
535
536
    "The renderer and associated components can take batched inputs and **render a batch of output images in one forward pass**. We will now use this feature to render the mesh from many different viewpoints.\n"
   ]
  },
  {
   "cell_type": "code",
537
   "execution_count": null,
538
539
540
541
542
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "CDQKebNNfBMI"
   },
facebook-github-bot's avatar
facebook-github-bot committed
543
544
545
546
547
548
549
550
551
552
553
   "outputs": [],
   "source": [
    "# Set batch size - this is the number of different viewpoints from which we want to render the mesh.\n",
    "batch_size = 20\n",
    "\n",
    "# Create a batch of meshes by repeating the cow mesh and associated textures. \n",
    "# Meshes has a useful `extend` method which allows us do this very easily. \n",
    "# This also extends the textures. \n",
    "meshes = mesh.extend(batch_size)\n",
    "\n",
    "# Get a batch of viewing angles. \n",
554
555
    "elev = torch.linspace(0, 180, batch_size)\n",
    "azim = torch.linspace(-180, 180, batch_size)\n",
facebook-github-bot's avatar
facebook-github-bot committed
556
557
558
559
560
    "\n",
    "# All the cameras helper methods support mixed type inputs and broadcasting. So we can \n",
    "# view the camera from the same distance and specify dist=2.7 as a float,\n",
    "# and then specify elevation and azimuth angles for each viewpoint as tensors. \n",
    "R, T = look_at_view_transform(dist=2.7, elev=elev, azim=azim)\n",
Georgia Gkioxari's avatar
Georgia Gkioxari committed
561
    "cameras = FoVPerspectiveCameras(device=device, R=R, T=T)\n",
facebook-github-bot's avatar
facebook-github-bot committed
562
    "\n",
563
564
    "# Move the light back in front of the cow which is facing the -z direction.\n",
    "lights.location = torch.tensor([[0.0, 0.0, -3.0]], device=device)"
facebook-github-bot's avatar
facebook-github-bot committed
565
566
567
568
   ]
  },
  {
   "cell_type": "code",
569
   "execution_count": null,
570
571
572
573
574
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "gyYJCwEDfBML"
   },
facebook-github-bot's avatar
facebook-github-bot committed
575
576
   "outputs": [],
   "source": [
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
577
    "# We can pass arbitrary keyword arguments to the rasterizer/shader via the renderer\n",
facebook-github-bot's avatar
facebook-github-bot committed
578
    "# so the renderer does not need to be reinitialized if any of the settings change.\n",
579
    "images = renderer(meshes, cameras=cameras, lights=lights)"
facebook-github-bot's avatar
facebook-github-bot committed
580
581
582
583
   ]
  },
  {
   "cell_type": "code",
584
   "execution_count": null,
585
   "metadata": {},
586
   "outputs": [],
facebook-github-bot's avatar
facebook-github-bot committed
587
588
589
   "source": [
    "image_grid(images.cpu().numpy(), rows=4, cols=5, rgb=True)"
   ]
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
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 7. Plotly visualization \n",
    "If you only want to visualize a mesh, you don't really need to use a differentiable renderer - instead we support plotting of Meshes with plotly. For these Meshes, we use TexturesVertex to define a texture for the rendering.\n",
    "`plot_meshes` creates a Plotly figure with a trace for each Meshes object. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "verts, faces_idx, _ = load_obj(obj_filename)\n",
    "faces = faces_idx.verts_idx\n",
    "\n",
    "# Initialize each vertex to be white in color.\n",
    "verts_rgb = torch.ones_like(verts)[None]  # (1, V, 3)\n",
    "textures = TexturesVertex(verts_features=verts_rgb.to(device))\n",
    "\n",
    "# Create a Meshes object\n",
    "mesh = Meshes(\n",
    "    verts=[verts.to(device)],   \n",
    "    faces=[faces.to(device)],\n",
    "    textures=textures\n",
    ")\n",
    "\n",
    "# Render the plotly figure\n",
621
622
623
624
625
    "fig = plot_scene({\n",
    "    \"subplot1\": {\n",
    "        \"cow_mesh\": mesh\n",
    "    }\n",
    "})\n",
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
    "fig.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# use Plotly's default colors (no texture)\n",
    "mesh = Meshes(\n",
    "    verts=[verts.to(device)],   \n",
    "    faces=[faces.to(device)]\n",
    ")\n",
    "\n",
    "# Render the plotly figure\n",
642
643
644
645
646
647
    "fig = plot_scene({\n",
    "    \"subplot1\": {\n",
    "        \"cow_mesh\": mesh\n",
    "    }\n",
    "})\n",
    "fig.show()"
648
649
650
651
652
653
654
655
656
657
658
659
660
661
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# create a batch of meshes, and offset one to prevent overlap\n",
    "mesh_batch = Meshes(\n",
    "    verts=[verts.to(device), (verts + 2).to(device)],   \n",
    "    faces=[faces.to(device), faces.to(device)]\n",
    ")\n",
    "\n",
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
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
    "# plot mesh batch in the same trace\n",
    "fig = plot_scene({\n",
    "    \"subplot1\": {\n",
    "        \"cow_mesh_batch\": mesh_batch\n",
    "    }\n",
    "})\n",
    "fig.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# plot batch of meshes in different traces\n",
    "fig = plot_scene({\n",
    "    \"subplot1\": {\n",
    "        \"cow_mesh1\": mesh_batch[0],\n",
    "        \"cow_mesh2\": mesh_batch[1]\n",
    "    }\n",
    "})\n",
    "fig.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# plot batch of meshes in different subplots\n",
    "fig = plot_scene({\n",
    "    \"subplot1\": {\n",
    "        \"cow_mesh1\": mesh_batch[0]\n",
    "    },\n",
    "    \"subplot2\":{\n",
    "        \"cow_mesh2\": mesh_batch[1]\n",
    "    }\n",
    "})\n",
    "fig.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For batches, we can also use `plot_batch_individually` to avoid constructing the scene dictionary ourselves."
710
711
712
713
714
715
716
717
718
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# extend the batch to have 4 meshes\n",
719
    "mesh_4 = mesh_batch.extend(2)\n",
720
721
    "\n",
    "# visualize the batch in different subplots, 2 per row\n",
722
    "fig = plot_batch_individually(mesh_4)\n",
723
    "# we can update the figure height and width\n",
724
    "fig.update_layout(height=1000, width=500)\n",
725
726
727
728
729
730
731
    "fig.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
732
    "We can also modify the axis arguments and axis backgrounds in both functions. "
733
734
735
736
737
738
739
740
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
741
742
743
744
745
746
747
748
749
    "fig2 = plot_scene({\n",
    "    \"cow_plot1\": {\n",
    "        \"cows\": mesh_batch\n",
    "    }\n",
    "},\n",
    "    xaxis={\"backgroundcolor\":\"rgb(200, 200, 230)\"},\n",
    "    yaxis={\"backgroundcolor\":\"rgb(230, 200, 200)\"},\n",
    "    zaxis={\"backgroundcolor\":\"rgb(200, 230, 200)\"}, \n",
    "    axis_args=AxisArgs(showgrid=True))\n",
750
751
752
    "fig2.show()"
   ]
  },
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig3 = plot_batch_individually(\n",
    "    mesh_4, \n",
    "    ncols=2,\n",
    "    subplot_titles = [\"cow1\", \"cow2\", \"cow3\", \"cow4\"], # customize subplot titles\n",
    "    xaxis={\"backgroundcolor\":\"rgb(200, 200, 230)\"},\n",
    "    yaxis={\"backgroundcolor\":\"rgb(230, 200, 200)\"},\n",
    "    zaxis={\"backgroundcolor\":\"rgb(200, 230, 200)\"}, \n",
    "    axis_args=AxisArgs(showgrid=True))\n",
    "fig3.show()"
   ]
  },
770
771
772
773
774
775
776
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "t3qphI1ElUb5"
   },
   "source": [
777
778
    "## 8. Conclusion\n",
    "In this tutorial we learnt how to **load** a textured mesh from an obj file, initialize a PyTorch3D datastructure called **Meshes**, set up an **Renderer** consisting of a **Rasterizer** and a **Shader**, and modify several components of the rendering pipeline. We also learned how to render Meshes in Plotly figures."
779
   ]
facebook-github-bot's avatar
facebook-github-bot committed
780
781
782
  }
 ],
 "metadata": {
783
  "accelerator": "GPU",
Nikhila Ravi's avatar
Nikhila Ravi committed
784
  "anp_metadata": {
785
   "path": "notebooks/render_textured_meshes.ipynb"
Nikhila Ravi's avatar
Nikhila Ravi committed
786
  },
facebook-github-bot's avatar
facebook-github-bot committed
787
788
789
790
791
792
793
794
  "bento_stylesheets": {
   "bento/extensions/flow/main.css": true,
   "bento/extensions/kernel_selector/main.css": true,
   "bento/extensions/kernel_ui/main.css": true,
   "bento/extensions/new_kernel/main.css": true,
   "bento/extensions/system_usage/main.css": true,
   "bento/extensions/theme/main.css": true
  },
795
796
797
798
  "colab": {
   "name": "render_textured_meshes.ipynb",
   "provenance": []
  },
Nikhila Ravi's avatar
Nikhila Ravi committed
799
800
801
  "disseminate_notebook_info": {
   "backup_notebook_id": "569222367081034"
  },
facebook-github-bot's avatar
facebook-github-bot committed
802
  "kernelspec": {
803
   "display_name": "pytorch3d_etc (local)",
facebook-github-bot's avatar
facebook-github-bot committed
804
   "language": "python",
805
   "name": "pytorch3d_etc_local"
facebook-github-bot's avatar
facebook-github-bot committed
806
807
808
809
810
811
812
813
814
815
816
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
817
   "version": "3.7.5+"
facebook-github-bot's avatar
facebook-github-bot committed
818
819
820
  }
 },
 "nbformat": 4,
821
 "nbformat_minor": 1
facebook-github-bot's avatar
facebook-github-bot committed
822
}