# Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved.
确保已安装torch
和torchvision
。如果未安装pytorch3d
,请使用以下单元格安装它
import os
import sys
import torch
need_pytorch3d=False
try:
import pytorch3d
except ModuleNotFoundError:
need_pytorch3d=True
if need_pytorch3d:
if torch.__version__.startswith("2.2.") and sys.platform.startswith("linux"):
# We try to install PyTorch3D via a released wheel.
pyt_version_str=torch.__version__.split("+")[0].replace(".", "")
version_str="".join([
f"py3{sys.version_info.minor}_cu",
torch.version.cuda.replace(".",""),
f"_pyt{pyt_version_str}"
])
!pip install fvcore iopath
!pip install --no-index --no-cache-dir pytorch3d -f https://dl.fbaipublicfiles.com/pytorch3d/packaging/wheels/{version_str}/download.html
else:
# We try to install PyTorch3D from source.
!pip install 'git+https://github.com/facebookresearch/pytorch3d.git@stable'
import os
import torch
import matplotlib.pyplot as plt
# Util function for loading meshes
from pytorch3d.io import load_objs_as_meshes, load_obj
# Data structures and functions for rendering
from pytorch3d.structures import Meshes
from pytorch3d.vis.plotly_vis import AxisArgs, plot_batch_individually, plot_scene
from pytorch3d.vis.texture_vis import texturesuv_image_matplotlib
from pytorch3d.renderer import (
look_at_view_transform,
FoVPerspectiveCameras,
PointLights,
DirectionalLights,
Materials,
RasterizationSettings,
MeshRenderer,
MeshRasterizer,
SoftPhongShader,
TexturesUV,
TexturesVertex
)
# add path for demo utils functions
import sys
import os
sys.path.append(os.path.abspath(''))
如果使用Google Colab,请获取用于绘制图像网格的utils文件
!wget https://raw.githubusercontent.com/facebookresearch/pytorch3d/main/docs/tutorials/utils/plot_image_grid.py
from plot_image_grid import image_grid
或者,如果本地运行,请取消注释并运行以下单元格
# from utils import image_grid
加载.obj
文件及其关联的.mtl
文件,并创建纹理和网格对象。
网格是PyTorch3D中提供的一种独特的数据结构,用于处理不同大小的网格批次。
TexturesUV是用于存储网格顶点uv和纹理贴图的辅助数据结构。
网格有几个类方法,这些方法贯穿整个渲染管道。
如果使用Google Colab运行此笔记本,请运行以下单元格以获取网格obj和纹理文件,并将其保存在路径data/cow_mesh
下:如果在本地运行,则数据已在正确的路径下可用。
!mkdir -p data/cow_mesh
!wget -P data/cow_mesh https://dl.fbaipublicfiles.com/pytorch3d/data/cow_mesh/cow.obj
!wget -P data/cow_mesh https://dl.fbaipublicfiles.com/pytorch3d/data/cow_mesh/cow.mtl
!wget -P data/cow_mesh https://dl.fbaipublicfiles.com/pytorch3d/data/cow_mesh/cow_texture.png
# Setup
if torch.cuda.is_available():
device = torch.device("cuda:0")
torch.cuda.set_device(device)
else:
device = torch.device("cpu")
# Set paths
DATA_DIR = "./data"
obj_filename = os.path.join(DATA_DIR, "cow_mesh/cow.obj")
# Load obj file
mesh = load_objs_as_meshes([obj_filename], device=device)
plt.figure(figsize=(7,7))
texture_image=mesh.textures.maps_padded()
plt.imshow(texture_image.squeeze().cpu().numpy())
plt.axis("off");
PyTorch3D有一种内置方法可以使用matplotlib查看纹理贴图,以及贴图上对应于顶点的点。还有一种方法texturesuv_image_PIL,可以获取类似的图像并将其保存到文件中。
plt.figure(figsize=(7,7))
texturesuv_image_matplotlib(mesh.textures, subsample=None)
plt.axis("off");
PyTorch3D中的渲染器由光栅化器和着色器组成,每个渲染器都包含许多子组件,例如相机(正交/透视)。这里我们初始化其中一些组件,并为其余组件使用默认值。
在这个例子中,我们首先创建一个使用透视相机、点光源并应用Phong着色的渲染器。然后,我们将学习如何使用模块化API更改不同的组件。
# Initialize a camera.
# With world coordinates +Y up, +X left and +Z in, the front of the cow is facing the -Z direction.
# So we move the camera by 180 in the azimuth direction so it is facing the front of the cow.
R, T = look_at_view_transform(2.7, 0, 180)
cameras = FoVPerspectiveCameras(device=device, R=R, T=T)
# Define the settings for rasterization and shading. Here we set the output image to be of size
# 512x512. As we are rendering images for visualization purposes only we will set faces_per_pixel=1
# and blur_radius=0.0. We also set bin_size and max_faces_per_bin to None which ensure that
# the faster coarse-to-fine rasterization method is used. Refer to rasterize_meshes.py for
# explanations of these parameters. Refer to docs/notes/renderer.md for an explanation of
# the difference between naive and coarse-to-fine rasterization.
raster_settings = RasterizationSettings(
image_size=512,
blur_radius=0.0,
faces_per_pixel=1,
)
# Place a point light in front of the object. As mentioned above, the front of the cow is facing the
# -z direction.
lights = PointLights(device=device, location=[[0.0, 0.0, -3.0]])
# Create a Phong renderer by composing a rasterizer and a shader. The textured Phong shader will
# interpolate the texture uv coordinates for each vertex, sample from a texture image and
# apply the Phong lighting model
renderer = MeshRenderer(
rasterizer=MeshRasterizer(
cameras=cameras,
raster_settings=raster_settings
),
shader=SoftPhongShader(
device=device,
cameras=cameras,
lights=lights
)
)
光源位于物体前方,因此物体很亮,图像有镜面高光。
images = renderer(mesh)
plt.figure(figsize=(10, 10))
plt.imshow(images[0, ..., :3].cpu().numpy())
plt.axis("off");
我们可以通过对renderer
的调用将任意关键字参数传递给rasterizer
/shader
,因此如果任何设置发生更改,则不需要重新初始化渲染器。
在这种情况下,我们可以简单地更新光源的位置并将它们传递到对渲染器的调用中。
图像现在变暗了,因为只有环境光,没有镜面高光。
# Now move the light so it is on the +Z axis which will be behind the cow.
lights.location = torch.tensor([0.0, 0.0, +1.0], device=device)[None]
images = renderer(mesh, lights=lights)
plt.figure(figsize=(10, 10))
plt.imshow(images[0, ..., :3].cpu().numpy())
plt.axis("off");
# Rotate the object by increasing the elevation and azimuth angles
R, T = look_at_view_transform(dist=2.7, elev=10, azim=-150)
cameras = FoVPerspectiveCameras(device=device, R=R, T=T)
# Move the light location so the light is shining on the cow's face.
lights.location = torch.tensor([[2.0, 2.0, -2.0]], device=device)
# Change specular color to green and change material shininess
materials = Materials(
device=device,
specular_color=[[0.0, 1.0, 0.0]],
shininess=10.0
)
# Re render the mesh, passing in keyword arguments for the modified components.
images = renderer(mesh, lights=lights, materials=materials, cameras=cameras)
plt.figure(figsize=(10, 10))
plt.imshow(images[0, ..., :3].cpu().numpy())
plt.axis("off");
PyTorch3D API的核心设计选择之一是支持所有组件的批处理输入。渲染器和相关组件可以接收批处理输入,并在一个前向传递中渲染一批输出图像。我们现在将使用此功能从许多不同的视角渲染网格。
# Set batch size - this is the number of different viewpoints from which we want to render the mesh.
batch_size = 20
# Create a batch of meshes by repeating the cow mesh and associated textures.
# Meshes has a useful `extend` method which allows us do this very easily.
# This also extends the textures.
meshes = mesh.extend(batch_size)
# Get a batch of viewing angles.
elev = torch.linspace(0, 180, batch_size)
azim = torch.linspace(-180, 180, batch_size)
# All the cameras helper methods support mixed type inputs and broadcasting. So we can
# view the camera from the same distance and specify dist=2.7 as a float,
# and then specify elevation and azimuth angles for each viewpoint as tensors.
R, T = look_at_view_transform(dist=2.7, elev=elev, azim=azim)
cameras = FoVPerspectiveCameras(device=device, R=R, T=T)
# Move the light back in front of the cow which is facing the -z direction.
lights.location = torch.tensor([[0.0, 0.0, -3.0]], device=device)
# We can pass arbitrary keyword arguments to the rasterizer/shader via the renderer
# so the renderer does not need to be reinitialized if any of the settings change.
images = renderer(meshes, cameras=cameras, lights=lights)
image_grid(images.cpu().numpy(), rows=4, cols=5, rgb=True)
如果您只想可视化网格,则实际上不需要使用可微渲染器 - 相反,我们支持使用plotly绘制网格。对于这些网格,我们使用TexturesVertex为渲染定义纹理。plot_meshes
创建一个包含每个Meshes对象的轨迹的Plotly图形。
verts, faces_idx, _ = load_obj(obj_filename)
faces = faces_idx.verts_idx
# Initialize each vertex to be white in color.
verts_rgb = torch.ones_like(verts)[None] # (1, V, 3)
textures = TexturesVertex(verts_features=verts_rgb.to(device))
# Create a Meshes object
mesh = Meshes(
verts=[verts.to(device)],
faces=[faces.to(device)],
textures=textures
)
# Render the plotly figure
fig = plot_scene({
"subplot1": {
"cow_mesh": mesh
}
})
fig.show()
# use Plotly's default colors (no texture)
mesh = Meshes(
verts=[verts.to(device)],
faces=[faces.to(device)]
)
# Render the plotly figure
fig = plot_scene({
"subplot1": {
"cow_mesh": mesh
}
})
fig.show()
# create a batch of meshes, and offset one to prevent overlap
mesh_batch = Meshes(
verts=[verts.to(device), (verts + 2).to(device)],
faces=[faces.to(device), faces.to(device)]
)
# plot mesh batch in the same trace
fig = plot_scene({
"subplot1": {
"cow_mesh_batch": mesh_batch
}
})
fig.show()
# plot batch of meshes in different traces
fig = plot_scene({
"subplot1": {
"cow_mesh1": mesh_batch[0],
"cow_mesh2": mesh_batch[1]
}
})
fig.show()
# plot batch of meshes in different subplots
fig = plot_scene({
"subplot1": {
"cow_mesh1": mesh_batch[0]
},
"subplot2":{
"cow_mesh2": mesh_batch[1]
}
})
fig.show()
对于批次,我们还可以使用plot_batch_individually
来避免自己构建场景字典。
# extend the batch to have 4 meshes
mesh_4 = mesh_batch.extend(2)
# visualize the batch in different subplots, 2 per row
fig = plot_batch_individually(mesh_4)
# we can update the figure height and width
fig.update_layout(height=1000, width=500)
fig.show()
我们还可以修改这两个函数中的轴参数和轴背景。
fig2 = plot_scene({
"cow_plot1": {
"cows": mesh_batch
}
},
xaxis={"backgroundcolor":"rgb(200, 200, 230)"},
yaxis={"backgroundcolor":"rgb(230, 200, 200)"},
zaxis={"backgroundcolor":"rgb(200, 230, 200)"},
axis_args=AxisArgs(showgrid=True))
fig2.show()
fig3 = plot_batch_individually(
mesh_4,
ncols=2,
subplot_titles = ["cow1", "cow2", "cow3", "cow4"], # customize subplot titles
xaxis={"backgroundcolor":"rgb(200, 200, 230)"},
yaxis={"backgroundcolor":"rgb(230, 200, 200)"},
zaxis={"backgroundcolor":"rgb(200, 230, 200)"},
axis_args=AxisArgs(showgrid=True))
fig3.show()
在本教程中,我们学习了如何从obj文件加载纹理网格,初始化一个名为Meshes的PyTorch3D数据结构,设置一个由光栅化器和着色器组成的渲染器,以及修改渲染管道的几个组件。我们还学习了如何在Plotly图形中渲染网格。