python - PIL模块mode转换问题请教
PHP中文网
PHP中文网 2017-04-18 09:55:44
0
0
376

我想要达到的目的是将一张图片中灰度模式小于阀值的像素点替换为透明,但是问题是灰度模式没有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<threshold):
            front_px[x,y] = 0
            
            

更新:在网上查找到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")
PHP中文网
PHP中文网

认证高级PHP讲师

reply all(0)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!