Python PIL 降低 alpha 级别,但不更改透明背景

Pan*_*ora 4 python png alpha python-imaging-library

我想让图像的可见部分更加透明,但也不改变完全透明背景的 Alpha 级别。

这是图片:在此输入图像描述

我这样做:

from PIL import Image
img = Image.open('image_with_transparent_background.png')
img.putalpha(128)
img.save('half_transparent_image_with_preserved_background.png')
Run Code Online (Sandbox Code Playgroud)

这是我得到的:half_transparent_image_with_preserved_background.png

如何在不改变背景的情况下实现我想要的效果?

Mar*_*ell 6

我认为你想在当前非零的任何地方将 alpha 设为 128:

from PIL import Image

# Load image and extract alpha channel
im = Image.open('moth.png')
A = im.getchannel('A')

# Make all opaque pixels into semi-opaque
newA = A.point(lambda i: 128 if i>0 else 0)

# Put new alpha channel back into original image and save
im.putalpha(newA)
im.save('result.png')
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


如果您更乐意使用Numpy执行此操作,您可以执行以下操作:

from PIL import Image
import numpy as np

# Load image and make into Numpy array
im = Image.open('moth.png')
na = np.array(im)

# Make alpha 128 anywhere is is non-zero
na[...,3] = 128 * (na[...,3] > 0)

# Convert back to PIL Image and save
Image.fromarray(na).save('result.png')
Run Code Online (Sandbox Code Playgroud)