栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在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/python3import numpy as npfrom PIL import Image# Open the input imagePILimage=Image.open("classified.png")# Use numpy to convert the PIL image into a numpy arraynpImage=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 1LUT[179]=2   # all pixels with value 179, will become 2# Transform pixels according to LUT - this line does all the workpixels=LUT[npImage];# Save resulting imageresult=Image.fromarray(pixels)result.save('result.png')

结果-拉伸对比度后:


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

import numpy as npfrom PIL import Image# Open the input image as numpy arraynpImage=np.array(Image.open("classified.png"))# Make a LUT (Look-Up Table) to translate image valuesLUT=np.zeros(256,dtype=np.uint8)LUT[29]=1    # all pixels with value 29, will become 1LUT[179]=2   # all pixels with value 179, will become 2# Apply LUT and save resulting imageImage.fromarray(LUT[npImage]).save('result.png')


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/516923.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号