You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将PyVista网格裁剪至半径为3的球体且边界平滑?

解决方案

完整修改代码

from math import pi, cos, sin
import pyvista as pv
import numpy as np

def strange_surface(x, y, z, A, B):
    return (
        z**4 * B**2
        + 4 * x * y**2 * A * B**2
        + x * z**2 * A * B**2
        - 2 * z**4 * A
        - 4 * x * y**2 * B**2
        - x * z**2 * B**2
        + 3 * z**2 * A * B**2
        - 2 * z**4
        - x * A * B**2
        - 2 * z**2 * A
        + x * B**2
        + A * B**2
        + 2 * z**2
        - B**2
    )

# 生成结构化网格并计算等值面
X, Y, Z = np.mgrid[-3.05:3.05:250j, -3.05:3.05:250j, -3.05:3.05:250j]
grid = pv.StructuredGrid(X, Y, Z)
A = cos(2.5*pi/4)
B = sin(2.5*pi/4)
grid["values"] = strange_surface(X, Y, Z, A, B)
isosurf = grid.contour(isosurfaces=[0])

# 裁剪到半径3的球体内并平滑边界
clip_sphere = pv.Sphere(radius=3, center=(0,0,0))
clipped_mesh = isosurf.clip_surface(clip_sphere, invert=False)
smoothed_mesh = clipped_mesh.smooth(n_iter=50, relaxation_factor=0.1)

# 可视化设置
dists = np.linalg.norm(smoothed_mesh.points, axis=1)
dists = (dists - dists.min()) / (dists.max() - dists.min())
smoothed_mesh["dist"] = dists

pltr = pv.Plotter(window_size=(512, 512))
pltr.background_color = "#363940"
pltr.set_focus(smoothed_mesh.center)
pltr.set_position((17, 14, 12))
pltr.add_mesh(
    smoothed_mesh,
    smooth_shading=True,
    specular=0.9,
    color="yellow"
)
pltr.show()

关键改动说明

  • 简化数据赋值:新版本PyVista无需手动调用ravel(order="F"),直接将计算结果赋值给grid["values"]即可,库会自动处理维度匹配。
  • 球体裁剪实现:用clip_surface方法结合半径3的球体,invert=False保留球内网格,自动丢弃距离原点超过3的点。
  • 平滑裁剪边界:通过smooth方法处理裁剪后的边界,n_iter控制迭代次数,relaxation_factor控制松弛程度,可根据需求调整参数平衡平滑效果与细节保留。
  • 移除冗余代码:删除了extract_geometry()(等值面已为几何网格)、pltr.camera.zoom(1)(默认缩放比例为1)、off_screen=False(默认非离线模式)等无意义调用。

内容的提问来源于stack exchange,提问作者Stéphane Laurent

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 07:43:15