Python如何生成树形图案
作者:oldjwu 发布时间:2022-11-17 03:39:58
标签:Python,树形图案
本文实例为大家分享了Python生成树形图案的具体代码,供大家参考,具体内容如下
先看一下效果,见下图。
上面这颗大树是使用Python + Tkinter绘制的,主要原理为使用分形画树干、树枝,最终叶节点上画上绿色圆圈代表树叶。当然,为了看起来更真实,绘制过程中也加入了一些随机变化,比如树枝会稍微有些扭曲而不是一条直线,分叉的角度、长短等都会随机地作一些偏移等。
以下是完整源代码:
# -*- coding: utf-8 -*-
import Tkinter
import sys, random, math
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return "<Point>: (%f, %f)" % (self.x, self.y)
class Branch(object):
def __init__(self, bottom, top, branches, level = 0):
self.bottom = bottom
self.top = top
self.level = level
self.branches = branches
self.children = []
def __str__(self):
s = "Top: %s, Bottom: %s, Children Count: %d" % /
(self.top, self.bottom, len(self.children))
return s
def nextGen(self, n = -1, rnd = 1):
if n <= 0: n = self.branches
if rnd == 1:
n = random.randint(n / 2, n * 2)
if n <= 0: n = 1
dx = self.top.x - self.bottom.x
dy = self.top.y - self.bottom.y
r = 0.20 + random.random() * 0.2
if self.top.x == self.bottom.x:
# 如果是一条竖线
x = self.top.x
y = dy * r + self.bottom.y
elif self.top.y == self.bottom.y:
# 如果是一条横线
x = dx * r + self.bottom.x
y = self.top.y
else:
x = dx * r
y = x * dy / dx
x += self.bottom.x
y += self.bottom.y
oldTop = self.top
self.top = Point(x, y)
a = math.pi / (2 * n)
for i in range(n):
a2 = -a * (n - 1) / 2 + a * i - math.pi
a2 *= 0.9 + random.random() * 0.2
self.children.append(self.mkNewBranch(self.top, oldTop, a2))
def mkNewBranch(self, bottom, top, a):
dx1 = top.x - bottom.x
dy1 = top.y - bottom.y
r = 0.9 + random.random() * 0.2
c = math.sqrt(dx1 ** 2 + dy1 ** 2) * r
if dx1 == 0:
a2 = math.pi / 2
else:
a2 = math.atan(dy1 / dx1)
if (a2 < 0 and bottom.y > top.y) /
or (a2 > 0 and bottom.y < top.y) /
:
a2 += math.pi
b = a2 - a
dx2 = c * math.cos(b)
dy2 = c * math.sin(b)
newTop = Point(dx2 + bottom.x, dy2 + bottom.y)
return Branch(bottom, newTop, self.branches, self.level + 1)
class Tree(object):
def __init__(self, root, canvas, bottom, top, branches = 3, depth = 3):
self.root = root
self.canvas = canvas
self.bottom = bottom
self.top = top
self.branches = branches
self.depth = depth
self.new()
def gen(self, n = 1):
for i in range(n):
self.getLeaves()
for node in self.leaves:
node.nextGen()
self.show()
def new(self):
self.leavesCount = 0
self.branch = Branch(self.bottom, self.top, self.branches)
self.gen(self.depth)
print "leaves count: %d" % self.leavesCount
def chgDepth(self, d):
self.depth += d
if self.depth < 0: self.depth = 0
if self.depth > 10: self.depth = 10
self.new()
def chgBranch(self, d):
self.branches += d
if self.branches < 1: self.branches = 1
if self.branches > 10: self.branches = 10
self.new()
def getLeaves(self):
self.leaves = []
self.map(self.findLeaf)
def findLeaf(self, node):
if len(node.children) == 0:
self.leaves.append(node)
def show(self):
for i in self.canvas.find_all():
self.canvas.delete(i)
self.map(self.drawNode)
self.canvas.tag_raise("leaf")
def exit(self, evt):
sys.exit(0)
def map(self, func = lambda node: node):
# 遍历树
children = [self.branch]
while len(children) != 0:
newChildren = []
for node in children:
func(node)
newChildren.extend(node.children)
children = newChildren
def drawNode(self, node):
self.line2(
# self.canvas.create_line(
node.bottom.x,
node.bottom.y,
node.top.x,
node.top.y,
fill = "#100",
width = 1.5 ** (self.depth - node.level),
tags = "branch level_%d" % node.level,
)
if len(node.children) == 0:
# 画叶子
self.leavesCount += 1
self.canvas.create_oval(
node.top.x - 3,
node.top.y - 3,
node.top.x + 3,
node.top.y + 3,
fill = "#090",
tag = "leaf",
)
self.canvas.update()
def line2(self, x0, y0, x1, y1, width = 1, fill = "#000", minDist = 10, tags = ""):
dots = midDots(x0, y0, x1, y1, minDist)
dots2 = []
for i in range(len(dots) - 1):
dots2.extend([dots[i].x,
dots[i].y,
dots[i + 1].x,
dots[i + 1].y])
self.canvas.create_line(
dots2,
fill = fill,
width = width,
smooth = True,
tags = tags,
)
def midDots(x0, y0, x1, y1, d):
dots = []
dx, dy, r = x1 - x0, y1 - y0, 0
if dx != 0:
r = float(dy) / dx
c = math.sqrt(dx ** 2 + dy ** 2)
n = int(c / d) + 1
for i in range(n):
if dx != 0:
x = dx * i / n
y = x * r
else:
x = dx
y = dy * i / n
if i > 0:
x += d * (0.5 - random.random()) * 0.25
y += d * (0.5 - random.random()) * 0.25
x += x0
y += y0
dots.append(Point(x, y))
dots.append(Point(x1, y1))
return dots
if __name__ == "__main__":
root = Tkinter.Tk()
root.title("Tree")
gw, gh = 800, 600
canvas = Tkinter.Canvas(root,
width = gw,
height = gh,
)
canvas.pack()
tree = Tree(root, canvas, Point(gw / 2, gh - 20), Point(gw / 2, gh * 0.2), /
branches = 2, depth = 8)
root.bind("n", lambda evt: tree.new())
root.bind("=", lambda evt: tree.chgDepth(1))
root.bind("+", lambda evt: tree.chgDepth(1))
root.bind("-", lambda evt: tree.chgDepth(-1))
root.bind("b", lambda evt: tree.chgBranch(1))
root.bind("c", lambda evt: tree.chgBranch(-1))
root.bind("q", tree.exit)
root.mainloop()
因为每次生成的树都是随机的,所以你生成的树和上图会不太一样,可能会更为枝繁叶茂,也可能会看起来才刚刚发芽。程序中绑定了若干快捷键,比如“n”是随机产生一颗新的树,“q”是退出程序。另外还有一些不太常用的快捷键,如“+”/“-”是增加/减少树的深度,“b”/“c”分别代表更多/更少的分叉,需要注意的是,增加深度或分叉可能需要更多的计算时间。
从这次树形图案的绘制过程中,我也有一些有趣的发现,比如,树枝上某一处的横截面宽度与它与树根之间的距离似乎呈一种指数函数的关系。如用H表示树的总高度,h表示树枝上某一点的高度,w表示这一点横截面的宽度,那么w与h之间似乎存在这样一种关系:w = a * b ^ (H - h) + c,这儿a、b、c都是常数。当然,这只是一个猜测,因为绘制的过程中我发现当w与h满足这样关系时画出来的图案看起来最“自然”,这个问题或许下次可以再深入研究一下。
来源:http://blog.csdn.net/oldjwu/article/details/4651146
0
投稿
猜你喜欢
- python turtle自定义画布背景色turtle是python一个简单好用的绘图包,它可以通过设计坐标来实时控制绘图。安装很简单,一行
- 前言每个人写脚本时的格式都会有所不同,有的会注明脚本本身的一些信息,有的则开门见山,这在小团队里其实没什么,基本别人做什么你也都知道,但如果
- 我们选择一种问题的解决办法,通常需要考虑到想要达到的效果,还有最重要的是这个办法本身的优缺点有哪些,与其他的方法对比哪一个更好。之前小编之前
- 以下保存成 App.xml , 与asp文件放在相同目录下! 代码如下: <?xml version="1.0"
- 由于最近需要使用爬虫爬取数据进行测试,所以开始了爬虫的填坑之旅,那么首先就是先系统的学习下关于正则相关的知识啦。所以将下面正则方面的知识点做
- 如下所示:# 返回一个列表中第二大的数def second(ln):max = 0s = {}for i in range(len(ln))
- 之前做的一些项目中涉及到feature map 可视化的问题,一个层中feature map的数量往往就是当前层out_channels的值
- 1、Linux主机重定向 Godaddy的Liunx主机,Godaddy本身已经支持Apache,所以直接创建一个.htaccess文件就可
- 本文实例讲述了Python3模拟登录操作。分享给大家供大家参考,具体如下:模拟登录_要求:1. 用户输入账号密码进行登录2. 用户信息保存在
- 根据 Dotzler 的统计,IE6 的份额正在缩水,这可能是 2009 年本人听到的第一个好消息。于此同时,Gmail 的浏览器支持列表中
- 本文实例讲述了Python面向对象程序设计类的多态用法。分享给大家供大家参考,具体如下:多态1、多态使用一种事物的多种体现形式,举例:动物有
- 使用cookie来判断来访者身份,是否是首次登陆, asp代码实例如下:< %@ LANGUAGE=&q
- 1、TCP连接的建立方法客户端在建立一个TCP连接时一般需要两步,而服务器的这个过程需要四步,具体见下面的比较。步骤TCP客户端TCP服务器
- numpy.amin()和numpy.amax()numpy.amin()用于计算数组中元素沿着指定轴的最小值。numpy.amax()用于
- 一、什么是索引 减少磁盘I/O和逻辑读次数的最佳方法之一就是使用【索引】 索引允许SQL Server在表中查找数据而不需要扫描整个表。 1
- 首先是对一元函数求积分,使用Scipy下的integrate函数:from scipy import integratedef g(x):
- 大家好,我是不学前端的前端程序员,事情是这个样子的,前几天不是双十一预购秒杀嘛由于我女朋友比较笨,手速比较慢,就一直抢不到,她没抢到特价商品
- 一个等号 =:表示赋值 ;两个等号 ==:先转换类型再比较 ;三个等号 ===:先判断类型,如果不是同一类型直接false。
- 起因:有一批数据需要每个月进行分析,数据存储在excel中,行标题一致,需要横向合并进行分析。数据示意:具有多个代码:# -*- codin
- 本文介绍了几种常用的python下载文件的方法,具体使用到了htttplib2,urllib等包,希望对大家有帮忙。1.简单文件下载使用ht