我正在尝试将图像中的所有红色和蓝色像素更改为黑色以仅具有绿色像素(基于某些条件)。
为了做到这一点,我现在使用了多个 for 循环,这个过程虽然有效,但速度非常慢。
到目前为止我的代码 -
### Test image is my original RGB image
mat = np.asarray(testim)
for elemento in mat:
for pixel in element:
if ((pixel[0] + pixel[2]) >= (2*pixel[1])): #Non-vegetation background changing to black according to the rule (R + B >= 2G)
pixel[0] = 0
pixel[1] = 0
pixel[2] = 0
elif pixel[1] > pixel[0] and pixel[1] > pixel[2] and pixel[1] > 25: # Treat these as green vegetation and do not change anything
continue
else: # Change background to black
pixel[0] = 0
pixel[1] = 0
pixel[2] = 0
cv2_imshow(testim)
print(testim.shape)
有什么方法可以使用Numpy对其进行矢量化,而无需使用嵌套的 for 循环来使相同的过程更快地工作?我对 NumPy 操作有点陌生,对如何完成它感到困惑。感谢您的帮助!
例如:我的输入图像 - [1]:https ://i.stack.imgur.com/zWGtA.jpg
我现在具有上述逻辑的输出图像 - [2]:https ://i.stack.imgur.com/VkmLC.jpg
我希望使用更快的代码获得相同的输出,最好使用 NumPy 而不是我目前拥有的嵌套 for 循环