图像索引超出范围 PIL

image index out of range PIL

此程序创建一个 600 x 600 图像,然后初始化四个点。 然后这四个点中的每一个向该点移动 10% 的距离 顺时针方向离他们最近。每次移动后,程序绘制 每对点之间的一条线。程序停止时点 靠得足够近了。

from PIL import Image
from math import *

# Initial white image
n=600
img = Image.new("RGB", (n, n), (255, 255, 255))

# Draws a line between (p1x, p1y) and (p2x, p2y)
def drawLine(p1x, p1y, p2x, p2y):
    t = 0.0
    while t < 1.0:
        x = int (n * (p1x + t * (p2x - p1x)))
        y = int (n * (p1y + t * (p2y - p1y)))
        img.putpixel((x, y),(0, 0, 255)) 
        t += 0.001          

# Initialize four points
P1 = (x1, y1) = (0.0, 0.0)
P2 = (x2, y2) = (1.0, 0.0)
P3 = (x3, y3) = (1.0, 1.0)
P4 = (x4, y4) = (0.0, 1.0)

# Draws lines
for counter in range(600):
    x1 = .9 * x1 + .1 * x2
    y1 = .9 * y1 + .1 * y2
    drawLine(x1, y1, x2, y2)
    x2 = .9 * x2 + .1 * x3
    y2 = .9 * y2 + .1 * y3
    drawLine(x2, y2, x3, y3) # Doesn't work
    x3 = .9 * x3 + .1 * x4
    y3 = .9 * y3 + .1 * y4
    drawLine(x3, y3, x4, y4) # Doesn't work
    x4 = .9 * x4 + .1 * x1
    y4 = .9 * y4 + .1 * y1
    drawLine(x4, y4, x1, y1)


# Saves image in Lab09.png
img.save("Lab09.png")
img.show("Lab09.png")

所以基本上用# Doesn't work 注释的行导致了这个错误:

Traceback (most recent call last):
  File "/Users/e154675/Desktop/Lab09.py", line 41, in <module>
    drawLine(x2, y2, x3, y3)
  File "/Users/e154675/Desktop/Lab09.py", line 25, in drawLine
    img.putpixel((x, y),(0, 0, 255))
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/PIL/Image.py", line 1518, in putpixel
    return self.im.putpixel(xy, value)
IndexError: image index out of range

我想知道如何解决此问题以及导致此问题的原因。 (我在使用 IDLE 的 macbook pro 上)

非常感谢你们!!! :) <3

来自 Python 文档:

exception IndexError Raised when a sequence subscript is out of range.

我会先尝试将有问题的代码块放入:except: 块中,也许尝试先打印它尝试访问的索引,然后再从那里返回。

对于 drawLine(x2, y2, x3, y3),您有 x2 = .9 * x2 + .1 * x3,其中 x2x3 最初定义为 1.0。因此,在函数调用时,x2 为 1。第一次通过 line-drawing 循环时,当 t=0.0 时,您会将 x 设置为 int (n * (p1x + t * (p2x - p1x))),计算结果为 1.0 * 600,即 600。因此,您最终会使用 x 分量为 600 的像素坐标调用 img.putpixel。在 600x600 图像上,外角位于 ( 599,599)。结果将是 IndexError。

为了验证这一理论,您可以尝试将图像放大一个像素,看看是否有帮助:

img = Image.new("RGB", (n+1, n+1), (255, 255, 255))

或者,将您的点(P1 等)移动到远离图像边缘的位置,例如将它们设为 (0.1,0.1) 和 (0.9,0.9) 或其他。