您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

问题是,正如您所说,您的图像是 ,因此在此行上:

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

这是对比结果:

在此处输入图片说明

您可能要考虑使用 “ Look Up Table” 或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')

结果-拉伸对比度后:

在此处输入图片说明

上面我可能有点冗长,所以如果您喜欢更简洁的代码

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')
python 2022/1/1 18:45:35 有306人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶