使用PIL放置像素会产生错误

时间:2016-09-10 19:34:07

标签: python python-imaging-library

新手在这里。 我试图用随机RGB颜色放置一些像素(比如添加噪声):

from PIL import Image
import random
img=Image.open('pic.bmp')
randomenter=int(input('Enter numpix: '))
for numpix in range(0, randomenter):
    x=random.randint(0,int(img.size[0]))
    y=random.randint(0,int(img.size[1]))
    r=random.randint(0,255)
    g=random.randint(0,255)
    b=random.randint(0,255)
    img.putpixel((x,y),(r,g,b))
img.show()

randomenter=100它有时会起作用。值越高,我就会收到错误:

Traceback (most recent call last):
  File "D:\study\7sem\GiMS\labs\1laba\123.py", line 11, in <module>
    img.putpixel((x,y),(r,g,b))
  File "C:\Python34\lib\site-packages\pillow-3.3.1-py3.4-win-amd64.egg\PIL\Image.py", line 1512, in putpixel
    return self.im.putpixel(xy, value)
IndexError: image index out of range

我做错了什么? (800, 500)值为

的图片

1 个答案:

答案 0 :(得分:0)

如何发布@ŁukaszRogalsk,它通过修改xyimg.size[0]-1img.size[1]-1来解决