python - PIL 的舍入误差

标签 python python-3.x numpy python-imaging-library

我在使用 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/

相关文章:

python - 如何在Google colab中更改Keras/tensorflow版本?

python - 是否可以在 Celery 中为每个队列分别设置 "worker_prefetch_multiplier"?

python - 在python中将罗马数字转换为整数

python - 如何使用 python 匹配文本文件中的单词?

python - Django 不以存储格式返回日期时间值

python - 在 numpy 二维数组上 - 当 N 改变行时如何将每行中的最后 N 个数组元素设置为零

python - 在 pandas 数据框中查找每行的两个列列表中哪一个是真的最快方法

python - 如何分离等于阈值的灰度图像区域?

python - 队列仍然未知或只是不知道如何调用它们

python - 无法在centos上执行python.3.5.1