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实现全排列的打印的代码,供大家参考,具体如下 问题:输入一个数字:3,打印它的全排列组合:123 132 213 231 312 321,并进行统计个数。 下...

Python实现二叉树前序、中序、后序及层次遍历示例代码

前言 树是数据结构中非常重要的一种,主要的用途是用来提高查找效率,对于要重复查找的情况效果更佳,如二叉排序树、FP-树。另外可以用来提高编码效率,如哈弗曼树。 用 Python 实现树...

跟老齐学Python之坑爹的字符编码

跟老齐学Python之坑爹的字符编码

字符编码,在编程中,是一个让学习者比较郁闷的东西,比如一个str,如果都是英文,好说多了。但恰恰不是如此,中文是我们不得不用的。所以,哪怕是初学者,都要了解并能够解决字符编码问题。...

通过数据库向Django模型添加字段的示例

首先借用书本(book)的这个数据模型: from django.db import models class Publisher(models.Model): name =...

Python实现扫描指定目录下的子目录及文件的方法

本文介绍了使用Python来扫描指定目录下的文件,或者匹配指定后缀和前缀的函数。步骤如下: 如果要扫描指定目录下的文件,包括子目录,需要调用scan_files("/export/hom...