Python 3 使用Pillow生成漂亮的分形树图片

yipeiwu_com5年前Python基础

该程序通过绘制树干(最初是树;后来是树枝)并递归地添加树来绘制“树”。 使用Pillow。

利用递归函数绘制分形树(fractal tree),分形几何学的基本思想:客观事物具有自相似的层次结构,局部与整体在形态、功能、信息、时间、空间等方面具有统计意义上的相似性,成为自相似性。自相似性是指局部是整体成比例缩小的性质。

版本:Python 3

# Adapted from http://rosettacode.org/wiki/Fractal_tree#Python
# to parameterise, and add colour.
# http://pillow.readthedocs.org/
# Author: Alan Richmond, Python3.codes, and others (Rosettacode)
import math, colorsys
from PIL import Image, ImageDraw
spread = 17     # how much branches spread apart
width, height = 1000, 800 # window size
maxd = 12     # maximum recursion depth
len = 9.0     # branch length factor
# http://pillow.readthedocs.org/en/latest/reference/Image.html
img = Image.new('RGB', (width, height))
# http://pillow.readthedocs.org/en/latest/reference/ImageDraw.html
d = ImageDraw.Draw(img)
# This function calls itself to add sub-trees
def drawTree(x1, y1, angle, depth):
 if depth > 0:
  #  compute this branch's next endpoint
  x2 = x1 + int(math.cos(math.radians(angle)) * depth * len)
  y2 = y1 + int(math.sin(math.radians(angle)) * depth * len)
  # https://docs.python.org/2/library/colorsys.html
  (r, g, b) = colorsys.hsv_to_rgb(float(depth) / maxd, 1.0, 1.0)
  R, G, B = int(255 * r), int(255 * g), int(255 * b)
  #  draw the branch
  d.line([x1, y1, x2, y2], (R, G, B), depth)
  #  and append 2 trees by recursion
  drawTree(x2, y2, angle - spread, depth - 1)
  drawTree(x2, y2, angle + spread, depth - 1)
# Start drawing!
drawTree(width / 2, height * 0.9, -90, maxd)
img.show()
img.save("www.linuxidc.com.png", "PNG")

效果图如下:

总结

以上所述是小编给大家介绍的Python 3 使用Pillow生成漂亮的分形树图片,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

相关文章

在Python中获取两数相除的商和余数方法

方法一:可以使用//求取两数相除的商、%求取两数相除的余数。[/在Python中获取的是相除的结果,一般为浮点数] 方法二:使用divmod()函数,获取商和余数组成的元祖 实例代码:...

Python进程间通信Queue消息队列用法分析

本文实例讲述了Python进程间通信Queue消息队列用法。分享给大家供大家参考,具体如下: 进程间通信-Queue Process之间有时需要通信,操作系统提供了很多机制来实现进程间的...

python+influxdb+shell编写区域网络状况表

python+influxdb+shell编写区域网络状况表

本文为大家分享了python+influxdb+shell写一个区域网络状况表,供大家参考,具体内容如下 shell脚本部分: ex:就是ping 各个目的ip10个包,然后获取丢包率...

python range()函数取反序遍历sequence的方法

python中的range函数取反序有两种方式 第一种:先构建一个列表,然后对列表中的元素进行反转。 例如: a=range(5) for i in reversed(a):...

Python列表切片操作实例总结

本文实例讲述了Python列表切片操作。分享给大家供大家参考,具体如下: 切片指的是列表的一部分。 1 基本用法 指定第一个元素和最后一个元素的索引,即可创建切片 。Python 会在到...