为白色 png 图像创建透明背景 Python

Create transparent background for white png image Python

我有几个 png 设计(至少大部分)是 white/gray(有时有一点其他颜色),所以例如当我 运行

from PIL import Image
Image.open('white_design.png')

我看不到图像,因为背景是白色的。我想在背景中添加一些浅灰色,但如果不同的设计主要是那种灰色阴影,那么这可能会导致问题。如何使图像“透明”或至少使设计可见?

我试过 之类的东西,但它改变了设计的颜色,我不想要这样。

可以通过 运行ning 生成一个这样的图像:

import base64
from bs4 import BeautifulSoup as bs
import requests
import wand.image

r = requests.get("http://www.codazen.com")
soup = bs(r.content, 'html.parser')
img_tags = soup.find_all('img')

urls = [img['src'] for img in img_tags]

svg_xml_url = urls[1] # white logo design

encoded = svg_xml_url.replace("data:image/svg+xml;base64,","")
decoded = base64.b64decode(encoded)

with wand.image.Image(blob=decoded, format="svg") as image:
    png_image = image.make_blob("png")
    
with open("image.png", "wb") as f:
    f.write(png_image)

和 returns 这个: (see here 如果你看不到图像)

你可以尝试从白色像素中减去使其变成灰色

from PIL import Image
import numpy as np

img = Image.open('your_image.png')
np_img = np.array(img)
v = 50 # the more v, the more black
np_img = np_img - [v,v,v,0] #[R, G, B, alpha]
np_img[np_img<0] = 0 # make the negative values to 0

Image.fromarray(np_img.astype('uint8'))

如果你想改变背景

from PIL import Image
import numpy as np

img = Image.open('t2.png')
np_img = np.array(img)

bg = np.ones_like(np_img)
bg[:] = [255,0,0,255] # red
bg[:] = [0,255,0,255] # green
bg[:] = [0,0,255,255] # blue
bg[:] = [125,125,125,255] # gray

bg[np_img>0] = 0

np_img = bg + np_img

Image.fromarray(np_img.astype('uint8'))