我想使用 Python 库将一张图片动态地叠加在另一张图片上,并且想知道哪一个会易于使用。
感谢您的帮助!
最佳答案
如果您想叠加两个图像,只需使用 OpenCV 库即可。
[示例]
这是使用 OpenCV 叠加 image1 和 image2 的示例 python 代码
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)
结果图像被调整大小以减小其体积,但在上面的代码中,调整大小的代码被省略了。
结果:
更新!
这是使用图像的 alpha 值的代码,输出比以前更好。
思路来自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
结果:
关于python - 使用 python 库叠加图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6974923/