Using openCV to overlay transparent image onto another image

后端 未结 6 2130
庸人自扰
庸人自扰 2020-12-01 12:18

How can I overlay a transparent PNG onto another image without loosing it\'s transparency using openCV in python?

import cv2

background = cv2.imread(\'field         


        
6条回答
  •  天涯浪人
    2020-12-01 12:43

    The following code will use the alpha channels of the overlay image to correctly blend it into the background image, use x and y to set the top-left corner of the overlay image.

    import cv2
    import numpy as np
    
    def overlay_transparent(background, overlay, x, y):
    
        background_width = background.shape[1]
        background_height = background.shape[0]
    
        if x >= background_width or y >= background_height:
            return background
    
        h, w = overlay.shape[0], overlay.shape[1]
    
        if x + w > background_width:
            w = background_width - x
            overlay = overlay[:, :w]
    
        if y + h > background_height:
            h = background_height - y
            overlay = overlay[:h]
    
        if overlay.shape[2] < 4:
            overlay = np.concatenate(
                [
                    overlay,
                    np.ones((overlay.shape[0], overlay.shape[1], 1), dtype = overlay.dtype) * 255
                ],
                axis = 2,
            )
    
        overlay_image = overlay[..., :3]
        mask = overlay[..., 3:] / 255.0
    
        background[y:y+h, x:x+w] = (1.0 - mask) * background[y:y+h, x:x+w] + mask * overlay_image
    
        return background
    

    This code will mutate background so create a copy if you wish to preserve the original background image.

提交回复
热议问题