PIL
from PIL import Image
def img_trans():
img98 = './banner/IPADbanner1080×380/98.png'
img99 = './banner/IPADbanner1080×380/99.png'
img98 = Image.open(img98)
img99 = Image.open(img99)
img98.paste(img99, (0, 0))
r, g, b, a = img99.split()
img98.paste(img99, (0, 0), mask=a)
img98.show()
img_trans()
cv2
import cv2
import numpy as np
def add_alpha_channel(img):
""" 为jpg图像添加alpha通道 """
b_channel, g_channel, r_channel = cv2.split(img)
alpha_channel = np.ones(b_channel.shape, dtype=b_channel.dtype) * 255
img_new = cv2.merge((b_channel, g_channel, r_channel, alpha_channel))
return img_new
def merge_img(jpg_img, png_img, bbox):
""" 将png透明图像与jpg图像叠加
y1,y2,x1,x2为叠加位置坐标值
"""
x1, y1, x2, y2 = bbox
if jpg_img.shape[2] == 3:
jpg_img = add_alpha_channel(jpg_img)
'''
当叠加图像时,可能因为叠加位置设置不当,导致png图像的边界超过背景jpg图像,而程序报错
这里设定一系列叠加位置的限制,可以满足png图像超出jpg图像范围时,依然可以正常叠加
'''
yy1 = 0
yy2 = png_img.shape[0]
xx1 = 0
xx2 = png_img.shape[1]
if x1 < 0:
xx1 = -x1
x1 = 0
if y1 < 0:
yy1 = - y1
y1 = 0
if x2 > jpg_img.shape[1]:
xx2 = png_img.shape[1] - (x2 - jpg_img.shape[1])
x2 = jpg_img.shape[1]
if y2 > jpg_img.shape[0]:
yy2 = png_img.shape[0] - (y2 - jpg_img.shape[0])
y2 = jpg_img.shape[0]
alpha_png = png_img[yy1:yy2, xx1:xx2, 3] / 255.0
alpha_jpg = 1 - alpha_png
for c in range(0, 3):
jpg_img[y1:y2, x1:x2, c] = ((alpha_jpg * jpg_img[y1:y2, x1:x2, c]) + (alpha_png * png_img[yy1:yy2, xx1:xx2, c]))
return jpg_img
if __name__ == '__main__':
img98 = './IPADbanner1080/98.png'
img99 = './IPADbanner1080/99.png'
target = np.zeros((727, 2393, 4), dtype=np.uint8)
img98 = cv2.imread(img98, cv2.IMREAD_UNCHANGED)
img99 = cv2.imread(img99, cv2.IMREAD_UNCHANGED)
target = merge_img(target, img98, (1306, 116, 2393, 727))
target = merge_img(target, img99, (1565, 419, 2131, 598))
target = target[232:612, 1309:2389, :]
cv2.imshow('result', target)
if cv2.waitKey(0) & 0xFF == 27:
cv2.destroyAllWindows()
吃水不忘挖井人
- https://www.cnblogs.com/lilinwei340/p/6474170.html
- https://www.cnblogs.com/zhaoyingjie/p/14699837.html
- https://www.freesion.com/article/7440581996/