import numpy as np
import matplotlib.pyplot as plt
from skimage import measure
n = 64
x, y, z = np.ogrid[-1:1:n*1j, -1:1:n*1j, -1:1:n*1j]
sphere = x**2 + y**2 + z**2
verts, faces, normals, values = measure.marching_cubes(sphere, level=0.5)
fig = plt.figure(figsize=(6, 6))
ax = fig.add_subplot(111, projection='3d')
mesh = ax.plot_trisurf(
verts[:, 0], verts[:, 1], faces, verts[:, 2],
cmap='Spectral', lw=1, alpha=0.9
)
ax.set_title('Iso-Surface Plot (Marching Cubes)')
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
plt.tight_layout()
plt.show()
#source code --> clcoding.com
Code Explanation:
Libraries Imported
import numpy as np
import matplotlib.pyplot as plt
from skimage import measure
numpy → for numerical calculations and creating 3D
grid.
Step 1: Create a Scalar Field (3D Grid of Values)
n = 64
x, y, z = np.ogrid[-1:1:n*1j, -1:1:n*1j, -1:1:n*1j]
sphere = x**2 + y**2 + z**2
np.ogrid creates 3D grid coordinates with n = 64
steps in each dimension.
This effectively creates a spherical shape within
the volume.
verts, faces, normals, values =
measure.marching_cubes(sphere, level=0.5)
marching_cubes() extracts the surface where the
scalar field equals 0.5.
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
Sets up a 3D plot figure and axis.
verts[:,
0], verts[:, 1], faces, verts[:, 2],
cmap='Spectral', lw=1, alpha=0.9
)
plot_trisurf() creates a triangular surface from the
mesh.
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
plt.tight_layout()
plt.show()
Adds axis labels and a title.


0 Comments:
Post a Comment