1. 颜色背景

实现如下:

#!/usr/bin/python3
#!--*-- coding: utf-8 --*--
import numpy as np 
from PIL import Image
import matplotlib.pyplot as plt 

img_file = 'test.jpg'
png_file = './test.png'

img_pil = Image.open(img_file)
png_pil = Image.open(png_file)
alpha = png_pil.split()[-1]

## pillow
#im = Image.new('RGBA', png_pil.size, (255, 0, 255))
#im.paste(im, mask=im)

# opencv
bg = Image.new("RGB", png_pil.size, (255, 0, 255))
fg = np.array(img_pil, np.float32)
alpha= np.expand_dims(np.array(alpha) / 255,axis=2)
im = alpha * fg + (1 - alpha) * bg
im = im.astype(np.uint8)

#
plt.figure(figsize=(12, 10))
plt.subplot(131)
plt.imshow(img_pil)
plt.subplot(132)
plt.imshow(alpha)
plt.subplot(133)
plt.imshow(im)
plt.show()

如,左原图,中alpha图,右新背景图.

2. 图片背景

#!/usr/bin/python3
#!--*-- coding: utf-8 --*--
from PIL import Image 

img_file = 'test.jpg'
png_file = './test.png'

#
bg = Image.open(bg_file)
png_pil = Image.open(png_file)
if png_pil.size != bg.size:
   png_pil = png_pil.resize(bg.size)
r, g, b, alpha = png_pil.split()
fg = Image.merge('RGB', (r, g, b))

out = Image.composite(fg, bg, png_pil)
Last modification:November 20th, 2020 at 11:08 am