图像叠加合成

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)

    # 非RGBA,即不用alpha通道,不考虑透明度
    img98.paste(img99, (0, 0))
    # RGBA,使用alpha通道,不考虑透明度
    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)  # 剥离jpg图像通道
    alpha_channel = np.ones(b_channel.shape, dtype=b_channel.dtype) * 255  # 创建Alpha通道

    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
    # 判断jpg图像是否已经为4通道
    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值,将像素值除以255,使值保持在0-1之间
    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/
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值