【问题标题】:merge two images with alpha channel合并两个带有 alpha 通道的图像
【发布时间】:2018-09-19 02:57:47
【问题描述】:

我有两张图片,一张有 Alpha 通道,另一张没有 Alpha 通道。因此,图像AB 的形状分别为(x,y,4)(x,y,3)

我想使用python 将两个图像合并到一个张量中,其中B 是背景,A 是上部图像。最终图像的形状必须为 (x, y, 3)。我试过 scikit-image 或 cv2 是否能够做到这一点,但我找不到任何解决方案。

【问题讨论】:

标签: python scikit-image cv2


【解决方案1】:

这是python中的alpha混合

import numpy as np
import cv2

alpha = 0.4

img1 = cv2.imread('Desert.jpg')
img2 = cv2.imread('Penguins.jpg')

#r,c,z = img1.shape

out_img = np.zeros(img1.shape,dtype=img1.dtype)
out_img[:,:,:] = (alpha * img1[:,:,:]) + ((1-alpha) * img2[:,:,:])
'''
# if want to loop over the whole image
for y in range(r):
    for x in range(c):
        out_img[y,x,0] = (alpha * img1[y,x,0]) + ((1-alpha) * img2[y,x,0])
        out_img[y,x,1] = (alpha * img1[y,x,1]) + ((1-alpha) * img2[y,x,1])
        out_img[y,x,2] = (alpha * img1[y,x,2]) + ((1-alpha) * img2[y,x,2])
'''

cv2.imshow('Output',out_img)
cv2.waitKey(0)

【讨论】:

  • JPG 是如何具有 ARGB 颜色的?恕我直言,这不能回答问题。不知道这怎么可能是公认的答案。不使用上图的alpha通道。
  • 请先检查一下什么是 alpha 混合 docs.opencv.org/3.4/d5/dc4/tutorial_adding_images.html 。答案并没有说它使用 alpha 通道。
  • OP:“我有两张图像,一张有,另一张没有 Alpha 通道”如果不是 RGBA,那么 (x,y,4) 是什么?
  • 如果您使用的是 png 图片并想使用 alpha 蒙版,那么您可以查看此教程learnopencv.com/alpha-blending-using-opencv-cpp-python
  • 另外,如果您不希望最终图像具有透明度,您可以简单地删除第 4 个 / alpha 通道
【解决方案2】:

上述解决方案有效,但我有一个更有效的解决方案:

alpha = A[:,:,3]
A1 = A[:,:,:3]

C = np.multiply(A1, alpha.reshape(x,y,1)) + np.multiply(B, 1-alpha.reshape(x,y,1))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-12
    • 2012-05-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多