图像索引超出范围PIL

2024-04-29 08:33:38 发布

您现在位置:Python中文网/ 问答频道 /正文

这个程序创建一个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")

因此,用#注释的行基本上不起作用,导致以下错误:

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


Tags: inimglinex1x2y1x3x4