【问题标题】:overlay one part of image onto another image将图像的一部分叠加到另一幅图像上
【发布时间】:2020-03-30 22:24:02
【问题描述】:

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

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

【问题讨论】:

  • 结果会是带有红色斑点的灰色图像吗?总是红蓝相间吗?
  • 是否应该将红色斑点半透明地覆盖在灰色图像上?还是纯红色?
  • 顺便说一句,你不需要任何 Python,你可以在终端中使用 ImageMagick 像这样magick image.jpg \( overlay.jpg -fuzz 30% -transparent blue \) -composite result.png

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


【解决方案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)


如果您想混合一小部分红色(例如 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,您可以在终端中使用 ImageMagick 来完成,如下所示:

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


关键字:Python、图像处理、叠加层、遮罩。

【讨论】:

    猜你喜欢
    • 2011-01-29
    • 2013-02-19
    • 1970-01-01
    • 2013-09-16
    • 2019-02-27
    • 1970-01-01
    • 2016-09-08
    • 1970-01-01
    • 2018-03-28
    相关资源
    最近更新 更多