3d平滑
import torch
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
class SmoothOperator:
def smooth(self, vertices):
# 使用一维平均池化进行平滑
vertices_smooth = F.avg_pool1d(
vertices.permute(0, 2, 1),
kernel_size=3,
stride=1,
padding=1
).permute(0, 2, 1)
# 保持顶点的首尾不变,只修改中间部分
vertices[:, 1:-1] = vertices_smooth[:, 1:-1]
return vertices
# 创建一些示例数据
t = np.linspace(0, 2 * np.pi, 100)
x = np.sin(t) + np.random.normal(0, 0.1, t.shape) # 添加一些噪声
y = np.cos(t) + np.random.normal(0, 0.1, t.shape)
z = t
vertices = torch.tensor(np.stack([x, y, z], axis=1), dtype=torch.float32).unsqueeze(0)
# 实例化平滑操作对象并应用平滑
smooth_operator = SmoothOperator()
vertices_smooth = smooth_operator.smooth(vertices.clone())
# 将PyTorch张量转换为NumPy数组以用于绘图
vertices_np = vertices.squeeze(0).numpy()
vertices_smooth_np = vertices_smooth.squeeze(0).numpy()
# 创建图形和3D轴
fig = plt.figure(figsize=(12, 6))
# 绘制原始数据
ax1 = fig.add_subplot(121, projection='3d')
ax1.plot(vertices_np[:, 0], vertices_np[:, 1], vertices_np[:, 2], label='Original', color='b')
ax1.set_title("Original Data")
ax1.legend()
# 绘制平滑后的数据
ax2 = fig.add_subplot(122, projection='3d')
ax2.plot(vertices_smooth_np[:, 0], vertices_smooth_np[:, 1], vertices_smooth_np[:, 2], label='Smoothed', color='r')
ax2.set_title("Smoothed Data")
ax2.legend()
# 显示图形
plt.show()