Search code examples
pythonreplacecolorsslicepixel

Replacing specific colors with black using slicing?


first time asking a question on stackoverflow! I'm trying to replace specific pixel colors using slicing. I'm interested in replacing the color pink with black.

 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

When I attempt to replace using this function

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

I get the following error

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

img and pink are same dimensions and sizes. What am I doing wrong?


Solution

  • This should work for you:

    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)