将 numpy value/color 红色更改为黑色

Change numpy value/color red to black

我想将 image[1] 的 red value > 100 更改为 RGB(0,0,0) - image [2] - 使用 Python.

现在: [1]: https://i.stack.imgur.com/cZhVG.jpg

目标: [2]: https://i.stack.imgur.com/bcTU0.png

比如RGB(120,60,90)应该是RGB(0,0,0)

data = np.array(img)

print(data)

航站楼:

[[[10  8  6]
  [10  8  6]
  [10  8  6]
  ...
  [ 8  7  5]
  [ 8  7  5]
  [ 8  7  5]]

 [[10  8  6]
  [10  8  6]
  [10  8  6]
  ...
  [ 8  7  5]
  [ 8  7  5]
  [ 8  7  5]]

 [[10  8  6]
  [10  8  6]
  [10  8  6]
  ...
  [ 8  7  5]
  [ 8  7  5]
  [ 8  7  5]]

...

我知道

data[..., 0]

用于红色通道。

red_channel = data[..., 0]
mask = red_chanel > 100
data[mask] = [0,0,0]

我想……你可能需要更花心一点

data[mask][...,0] = 0 
data[mask][...,1] = 0 
data[mask][...,2] = 0 

(可能有更简单的设置方法,但应该可行)

如果您只是想更改 NumPy 数组中的值,那么只需使用 NumPy 的高级索引

data[data[..., 0] > 100] = np.array([0, 0, 0])

这里有一条线:

(rgb[..., 0] < 100)[..., np.newaxis] * rgb

这也有效(尚未测试哪个更快):

rgb[rgb[..., 0] > 100] *= 0

这是随机 (3, 5, 3) 数组的结果:

>>> import numpy as np
>>> rgb = np.random.randint(0, 255, (3, 5, 3), dtype="uint8")
>>> rgb
array([[[159, 204, 134],
        [208, 224, 176],
        [177,  57,  26],
        [213, 191,  17],
        [ 71, 205, 162]],

       [[124,  94,  64],
        [ 41, 231, 130],
        [ 90, 235, 124],
        [ 18, 237, 101],
        [ 92,  86, 250]],

       [[104, 107, 251],
        [ 27, 247, 214],
        [123, 129,  88],
        [199, 105, 225],
        [ 29, 223, 117]]], dtype=uint8)
>>>
>>> (rgb[..., 0] < 100)[..., np.newaxis] * rgb
array([[[  0,   0,   0],
        [  0,   0,   0],
        [  0,   0,   0],
        [  0,   0,   0],
        [ 71, 205, 162]],

       [[  0,   0,   0],
        [ 41, 231, 130],
        [ 90, 235, 124],
        [ 18, 237, 101],
        [ 92,  86, 250]],

       [[  0,   0,   0],
        [ 27, 247, 214],
        [  0,   0,   0],
        [  0,   0,   0],
        [ 29, 223, 117]]], dtype=uint8)

编辑:我对 500x500 像素的“图像”做了一些非常简单的基准测试:

In [1]: import numpy as np

In [2]: rgb = np.random.randint(0, 255, (500, 500, 3), dtype="uint8")

In [3]: rgb_copy = rgb.copy()

In [4]: %timeit rgb_copy[rgb[..., 0] > 100] *= 0
6.63 ms ± 15 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [5]: rgb_copy = rgb.copy()

In [6]: %timeit rgb_copy[rgb[..., 0] > 100] = np.array([0, 0, 0])
3.25 ms ± 14.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [7]: rgb_copy = rgb.copy()

In [8]: %timeit new_rgb = rgb * (rgb[..., 0] < 100)[..., np.newaxis]
1.24 ms ± 2.91 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

漂亮 类似的结果,尽管我的第一个建议似乎在我的测试中表现最好。