尝试绘制 Mandelbrot 集 - 无论如何,总是得到纯黑色图像

Trying to plot Mandelbrot set - no matter what, always get plain black image

首先,这是我的代码:

from PIL import Image as im
import numpy as np 

def mandelbrot_iteration(c): 
    iters = 0
    while abs(c)<2 and iters<200:
        c=c**2+c
        iters+=1
    return iters

HEIGHT = 400
WIDTH = 500

diag = im.new('L',(WIDTH, HEIGHT))
pix = diag.load()

x_pts = np.arange(-2,2,4/WIDTH)  
y_pts = np.arange(-2,2,4/HEIGHT)

for x in x_pts:
    for y in y_pts:
        pix[x+2,y+2]=mandelbrot_iteration(complex(x,y))

diag.save("Fractal.png")

我认为这很简单。我看到复数网格上的每个点需要多少次交互才能超过 abs。 2 的值并将这些值绘制为每个点的颜色(200 是截止值,假设序列不发散)。在指定的范围内,肯定会发生一些不平凡的事情,但无论我尝试什么,制作的图像都是纯黑色的。

此外,这种生成图像的方法的文档几乎为零。我搜索了很多,这个:

im.load()

Allocates storage for the image and loads it from the file (or from the source, for lazy operations). In normal cases, you don’t need to call this method, since the Image class automatically loads an opened image when it is accessed for the first time.

(New in 1.1.6) In 1.1.6 and later, load returns a pixel access object that can be used to read and modify pixels. The access object behaves like a 2-dimensional array, so you can do:

pix = im.load() print pix[x, y] pix[x, y] = value

Access via this object is a lot faster than getpixel and putpixel

是我能找到的一切(也没有示例),这非常令人沮丧。我想 pix[x+2,y+2] 行有问题。 '+2' 用于阻止 "out of range" 错误,但是,在尝试了一些示例后,我不知道它如何处理输入数字以生成颜色。我确实发现 'L' 在创建图像时应该制作灰度图像,但不知道 pix[x,y] 期望的范围或任何东西。一切都变黑了...

眼前的问题是您的 scale 已关闭。

在这一行 pix[x+2,y+2]=... 中,使用 xy 的范围,唯一绘制的像素是 0..4。由于最后绘制的几个像素是黑色的,所以整个左上角的 4x4 方块都是黑色的(其余为 0 - 也是黑色 - 默认情况下,对于新图像)。

可以这样解决:

from PIL import Image as im
import numpy as np 

def mandelbrot_iteration(c): 
    iters = 0
    while abs(c)<2 and iters<200:
        c=c**2+c
        iters+=1
    return iters

HEIGHT = 400
WIDTH = 500

diag = im.new('L',(WIDTH, HEIGHT))
pix = diag.load()

x_pts = np.arange(-2,2,4.0/WIDTH)  
y_pts = np.arange(-2,2,4.0/HEIGHT)

for x in x_pts:
    for y in y_pts:
        pix[WIDTH*(x+2)/4.0,HEIGHT*(y+2)/4.0]=mandelbrot_iteration(complex(x,y))

diag.show()

虽然结果还不是很好的Mandelbrot...

应用 hcs 的评论 "mandelbrot iteration should be z=0, while abs(z)<2, z=z**2+c",您将使用此代码

from PIL import Image as im
import numpy as np 

def mandelbrot_iteration(c): 
    iters = 0
    z = 0
    while abs(z)<2 and iters<200:
        z=z**2+c
        iters+=1
    return iters

HEIGHT = 400
WIDTH = 500

diag = im.new('L',(WIDTH, HEIGHT))
pix = diag.load()

x_pts = np.arange(-2,2,4.0/WIDTH)  
y_pts = np.arange(-2,2,4.0/HEIGHT)

for x in x_pts:
    for y in y_pts:
        pix[WIDTH*(x+2)/4.0,HEIGHT*(y+2)/4.0]=mandelbrot_iteration(complex(x,y))

# diag.show()
diag.save("Fractal.png")

你瞧,一个真正的 Mandelbrot 弹出: