如果满足条件,如何将像素值设置为特定值? [重复]

问题描述 投票:-1回答:1

我有一个基于RGBA模式的图像,它具有如下所示的透明背景。

我注意到的红点的像素值为(2, 2, 3, 45),代表R,G,B和alpha值。

我想将其alpha值小于45的所有像素都设为(0, 0, 0, 0)。我搜索了一段时间,但我只发现numpy.where具有相似的功能,但它仅适用于R或B值之类的单个数据,而不适合整个像素元组:

这是我想要实现的一些伪代码:

if pixel's alpha value <= 45:
    pixel = (0,0,0,0)

enter image description here

python image numpy opencv
1个回答
2
投票

您可以使用NumPy的boolean array indexing

import cv2
import numpy as np

image = np.uint8(np.ones((256, 256, 4)) * (255, 0, 0, 0))
alpha = np.uint8(np.expand_dims(np.arange(256), axis=1) * np.ones(256))
image[:, :, 3] = alpha

image_alpha_cut = image.copy()
image_alpha_cut[image_alpha_cut[:, :, 3] <= 45] = 0

cv2.imwrite('image.png', image)
cv2.imwrite('image_alpha_cut.png', image_alpha_cut)

[输入带有渐变Alpha通道的图像:

Input image

具有剪切的Alpha通道的结果图像:

Result image

希望有帮助!

----------------------------------------
System information
----------------------------------------
Platform:    Windows-10-10.0.16299-SP0
Python:      3.8.1
NumPy:       1.18.1
OpenCV:      4.2.0
----------------------------------------

EDIT:要将受影响的alpha值乘以0.3之类的常数,可以执行以下操作:

idx = image_alpha_cut[:, :, 3] < 40
image_alpha_cut[idx, 3] = 0.3 * image_alpha_cut[idx, 3]

简单的image_alpha_cut[idx, 3] *= 0.3在这里不起作用:

Traceback (most recent call last):
  File "[...].py", line 9, in <module>
    image_alpha_cut[idx, 3] *= 0.3
numpy.core._exceptions.UFuncTypeError: Cannot cast ufunc 'multiply' output from dtype('float64') to dtype('uint8') with casting rule 'same_kind'

Result image #2

© www.soinside.com 2019 - 2024. All rights reserved.