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

用户名

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

第一张图片 在此处输入图片说明

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

马克·谢切尔

您可以使用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)

在此处输入图片说明


如果要混合少量的红色(例如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)

在此处输入图片说明


顺便说一句,您实际上并不需要任何Python,只需在Terminal中使用ImageMagick进行如下操作:

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

在此处输入图片说明


关键字:Python,图像处理,覆盖,蒙版。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章