- Read the input
- Compute top and bottom heights for the alpha channel
- Create a constant white image for top
- Create a vertical gradient going from 255 to 0 for the bottom
- Stack the top and bottom parts
- Convert the image to 4 channels BGRA
- Replace the alpha in the BGRA image with the stacked alpha
- Save the result
输入:
import cv2
import numpy as np
# read image
img = cv2.imread("lena.png")
ht, wd = img.shape[:2]
# compute 5% of ht and 95% of ht
# pct = 5
pct = 25 # temparily set pct to 25 percent for demonstration
ht2 = int(ht*pct/100)
ht3 = ht - ht2
# create opaque white image for top
top = np.full((ht3,wd), 255, dtype=np.uint8)
# create vertical gradient for bottom
btm = np.linspace(255, 0, ht2, endpoint=True, dtype=np.uint8)
btm = np.tile(btm, (wd,1))
btm = np.transpose(btm)
# stack top and bottom
alpha = np.vstack((top,btm))
# put alpha channel into image
result = img.copy()
result = cv2.cvtColor(result, cv2.COLOR_BGR2BGRA)
result[:,:,3] = alpha
# save result
cv2.imwrite('lena_fade.png', result)
# display results
# (note: display does not show transparency)
cv2.imshow('btm', btm)
cv2.imshow('alpha', alpha)
cv2.imshow('result', result)
cv2.waitKey(0)
3条答案
按热度按时间k75qkfdt1#
下面是如何在ImageMagick 7中实现这一点,无论你是否在输入中有一个现有的alpha通道。它略有不同。你基本上是从输入中提取alpha通道,并将其与包含梯度的通道相乘。然后将新的通道放入原始图像中,替换现有的alpha通道。
输入:
生成图像:
q35jwt9p2#
下面是在Python/OpenCV/Numpy中对不透明图像执行此操作的一种方法。
输入:
结果:
下面是如何在ImageMagick 7中实现这一点。
生成图像:
e5nqia273#
如果图像已经具有透明度,下面是如何在Python/OpenCV中实现这一点。需要提取图像alpha,为渐变创建一个新的alpha,然后将两个alpha通道相乘。最后将新的alpha放入原始图像中,替换旧的alpha。
输入:
结果: