1

I wanted to overlay one image over another dynamically using a Python library, and was wondering which one would be easy to use.

Thanks for your help!

iman453
  • 8,225
  • 13
  • 49
  • 66

2 Answers2

2

If you want to overlay two images, simply use the OpenCV libraries.

[Sample]

enter image description here

enter image description here Here is the sample python code using OpenCV to overlay image1 and image2

import cv2
import numpy as np

def overlay(image1, image2, x, y):
    image1_gray = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)
    _, contours, _ = cv2.findContours(image1_gray, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    image1_mask = np.zeros_like(image1)
    cv2.drawContours(image1_mask, contours, -1, (255,255,255), -1)
    idx = np.where(image1_mask == 255)
    image2[y+idx[0], x+idx[1], idx[2]] = image1[idx[0], idx[1], idx[2]]
    return image2

if __name__ == '__main__':
    grass_img = cv2.imread('grassland.jpg')
    horse_img = cv2.imread('horse.png')
    overlayed = overlay(horse_img, grass_img, 300, 300)
    cv2.imwrite('overlayed.png', overlayed)

The result image was resized to reduce its volume, but in the above code, the resize code was omitted.

Result:

enter image description here

Update!

Here is the code using image's alpha value, and the output is better than before.

The idea is from overlay a smaller image on a larger image python OpenCv

def better_overlay(image1, image2, x, y):
    image1_alpha = image1[:, :, 3] / 255.0
    height, width = image1.shape[0], image1.shape[1]
    for c in range(3):
        image2[y:y+height, x:x+width, c] = image1_alpha * image1[:, :, c] + (1.0 - image1_alpha)* image2[y:y+height, x:x+width, c]
    return image2

Result:

enter image description here

Community
  • 1
  • 1
Alex Kim
  • 31
  • 1
  • 6
  • I get error: ``` image1_alpha = image1[:, :, 3] / 255.0 IndexError: index 3 is out of bounds for axis 2 with size 3``` – JJ Zabkar Sep 25 '19 at 17:51
2

Usually PIL(Python Imaging Library) is for image processing stuff.

utdemir
  • 24,044
  • 9
  • 56
  • 78