将图像的一部分覆盖到另一幅图像上

时间:2019-12-05 22:55:18

标签: python-3.x opencv image-processing computer-vision scikit-image

有两个对应的图像,第二个图像反映了第一个图像的遮罩区域。

the first image enter image description here

如何将第二张图像中的红色区域叠加到第一张图像上?

1 个答案:

答案 0 :(得分:1)

您可以使用 OpenCV 来做到这一点:

#!/usr/local/bin/python3

import numpy as np
import cv2

# Load base image and overlay
base = cv2.imread("image.jpg",   cv2.IMREAD_UNCHANGED)
over = cv2.imread("overlay.jpg", cv2.IMREAD_UNCHANGED)

# Anywhere the red channel of overlay image exceeds 127, make base image red
# Remember OpenCV uses BGR ordering, not RGB
base[over[...,2]>127] = [0,0,255]

# Save result
cv2.imwrite('result.jpg',base)

enter image description here


如果您想混合少量红色(例如20%),同时保留基础图像的结构,则可以执行以下操作:

#!/usr/local/bin/python3

import numpy as np
import cv2

# Load base image and overlay
base = cv2.imread("image.jpg",   cv2.IMREAD_UNCHANGED)
over = cv2.imread("overlay.jpg", cv2.IMREAD_UNCHANGED)

# Blend 80% of the base layer with 20% red
blended = cv2.addWeighted(base,0.8,(np.zeros_like(base)+[0,0,255]).astype(np.uint8),0.2,0)

# Anywhere the red channel of overlay image exceeds 127, use blended image, elsewhere use base
result = np.where((over[...,2]>127)[...,None], blended, base)

# Save result
cv2.imwrite('result.jpg',result)

enter image description here


顺便说一句,实际上您不需要任何Python,您可以在终端中使用 ImageMagick 来做到这一点,像这样:

magick image.jpg \( overlay.jpg -fuzz 30% -transparent blue \) -composite result.png

enter image description here


关键字:Python,图像处理,叠加层,蒙版。