我目前正在使用PhotoImage和tkinter逐像素绘制Mandelbrot集。我基本上是直接使用没有修改的算法。有没有使计算更快的方法?也许快速填充大面积的颜色,或者预先计算常数?

部分代码:

ITERATIONS = 50
WIDTH, HEIGHT = 600, 600
CENTER = (-.5, 0)
DIAMETER = 2.5

def mandel(c):
    z = 0
    for i in range(ITERATIONS):
        z = z**2 + c
        if abs(z) > 2:
            return i
    return ITERATIONS

root = Tk()
canvas = Canvas(root, width=WIDTH,height=HEIGHT)
canvas.pack()
img = PhotoImage(width=WIDTH, height=HEIGHT)
canvas.create_image((WIDTH/2, HEIGHT/2), image=img, state="normal")


real = CENTER[0] - 0.5 * DIAMETER
imag = CENTER[1] - 0.5 * DIAMETER

def color(i):
    colors = ("#0000AA", "#88DDFF", "#FF8800", "#000000")
    if i == ITERATIONS:
        return colors[-1]
    else:
        choice = (i//2) % len(colors)
    return colors[choice]

for x in range(WIDTH):
    for y in range(HEIGHT):
        i = mandel(complex(real, imag))

        img.put(color(i), (x, HEIGHT-y))

        imag += DIAMETER / HEIGHT
    imag = CENTER[1] - 0.5 * DIAMETER
    real += DIAMETER / WIDTH

mainloop()

最佳答案

一次设置一个像素可能是减速的主要来源。代替为每个像素调用put,计算机要整行像素或整个像素矩阵,然后在循环结束时调用一次。

您可以在这里找到示例,以及其他地方:https://web.archive.org/web/20170512214049/http://tkinter.unpythonic.net:80/wiki/PhotoImage#Fill_Many_Pixels_at_Once

关于python - 如何更快地渲染Mandelbrot集?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26447915/

10-12 18:23