Python 3 使用Pillow生成漂亮的分形樹圖片
該程序通過繪制樹干(最初是樹;后來是樹枝)并遞歸地添加樹來繪制“樹”。 使用Pillow。
利用遞歸函數(shù)繪制分形樹(fractal tree),分形幾何學(xué)的基本思想:客觀事物具有自相似的層次結(jié)構(gòu),局部與整體在形態(tài)、功能、信息、時(shí)間、空間等方面具有統(tǒng)計(jì)意義上的相似性,成為自相似性。自相似性是指局部是整體成比例縮小的性質(zhì)。
版本: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")
效果圖如下:
總結(jié)
以上所述是小編給大家介紹的Python 3 使用Pillow生成漂亮的分形樹圖片,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時(shí)回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!
相關(guān)文章
pyqt5使用按鈕進(jìn)行界面的跳轉(zhuǎn)方法
今天小編就為大家分享一篇pyqt5使用按鈕進(jìn)行界面的跳轉(zhuǎn)方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-06-06Python Tkinter模塊 GUI 可視化實(shí)例
今天小編就為大家分享一篇Python Tkinter模塊 GUI 可視化實(shí)例,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11基于Python實(shí)現(xiàn)體育彩票選號器功能代碼實(shí)例
這篇文章主要介紹了基于Python實(shí)現(xiàn)體育彩票選號器功能代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-09-09