如何在Python 3D绘图环境中交互操作.obj/.stl格式3D对象
Hey there! I’ve spent a fair amount of time working with 3D model manipulation in Python, so let me break down the best tools and hands-on workflows for handling .obj and .stl files—covering everything from loading, interactive viewing, adding multiple objects, to editing mesh data.
PyVista is hands-down the easiest library for interactive 3D in Python. It wraps VTK under the hood but has a Pythonic API that’s way more approachable for everyday tasks.
Installation
First, get it installed:
pip install pyvista
Loading .obj/.stl Files
Loading models is a total one-liner—no messy parsing required:
import pyvista as pv # Load an .obj file mesh_obj = pv.read("your_model.obj") # Load an .stl file mesh_stl = pv.read("your_model.stl")
Interactive Viewing
To view the model with full interactivity (zoom, pan, rotate, toggle wireframe, etc.), just call:
mesh_obj.plot()
You’ll get a dedicated window with a toolbar—hover over buttons to see their functions. It’s intuitive enough that you’ll be navigating the model in seconds.
Adding Multiple Objects to the Scene
Want to combine multiple models or add primitive shapes? Use a Plotter object to build your scene:
plotter = pv.Plotter() # Add first mesh with a red color and label it plotter.add_mesh(mesh_obj, color="red", label="Original Object") # Shift the STL mesh along the X-axis and add it mesh_stl_shifted = mesh_stl.translate([10, 0, 0]) plotter.add_mesh(mesh_stl_shifted, color="blue", label="Shifted STL") # Add a small sphere at the origin as a reference sphere = pv.Sphere(radius=1, center=[0,0,0]) plotter.add_mesh(sphere, color="green", label="Reference Sphere") # Add a legend and show the final scene plotter.add_legend() plotter.show()
Editing Operations
PyVista has tons of built-in editing tools. Here are a few common ones:
- Cropping: Cut a section out of the mesh with a bounding box
# Crop to a box from (-5,-5,-5) to (5,5,5) cropped_mesh = mesh_obj.clip_box(bounds=[-5,5,-5,5,-5,5]) cropped_mesh.plot(title="Cropped Mesh") - Smoothing: Reduce mesh roughness for cleaner visuals
smoothed_mesh = mesh_obj.smooth(n_iter=100) smoothed_mesh.plot(title="Smoothed Mesh") - Merging Meshes: Combine your model with another shape
cube = pv.Cube(center=[5,0,0], x_length=4) combined_mesh = mesh_obj.merge(cube) combined_mesh.plot(title="Combined Mesh")
If you need low-level control over mesh data (like modifying vertices, faces, or processing point clouds), Open3D is your go-to. It also has solid interactive tools for inspecting edits.
Installation
Install via pip:
pip install open3d
Loading .obj/.stl Files
import open3d as o3d # Load .obj file mesh_obj = o3d.io.read_triangle_mesh("your_model.obj") # Load .stl file mesh_stl = o3d.io.read_triangle_mesh("your_model.stl") # Fix common mesh issues (like non-manifold edges) mesh_obj.remove_non_manifold_edges()
Interactive Viewing
Open3D’s viewer lets you interact with the model and even select individual faces/vertices:
o3d.visualization.draw_geometries([mesh_obj])
Mouse controls: Left-click drag to rotate, right-click drag to pan, scroll to zoom.
Adding Multiple Objects
Just pass a list of geometries to the viewer function:
# Shift the STL mesh along the Y-axis mesh_stl.translate([0, 6, 0]) # Add a cylinder as a third object cylinder = o3d.geometry.TriangleMesh.create_cylinder(radius=1, height=8) cylinder.translate([6,0,0]) # Show all objects together o3d.visualization.draw_geometries([mesh_obj, mesh_stl, cylinder])
Editing Operations
- Mesh Simplification: Reduce the number of faces for lighter models
# Simplify to 1000 triangles from the original count simplified_mesh = mesh_obj.simplify_quadric_decimation(target_number_of_triangles=1000) o3d.visualization.draw_geometries([simplified_mesh], window_name="Simplified Mesh") - Manual Vertex Editing: Adjust specific vertex positions
import numpy as np # Get vertex data as a numpy array vertices = np.asarray(mesh_obj.vertices) # Move the first 15 vertices up along the Z-axis vertices[:15, 2] += 4 # Update the mesh with modified vertices mesh_obj.vertices = o3d.utility.Vector3dVector(vertices) o3d.visualization.draw_geometries([mesh_obj], window_name="Edited Vertices") - Plane Cutting: Split the mesh with a custom plane
# Create a plane at the origin with normal along the X-axis plane = o3d.geometry.Plane() plane.set_from_point_normal([0,0,0], [1,0,0]) # Cut the mesh along the plane cut_mesh = mesh_obj.cut_plane(plane) o3d.visualization.draw_geometries([cut_mesh], window_name="Cut Mesh")
If you don’t need heavy interactivity and just want to embed a 3D view in a matplotlib figure, this combo works. Note: Matplotlib’s 3D controls are clunky compared to PyVista/Open3D, so it’s best for quick previews.
Installation
You’ll need matplotlib and trimesh (to handle mesh file loading):
pip install matplotlib trimesh
Loading and Viewing
import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import trimesh # Load the mesh mesh = trimesh.load("your_model.obj") # Set up the 3D plot fig = plt.figure(figsize=(10,8)) ax = fig.add_subplot(111, projection='3d') # Plot each face of the mesh for face in mesh.faces: ax.plot3D(mesh.vertices[face, 0], mesh.vertices[face, 1], mesh.vertices[face, 2], color='gray', linewidth=0.5) # Add axis labels ax.set_xlabel('X Axis') ax.set_ylabel('Y Axis') ax.set_zlabel('Z Axis') ax.set_title('Quick Mesh Preview') plt.show()
You can rotate the plot with mouse drag, but zoom and pan are not as smooth as the other libraries.
内容的提问来源于stack exchange,提问作者Ray Lee




