我在使用 Mandelbrot 程序写入图像时遇到问题;它与第 31 行“(maxx-minx)/width”与“(maxy-miny)/width”相比的舍入误差有关,这会导致 501 x 500 的图片而不是 500 平方的图片。 ((宽度+1)*长度)而不是(宽度*长度)。 我该如何解决这个问题?
from PIL import Image
from cmath import *
from math import sqrt
from numpy import arange
width = 500
height = 500
minx = -0.752 #float(input("Please enter the minimum x value:"))
maxx = -0.748 #float(input("Please enter the maximum x value:"))
miny = 0.098 #float(input("Please enter the minimum y value:"))
maxy = 0.102 #float(input("Please enter the maximum y value:"))
gradient = Image.open("mandelbrot.png")
gradlist = list(gradient.getdata())
def testMandelbrot(x, y):
z = 0 + 0j
c = x + (y*1j)
iter = 0
while iter <= 69 and sqrt(z.real**2 + z.imag**2) < 4:
z = (z*z) + c
iter += 1
if iter == 70:
return (0, 0, 0, 255)
else:
return gradlist[int((iter - 1) * 140 / 70)]
img = Image.new('RGBA', (width, height), color=(255, 255, 255, 255))
image = [testMandelbrot(x, y) for y in arange(miny, maxy, (maxy-miny)/height) for x in arange(minx, maxx, (maxx-minx)/width)] #this line creates the error ((maxx-minx)/width) / (maxx - min) gives (width+1) not width
print(len(image), img.size)
img.putdata(image)
img.save("picture111.png", "PNG")
最佳答案
我建议使用numpy
's linspace
而不是arange
。它将返回一个由给定数量的均匀间隔样本组成的数组。
看到 linspace(0.098, 0.102, 500, endpoint=False)
的长度正好是 500 个点。如果要包含端点,可以省略 endpoint=False
或传递 endpoint=True
。
使用endpoint=False
,如果您生成另一个具有相同尺寸高度和宽度但偏移max_ - min_
之间差异的图像,结果将是相邻图 block ,具体取决于这将导致八个之一。
您的代码将是:
Y = linspace(miny, maxy, height, endpoint=False)
X = linspace(minx, maxx, width, endpoint=False)
image = [testMandelbrot(x, y) for y in Y for x in X]
我命名这些数组是因为 Y
被重复使用 len(X)
次,而且高度和宽度都很小 (500),因此成本不高并且有助于可读性。
关于python - PIL 的舍入误差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45653671/