mirror of
https://github.com/Estom/notes.git
synced 2026-02-07 20:44:38 +08:00
52 lines
1.4 KiB
Markdown
52 lines
1.4 KiB
Markdown
# 带有rgb颜色的3D体素/体积图
|
|
|
|
演示使用ax.voxels可视化颜色空间的各个部分
|
|
|
|

|
|
|
|
```python
|
|
import matplotlib.pyplot as plt
|
|
import numpy as np
|
|
|
|
# This import registers the 3D projection, but is otherwise unused.
|
|
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
|
|
|
|
|
|
def midpoints(x):
|
|
sl = ()
|
|
for i in range(x.ndim):
|
|
x = (x[sl + np.index_exp[:-1]] + x[sl + np.index_exp[1:]]) / 2.0
|
|
sl += np.index_exp[:]
|
|
return x
|
|
|
|
# prepare some coordinates, and attach rgb values to each
|
|
r, g, b = np.indices((17, 17, 17)) / 16.0
|
|
rc = midpoints(r)
|
|
gc = midpoints(g)
|
|
bc = midpoints(b)
|
|
|
|
# define a sphere about [0.5, 0.5, 0.5]
|
|
sphere = (rc - 0.5)**2 + (gc - 0.5)**2 + (bc - 0.5)**2 < 0.5**2
|
|
|
|
# combine the color components
|
|
colors = np.zeros(sphere.shape + (3,))
|
|
colors[..., 0] = rc
|
|
colors[..., 1] = gc
|
|
colors[..., 2] = bc
|
|
|
|
# and plot everything
|
|
fig = plt.figure()
|
|
ax = fig.gca(projection='3d')
|
|
ax.voxels(r, g, b, sphere,
|
|
facecolors=colors,
|
|
edgecolors=np.clip(2*colors - 0.5, 0, 1), # brighter
|
|
linewidth=0.5)
|
|
ax.set(xlabel='r', ylabel='g', zlabel='b')
|
|
|
|
plt.show()
|
|
```
|
|
|
|
## 下载这个示例
|
|
|
|
- [下载python源码: voxels_rgb.py](https://matplotlib.org/_downloads/voxels_rgb.py)
|
|
- [下载Jupyter notebook: voxels_rgb.ipynb](https://matplotlib.org/_downloads/voxels_rgb.ipynb) |