telegram_amicobot/overlay_test.py
2025-07-11 20:55:10 +02:00

41 lines
1.3 KiB
Python

import cv2
import numpy as np
back = cv2.imread('/home/luca/git_repos/telegram_amicobot/data/photos/Untitled.jpg')
overlay = cv2.imread('/home/luca/git_repos/telegram_amicobot/data/faces/piovra.png', cv2.IMREAD_UNCHANGED) # Load with alpha channel
scale_percent = 200 # percent of original size
width = int(overlay.shape[1] * scale_percent / 100)
height = int(overlay.shape[0] * scale_percent / 100)
dim = (width, height)
# resize image
overlay = cv2.resize(overlay, dim, interpolation = cv2.INTER_AREA)
h, w = back.shape[:2]
h1, w1 = overlay.shape[:2]
# let store center coordinate as cx, cy
cx, cy = (w - w1) // 2, (h - h1) // 2 # Note the order of width and height here
# Ensure the overlay image has an alpha channel
if overlay.shape[2] == 3:
overlay = cv2.cvtColor(overlay, cv2.COLOR_BGR2BGRA)
# Create masks for overlay and background
overlay_mask = overlay[:, :, 3] / 255.0
background_mask = 1.0 - overlay_mask
# Resize overlay image to fit within specified region
overlay_resized = cv2.resize(overlay, (w1, h1))
# Blend the images using alpha blending
for c in range(0, 3):
back[cy:cy + h1, cx:cx + w1, c] = (overlay_resized[:, :, c] * overlay_mask +
back[cy:cy + h1, cx:cx + w1, c] * background_mask)
# View result
cv2.imshow('back with overlay', back)
cv2.waitKey(0)
cv2.destroyAllWindows()