acciolurker
acciolurker

Reputation: 521

Create transparent background for white png image Python

I have several png designs that are (at least mostly) white/gray (sometimes with a little bit of other colors), so for example when I run

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

I don't see the image, since the background is white. I would like to add some light gray to the background, but then that could cause problems if a different design was mostly that shade of gray. How can I make the images "transparent" or at least so the designs are visible?

I've tried something like this but that changes the color of the design, which I don't want.

One such image can be generated by running:

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)

and returns this: white image (see here if you can't see the image)

Upvotes: 0

Views: 2049

Answers (1)

Epsi95
Epsi95

Reputation: 9047

You can try to subtract from the white pixels to make it grey like

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'))

If you want to change the background

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'))

Upvotes: 1

Related Questions