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

问题描述

我有几个 png 设计(至少大部分是)白色/灰色(有时还有一点其他颜色),例如当我跑步时

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

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

我尝试过类似 this 之类的东西,但这改变了设计的颜色,这是我不想要的。

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

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)

并返回:

white image

(如果您看不到图像,请参阅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,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,255] # red
bg[:] = [0,255,255] # green
bg[:] = [0,255] # blue
bg[:] = [125,125,255] # gray

bg[np_img>0] = 0

np_img = bg + np_img

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