본문 바로가기
Programming/Python

Overlay two transparent image with PIL

by owllight 2022. 5. 22.
import numpy as np
from PIL import Image
 
img = Image.open("background.png")
 
# convert numpy array to PIL image
mask_img = Image.fromarray(mask).convert('RGBA')

# change mask color
opacity_level = 130  # 0~255
new_data = []
for item in mask_img.getdata()
	if item[0] != 0 and item[1] != 0 and item[2] != 0:
    	new_data.append((R, G, B, opacity_level))
    else:
    	new_data.append((0, 0, 0, 0))  # no-opacity. so, it's blank.
mask_img.putdata(new_data)

# overlay two transparent image
overlay_img = Image.alpha_composite(img, mask_img)

background = Image.new("RGB", overlay_img.size, (255, 255, 255))
background.paste(final_img, mask=overlay_img.split()[3])  # 3 is the alpha channel
color_vol = np.asarray(background)

# save result image to raw file
fn_mask = os.path.join(save_dir, f'Overlay_{size_x}x{size_y}x{size_z}.raw')
color_vol.astype(np.uint8).tofile(fn_mask)

 

댓글