How to blend color using mask with object?

Trying to recolor the hair using a mask. I have tried using cv2.addWeighted but it’s not blending properly with hair.

So far I tried:

img_mask = np.copy(img_face)

_, mask_hair = cv2.threshold(mask_hair, thresh=180, maxval=255, type=cv2.THRESH_BINARY)

img_mask = (img_mask * 255).astype(np.uint8)

img_mask[np.where((mask_hair==255).all(axis = 2))] = [139, 0, 247]

img_mask = (img_mask/255).astype(np.float32)
img_face = img_face.astype(np.float32)

alpha = 0.5

hair_clr = cv2.addWeighted(img_mask, alpha, img_face, 1-alpha, 0)

hair_clr = (hair_clr * 255).astype(np.uint8)


But it’s not the output I’m am looking for!


you need to distinguish between a simple true/false mask and a grayscale alpha channel with per-pixel information.

your alpha channel needs to be sensitive to the hair’s brightness. black hair takes less color.

@crackwitz Thanks for your reply.

hairmask[hairmask > 0.6] = 255
hairmask[hairmask <= 0.6] = 0

# a boolean mask
bool_hairmask = hairmask.astype(np.bool)

I made a boolean mask but I didn’t get your next point. Can you elaborate or provide me any ref. ?