开发者

Overlay images using python library

I wanted to overlay one image over another dynamic开发者_JAVA百科ally using a Python library, and was wondering which one would be easy to use.

Thanks for your help!


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

[Sample]

Overlay images using python library

Overlay images using python library

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:

Overlay images using python library

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:

Overlay images using python library


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜