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中正则的使用指南

上一次很多朋友写文字屏蔽说到要用正则表达,其实不是我不想用(我正则用得不是很多,看过我之前爬虫的都知道,我直接用BeautifulSoup的网页标签去找内容,因为容易理解也方便,),而是...

使用Python搭建虚拟环境的配置方法

python 的虚拟环境可以为一个 python 项目提供独立的解释环境、依赖包等资源,既能够很好的隔离不同项目使用不同 python 版本带来的冲突,而且还能方便项目的发布。 virt...

python3+opencv3识别图片中的物体并截取的方法

如下所示: 运行环境:python3.6.4 opencv3.4.0 # -*- coding:utf-8 -*- """ Note: 使用Python和OpenCV检测...

Python中利用原始套接字进行网络编程的示例

在实验中需要自己构造单独的HTTP数据报文,而使用SOCK_STREAM进行发送数据包,需要进行完整的TCP交互。 因此想使用原始套接字进行编程,直接构造数据包,并在IP层进行发送,即采...

python实现AES加密和解密

一、前言 AES,高级加密标准(英语:Advanced Encryption Standard)。是用来替代DES,目前比较流行的加密算法。 它是一种对称加密算法,与上一篇博文提到过的...