python - PIL模块mode转换问题请教

 mobiledu2502882333 发布于 2022-10-26 13:38

我想要达到的目的是将一张图片中灰度模式小于阀值的像素点替换为透明,但是问题是灰度模式没有alpha通道,只有先转换为RGBA模式才行,现在想到的办法就是建立一张映射表,可以有更优雅的解决办法吗?

#Allocate memory for images
front_px = front_L.load()
back_px = back_L.load()


threshold = 224
for x in range(0,width):
    for y in range(0,height):
        grayValue = front_px[x,y]
        if(grayValue

更新:在网上查找到getdata,putdata方法,确实比循环更高效,但是我陷进了一个循环,convert('L')之后它又会把透明像素填充为白色,吃完饭再想办法

front_RGBA = front.convert('RGBA')


datas_RGBA = front_RGBA.getdata()
datas_L = front_L.getdata()


threshold = 224
newData = []
for index,item in enumerate(datas_L):
    if item < threshold:
        newData.append(datas_RGBA[index])
    else:
        newData.append((255,255,255,0))

front_RGBA.putdata(newData)
front_RGBA.save("images/img.png")
img_L = front_RGBA.convert('L')
img_L.save("images/img_L.png")

第二次更新: 问题已经自己解决了- -,查了下RGBA转灰度图的公式,试了下比较简单的一种做出来效果很好了,谢谢关注问题的人。代码:

threshold = 224
newData = []
for item in datas_L:
    if item < threshold:
        newData.append((item,item,item,256))
    else:
        newData.append((255,255,255,0))

front_RGBA.putdata(newData)
front_RGBA.save("images/img.png")
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有