在python中有效地将颜色转换为透明度

Mak*_*gan 4 python opencv image image-processing computer-vision

GIMP 有一个方便的功能,允许您将任意颜色转换为 Alpha 通道。

基本上所有像素都变得透明,这与它们与所选颜色的距离有关。

我想用 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))
Run Code Online (Sandbox Code Playgroud)

但这是非常昂贵的,执行该迭代所需的时间比简单地将字段设置为 0(6 分钟对 1 小时)所需的时间长约 10 倍

这似乎更像是一个 python 问题而不是一个算法问题。我在 C++ 中做过类似的事情,在性能方面并没有那么糟糕。

有没有人有关于实现这一目标的建议?

Han*_*rse 5

这是我仅使用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)
Run Code Online (Sandbox Code Playgroud)

生成的 Alpha 通道colortrans_alpha.png如下所示:

阿尔法通道

并且,最终的输出图像colortrans_output.png如下所示:

输出图像

这就是你想要达到的目标吗?