[英]How to fix “IndexError: image index out of range”?
I am writing this code for a problem in Automate the Boring Stuff with Python. 我在用Python自动完成无聊的东西中编写此代码是为了解决这个问题。 The code is supposed to create a new image that is all black, then put an off-white rectangle in the center of it, leaving a black border.
该代码应创建一个全黑的新图像,然后在其中心放置一个灰白色矩形,并留一个黑色边框。 In testing this section of code, I get an error
IndexError: image index out of range
on the last line in the code excerpt below. 在测试此部分代码时,在下面的代码摘录的最后一行中,我收到错误
IndexError: image index out of range
。
I have found many other questions addressing this error message, but none of the solutions seem related. 我发现了许多其他问题可以解决此错误消息,但似乎没有解决方案。 The range of pixels I am asking to color seems to be inside the rectangle of the image.
我要着色的像素范围似乎在图像的矩形内。 I feel like I'm missing something really simple here.
我觉得我在这里错过了一些非常简单的事情。
baseIm = Image.new('RGBA', (298, 370), 'black')
for x in range(5, 365):
for y in range(5, 293):
baseIm.putpixel((x, y), (239, 222, 205))
Your image is 298 pixels wide (dimension x) and 370 pixels tall (dimension y). 您的图像宽298像素(尺寸x),高370像素(尺寸y)。 The code goes out of range because it tries to set pixels outside the image -- you make
x
go through range(5, 365)
. 该代码超出范围,因为它尝试设置图像外部的像素-您使
x
穿过range(5, 365)
。
Why don't you use baseIm.width
and baseIm.height
in your code? 为什么不在代码中使用
baseIm.width
和baseIm.height
? Like this: 像这样:
baseIm = Image.new('RGBA', (370, 298), 'black')
for x in range(5, baseIm.width-5):
for y in range(5, baseIm.height-5):
baseIm.putpixel((x,y), (239, 222, 205))
Yes, you did a small mistake, you swapped the column loop and row loop control values. 是的,您犯了一个小错误,交换了列循环和行循环控制值。 interchange the limit of both range methods of loop x and y.
互换循环x和y的两种范围方法的极限。
baseIm = Image.new('RGBA', (298, 370), 'black')
for x in range(5, 293):
for y in range(5, 365):
baseIm.putpixel((x, y), (239, 222, 205))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.