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

寻求可生成万花筒图形的Python模块,Plotly尝试无果

生成万花筒风格图形的Python工具方案

1. Matplotlib + 自定义几何变换(适配Voronoi类万花筒)

Matplotlib结合SciPy的Voronoi模块,叠加旋转变换就能实现你示例中的效果。核心思路是先生成基础图形单元,再通过旋转复制出对称单元,拼接成万花筒:

import matplotlib.pyplot as plt
from scipy.spatial import Voronoi
import numpy as np

# 生成随机Voronoi点集,控制点在中心区域避免超出画布
points = np.random.rand(12, 2) * 0.8 + 0.1
vor = Voronoi(points)

# 设置6次旋转对称,可调整为3/4/8等不同次数
symmetry_num = 6
angle_step = 2 * np.pi / symmetry_num

fig, ax = plt.subplots(figsize=(8, 8))
ax.set_aspect('equal')
plt.axis('off')

# 绘制基础Voronoi单元
for region in vor.regions:
    if -1 not in region and len(region) > 0:
        polygon = vor.vertices[region]
        ax.fill(*zip(*polygon), alpha=0.8)

# 旋转复制单元生成万花筒效果
for i in range(1, symmetry_num):
    rot_matrix = np.array([
        [np.cos(i * angle_step), -np.sin(i * angle_step)],
        [np.sin(i * angle_step), np.cos(i * angle_step)]
    ])
    rotated_verts = vor.vertices @ rot_matrix.T
    for region in vor.regions:
        if -1 not in region and len(region) > 0:
            polygon = rotated_verts[region]
            ax.fill(*zip(*polygon), alpha=0.8)

plt.tight_layout()
plt.show()

2. Pycairo(高精度2D图形渲染)

如果需要更精细的图形控制,比如平滑边缘、复杂裁剪,Pycairo是更优选择。它支持路径变换、蒙版裁剪,能精准控制每个对称单元的绘制范围:

  • 先绘制单个扇形区域内的基础图形,再通过旋转变换将该区域复制到整个画布的对称位置
  • 配合cairo.Matrix实现旋转、缩放等变换,确保图形对齐精准

安装命令:pip install pycairo

3. Pillow(图像后处理式生成)

如果已经有了基础图形,比如导出的Voronoi图,可以用Pillow对图像做对称拼接,快速生成万花筒效果:

from PIL import Image

# 读取已生成的基础图形
base_img = Image.open("base_voronoi.png").convert("RGBA")
w, h = base_img.size
center = (w // 2, h // 2)
symmetry = 6

kaleido = Image.new("RGBA", (w, h))

for i in range(symmetry):
    rotated = base_img.rotate(360 // symmetry * i, center=center)
    kaleido.paste(rotated, (0, 0), mask=rotated)

kaleido.save("kaleido_result.png")

针对你使用Plotly失败的补充建议

Plotly核心定位是交互式可视化,对这种需要自定义几何对称变换的静态万花筒图形支持有限,更适合用上述专注于2D图形渲染/变换的工具。如果一定要用Plotly,可尝试先生成基础图形,再通过figure.add_shape()手动添加旋转后的图形元素,但效率和灵活性远不如Matplotlib或Pycairo。


内容的提问来源于stack exchange,提问作者Gago-Silva

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 17:50:43