以下代码展示了如何使用 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()
结果:
有一种方法可以一次性完成,但是由于操作比较复杂,速度会比较慢:
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/