python - 用于近似像素颜色变化的嵌套 For 循环的 Numpy 等效项

标签 python numpy matplotlib numpy-ndarray array-broadcasting

以下代码展示了如何使用 for 循环通过 numpy 更改 3D 图像中的像素。正如您所看到的,真值是几个逻辑与,其中 RGB 像素值必须在一定范围内。我想知道如何使用 numpy 并行性来做到这一点。我尝试了 np.where 的许多组合,但它们都不起作用,因为这个错误通常显示:“真值不明确,使用 a.any() a.all()”。我只想使用 numpy 方法在这段代码中重新创建嵌套的 for 循环结果。这应该适用于以 3 维导入且 RGB 值为 [0,1] 的任何图像。谢谢。

import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np

avatar = mpimg.imread("some_image.png")

#Looking for pixels that approximate the color red for the color green (thresholding)
#i.e:
#red = np.array([1,0,0,1])
#green = np.array([0,1,0,1])

avatar2 = np.copy(avatar)

for x in range(len(avatar2)):
    for y in range(len(avatar2[0])):
        if (avatar2[x,y][0] > .95 and 
            avatar2[x,y][3] > .95 and
            avatar2[x,y][1] < .05 and
            avatar2[x,y][2] < .05
           ):
            avatar2[x,y] = [0,1,0,1]

plt.imshow(avatar1)
plt.imshow(avatar2)

最佳答案

你可以这样做:

import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np

avatar = mpimg.imread('image.png')
avatar2 = avatar.copy()

print('Input')
plt.imshow(avatar)
plt.show()

mask = ((avatar[:, :, 0] > .95) & 
        (avatar[:, :, 1] < .05) & 
        (avatar[:, :, 2] < .05) & 
        (avatar[:, :, 3] > .95)
       )
avatar2[mask, :] = [0, 1, 0, 1]

print('Output')
plt.imshow(avatar2)
plt.show()

结果:

enter image description here

有一种方法可以一次性完成,但是由于操作比较复杂,速度会比较慢:

mask = (np.sign(avatar - [0.95, 0.05, 0.05, 0.95]) == [1, -1, -1, 1]).all(axis=-1)

但是,请注意,像 OpenCV 这样的库对此有专门的函数,例如 inRange .

关于python - 用于近似像素颜色变化的嵌套 For 循环的 Numpy 等效项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72322152/

相关文章:

Python:如何检查字符串的编码并在不同的地方插入空格?

限制可能值的 Python 类型提示友好类型

python - NumPy 将 np.dot 或 np.multiply 的输出添加到现有数组

python - 在 matplotlib 中绘制多个 y 轴和颜色条

python - Json 与 SQL 建议

python - iPython :Using Pandas, 如何组合多个文本文件来查找重复出现的用户名?

Python Numpy - 创建长度基于一维数组的二维数组

python - 用于复杂 numpy 数组的 Json 编码器和解码器

python - 从二维数组python创建直方图

python - matplotlib 不显示 x 轴和 y 轴标签和值以及图表标题