Is there a smart way to convert my dirty code changing a specific color to another?

Viewed 45
#convert pixels's color from 0,255,255 to 0,0,0
h = mask.shape[0] 
w = mask.shape[1]
for py in range(0,h):
    for px in range(0,w):
        if mask[py][px][0] ==0 and mask[py][px][1] == 255 and mask[py][px][2] == 255:
            for i in range(3):
                mask[py][px][i] = 0
# masking
masked = mask.copy()
for py in range(0,h):
    for px in range(0,w):
        if masked[py][px][0] != 0:
            masked[py][px] = im[py][px]
masked = cv2.cvtColor(masked, cv2.COLOR_RGB2BGR)

Is there any fancy way to convert my dirty code to a simple code with cv2 or numpy function?

1 Answers

You can simply do:

color_old = (0,255,255)
color_new = (0,0,0)

img[(img==color_old).all(-1)] = color_new
Related