在Python上使用PIL更改像素颜色

时间:2018-05-29 09:24:17

标签: python image loops python-imaging-library

我对编程非常陌生,而且我正在学习更多关于使用PIL进行图像处理的知识。

我有一项任务要求我用其他颜色更改每个特定像素的颜色。由于我需要更改几个像素,因此我创建了一个for循环来访问每个像素。脚本"工作"至少,结果只是每个像素中有一个(0,0,0)颜色的黑色屏幕。

from PIL import Image
img = Image.open('/home/usr/convertimage.png')
pixels = img.load()
for i in range(img.size[0]):
    for j in range(img.size[1]):
            if pixels[i,j] == (225, 225, 225):
                pixels[i,j] = (1)
            elif pixels[i,j] == (76, 76, 76):
                pixels [i,j] = (2)
            else: pixels[i,j] = (0)
img.save('example.png')

我的图像是灰度图像。有特定的颜色,边框附近有渐变色。我试图用另一种颜色替换每种特定颜色,然后用另一种颜色替换渐变颜色。

然而,对于我的生活,我不明白为什么我的输出会出现单一(0,0,0)颜色。

我试图在线和朋友寻找答案,但无法提出解决方案。

如果有人知道我做错了什么,任何反馈都会受到高度赞赏。提前谢谢。

1 个答案:

答案 0 :(得分:2)

问题在于,正如您所说,您的图片是灰度,所以在这一行:

if pixels[i,j] == (225, 225, 225):

没有像素将等于RGB三元组(255,255,255),因为白色像素将只是灰度值255而不是RGB三元组。

如果将循环更改为:

,它可以正常工作
        if pixels[i,j] == 29:
            pixels[i,j] = 1
        elif pixels[i,j] == 179:
            pixels [i,j] = 2
        else:
            pixels[i,j] = 0

这是对比度拉伸的结果:

enter image description here

您可能会考虑使用“查找表”或LUT进行转换,因为大量if语句可能会变得难以处理。基本上,图像中的每个像素都被替换为通过在表中查找其当前索引而找到的新像素。我正在使用numpy来做这件事:

#!/usr/local/bin/python3
import numpy as np
from PIL import Image

# Open the input image
PILimage=Image.open("classified.png")

# Use numpy to convert the PIL image into a numpy array
npImage=np.array(PILimage)

# Make a LUT (Look-Up Table) to translate image values. Default output value is zero.
LUT=np.zeros(256,dtype=np.uint8)
LUT[29]=1    # all pixels with value 29, will become 1
LUT[179]=2   # all pixels with value 179, will become 2

# Transform pixels according to LUT - this line does all the work
pixels=LUT[npImage];

# Save resulting image
result=Image.fromarray(pixels)
result.save('result.png')

结果 - 拉伸对比后:

enter image description here

我上面可能有点冗长,所以如果你想要更简洁的代码:

import numpy as np
from PIL import Image

# Open the input image as numpy array
npImage=np.array(Image.open("classified.png"))

# Make a LUT (Look-Up Table) to translate image values
LUT=np.zeros(256,dtype=np.uint8)
LUT[29]=1    # all pixels with value 29, will become 1
LUT[179]=2   # all pixels with value 179, will become 2

# Apply LUT and save resulting image
Image.fromarray(LUT[npImage]).save('result.png')
相关问题