使用切片将特定颜色替换为黑色?



第一次在stackoverflow上提问! 我正在尝试使用切片替换特定的像素颜色。我有兴趣用黑色替换粉红色。

 colors = [(0, 0, 0), (255, 0, 255)]
 img = cv2.imread('Untitled.png')  # Random image containing some pink pixels
 pink = img[:, :, :] == np.array(colors[1])  # Boolean array with TRUE @ all pink indices

当我尝试使用此函数替换时

img[pink, :] = np.array(colors[0])  # Replace with black

我收到以下错误

img[pink, :] = np.array(colors[0])
IndexError: too many indices for array

IMG和粉红色是相同的尺寸和大小。我做错了什么?

这应该适合您:

import cv2
image = cv2.imread('test.png')
image[np.where((image==[255,0,255]).all(axis=2))] = [0,0,0]
cv2.imwrite('test_out.png', image)

最新更新