Skip to content

Instantly share code, notes, and snippets.

@clungzta
Created August 23, 2017 03:40
Show Gist options
  • Save clungzta/b57163b165d3247af2ebfe2868f7dccf to your computer and use it in GitHub Desktop.
Save clungzta/b57163b165d3247af2ebfe2868f7dccf to your computer and use it in GitHub Desktop.
Function for overlaying transparent (PNG) images in python
import cv2
import numpy as np
def overlay_transparent(background_img, img_to_overlay_t, x, y, overlay_size=None):
"""
@brief Overlays a transparant PNG onto another image using CV2
@param background_img The background image
@param img_to_overlay_t The transparent image to overlay (has alpha channel)
@param x x location to place the top-left corner of our overlay
@param y y location to place the top-left corner of our overlay
@param overlay_size The size to scale our overlay to (tuple), no scaling if None
@return Background image with overlay on top
"""
bg_img = background_img.copy()
if overlay_size is not None:
img_to_overlay_t = cv2.resize(img_to_overlay_t.copy(), overlay_size)
# Extract the alpha mask of the RGBA image, convert to RGB
b,g,r,a = cv2.split(img_to_overlay_t)
overlay_color = cv2.merge((b,g,r))
print(overlay_color.shape)
# Optional, apply some simple filtering to the mask to remove edge noise
#mask = cv2.medianBlur(a,5)
h, w, _ = overlay_color.shape
x, y = int(x-(float(w)/2.0)), int((y-float(h)/2.0))
roi = bg_img[y:y+h, x:x+w]
print(h,w)
print('x y: ', x,y)
print(roi.shape, mask.shape)
# Black-out the area behind the logo in our original ROI
img1_bg = cv2.bitwise_and(roi,roi,mask = cv2.bitwise_not(mask))
# Mask out the logo from the logo image.
img2_fg = cv2.bitwise_and(overlay_color,overlay_color,mask = mask)
# Update the original image with our new ROI
bg_img[y:y+h, x:x+w] = cv2.add(img1_bg, img2_fg)
return bg_img
if __name__ == '__main__':
# Load overlay with transparency
img_transparent = cv2.imread('overlay.png',-1)
# Load Background
background_img = cv2.imread('background_image.jpg')
# Perform overlay
image_with_overlay = overlay_transparent(background_img, img_transparent, 50, 50)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment