如何在Python中更改像素颜色

时间:2014-04-16 09:16:35

标签: python python-imaging-library

如何更改不在预定义列表中的图像中某些像素的颜色? 我试过这样的事情:

from PIL import Image
picture = Image.open("// location")

imshow (picture)

_colors = [[0, 128, 0], [128, 128, 0], [128, 128, 128], [192, 128, 0], [128, 64, 0],    [0, 192, 0], [128, 64, 128], [0, 0, 0]]
 width, height = picture.size

for x in range(0, width-1):
 for y in range(0, height-1):
  current_color = picture.getpixel( (x,y) )
  if current_color!= _colors[0] and current_color!= _colors[1] and current_color!= _colors[2] and current_color!= _colors[3] and current_color!= _colors[4] and  current_color!= _colors[5] and current_color!= _colors[6] and current_color!= _colors[7]:
   picture.putpixel( (x,y), (0, 0, 0))

  imshow (picture)

我想让一些像素变成黑色,但不知怎的,这将完全返回黑色图像

2 个答案:

答案 0 :(得分:0)

这一行:

if current_color!= _colors[0] and current_color!= _colors[1] and current_color!= _colors[2] and current_color!= _colors[3] and current_color!= _colors[4] and  current_color!= _colors[5] and current_color!= _colors[6] and current_color!= _colors[7]:

始终返回True,因此您将遍历整个图片,将其更改为黑色。 getpixel返回一个元组:

>>> print picture.getpixel((1, 1))
   (79, 208, 248)

并将其与列表([0,128,0])进行比较。它们不一样:

>>> (1,2,3) == [1,2,3]
False

colors更改为元组列表而不是列表列表。

答案 1 :(得分:0)

保持像素数据的类型相同,并缩短if" in"

的if语句
import Image
filename ="name.jpg"

picture = Image.open(filename, 'r')
_colors = [(0, 128, 0), (128, 128, 0), (128, 128, 128), (192, 128, 0), (128, 64, 0), (0, 192, 0), (128, 64, 128), (0, 0, 0)]
width, height = picture.size

for x in range(0, width):
    for y in range(0, height):
        current_color = picture.getpixel((x,y))
        if current_color in _colors:
            picture.putpixel((x,y), (0, 0, 0))

picture.show()