如何在Python中更改像素颜色

2024-05-20 23:00:54 发布

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

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

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)

我只想让一些像素变黑,但不知怎么的,这会返回一个黑色的图像


Tags: andin图像image列表forrange像素
2条回答

这条线:

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返回一个元组:

^{pr2}$

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

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

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

保持像素数据的类型不变,并用“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()

相关问题 更多 >