如何在Python中更改像素颜色

0 投票
2 回答
1731 浏览
提问于 2025-04-18 02:56

如何只改变图像中某些像素的颜色,而这些像素并不在一个预先定义的列表中呢?

我尝试了类似这样的代码:

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

保持像素数据的类型一致,并用“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()
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 改成一个元组的列表,而不是列表的列表。

撰写回答