溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

如何在Python 3中使用Pillow生成一個(gè)分形樹(shù)圖片

發(fā)布時(shí)間:2021-03-22 17:16:00 來(lái)源:億速云 閱讀:148 作者:Leah 欄目:開(kāi)發(fā)技術(shù)

這篇文章給大家介紹如何在Python 3中使用Pillow生成一個(gè)分形樹(shù)圖片,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對(duì)大家能有所幫助。

該程序通過(guò)繪制樹(shù)干(最初是樹(shù);后來(lái)是樹(shù)枝)并遞歸地添加樹(shù)來(lái)繪制“樹(shù)”。 使用Pillow。

利用遞歸函數(shù)繪制分形樹(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")

關(guān)于如何在Python 3中使用Pillow生成一個(gè)分形樹(shù)圖片就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI