手机版
你好,游客 登录 注册
背景:
阅读新闻

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

[日期:2019-12-23] 来源:Linux公社  作者:醉落红尘 [字体: ]

该程序通过绘制树干(最初是树;后来是树枝)并递归地添加树来绘制“树”。 使用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 生成漂亮的分形树图片

关注Linux公社微信公众号(linuxidc_com),(见https://www.linuxidc.com/Linux/2013-12/93755.htm)发送“分形树”即可获得本文Python代码。

更多Python相关信息见Python 专题页面 https://www.linuxidc.com/topicnews.aspx?tid=17

Linux公社的RSS地址https://www.linuxidc.com/rssFeed.aspx

本文永久更新链接地址https://www.linuxidc.com/Linux/2019-12/161794.htm

linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款