GIMP 有一个方便的功能,允许您将任意颜色转换为 alpha channel 。
基本上所有像素都变得透明,这取决于它们与所选颜色的距离。
我想用 opencv 复制这个功能。
我尝试遍历图像:
for x in range(rows):
for y in range(cols):
mask_img[y, x][3] = cv2.norm(img[y, x] - (255, 255, 255, 255))
但这非常昂贵,执行该迭代所需的时间比简单地将字段设置为 0 所需的时间长 10 倍(6 分钟对一个小时)
与其说是算法问题,不如说这是一个 Python 问题。我在 C++ 中做过类似的事情,它在性能方面并没有那么糟糕。
有人对实现这一点有什么建议吗?
最佳答案
这是我仅使用 numpy
矩阵运算的尝试。
我的输入图像 colortrans.png
如下所示:
我想让对角线紫色部分 (128, 0, 128)
透明,左边有一些公差 +/- (25, 0, 25)
和对,导致一些透明度梯度。
代码如下:
import cv2
import numpy as np
# Input image
input = cv2.imread('images/colortrans.png', cv2.IMREAD_COLOR)
# Convert to RGB with alpha channel
output = cv2.cvtColor(input, cv2.COLOR_BGR2RGBA)
# Color to make transparent
col = (128, 0, 128)
# Color tolerance
tol = (25, 0, 25)
# Temporary array (subtract color)
temp = np.subtract(input, col)
# Tolerance mask
mask = (np.abs(temp) <= tol)
mask = (mask[:, :, 0] & mask[:, :, 1] & mask[:, :, 2])
# Generate alpha channel
temp[temp < 0] = 0 # Remove negative values
alpha = (temp[:, :, 0] + temp[:, :, 1] + temp[:, :, 2]) / 3 # Generate mean gradient over all channels
alpha[mask] = alpha[mask] / np.max(alpha[mask]) * 255 # Gradual transparency within tolerance mask
alpha[~mask] = 255 # No transparency outside tolerance mask
# Set alpha channel in output
output[:, :, 3] = alpha
# Output images
cv2.imwrite('images/colortrans_alpha.png', alpha)
cv2.imwrite('images/colortrans_output.png', output)
生成的 alpha channel colortrans_alpha.png
如下所示:
并且,最终输出图像 colortrans_output.png
如下所示:
这就是您想要实现的目标吗?
关于python - 在python中有效地将颜色转换为透明度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55582117/