将像素与PIL结合

2024-09-27 00:15:53 发布

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

我是新手。 我尝试使用随机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)值的pic


Tags: inimageimportimgsizepilrangerandom

热门问题