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

标签 python image opencv image-processing computer-vision

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 如下所示:

Input image

我想让对角线紫色部分 (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 如下所示:

Alpha channel

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

Output image

这就是您想要实现的目标吗?

关于python - 在python中有效地将颜色转换为透明度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55582117/

相关文章:

python - 适用于 Google 日历 -> iPhone 的字符编码和 VALARM 以及 .ics 文件

python - 将 .ui 文件转换为 .py 文件时出错

android - sqlite 中的图像巨大

javascript - onerror 的对立事件是什么

opencv - 如何找到文本字段的边线

python - 合并多个图像 matplotlib

python - py.test 测试 flask 寄存器,AssertionError : Popped wrong request context

javascript - $ ('img' ).show ("slide", direction : "right", 500) 改变img的位置

python - OpenCV cv2 图像到 PyGame 图像?

python - 如何在Python中将多个摄像机源流传输到单个套接字