ahmed osama
ahmed osama

Reputation: 633

OpenCV Python - replace the mask with the background color

I want to remove the mask from the image and replace it with the background color. as in this case, i want to remove Cristiano's face from the original image

this is the original image
enter image description here

this is the mask
enter image description here

this is the code I am using now

# load background (could be an image too)
bk = np.full(frame.shape, 255, dtype=np.uint8)  # white bk


# blur the mask to help remove noise, then apply the
# mask to the frame
skinMask = cv2.GaussianBlur(skinMask, (3, 3), 0)



#skinMask = cv2.bitwise_not(skinMask)
skin = cv2.bitwise_and(frame, frame, mask = skinMask)

cv2.imshow("mask", skin)

mask = cv2.bitwise_not(skinMask)
bk_masked = cv2.bitwise_and(bk, bk, mask=mask)

# combine masked foreground and masked background 
final = cv2.bitwise_or(bk_masked,skin)

Upvotes: 0

Views: 2277

Answers (1)

Kaiser Dandangi
Kaiser Dandangi

Reputation: 230

I am not sure exactly what the shape of your mask is, but the swapping operation should be quite straight forward.

# Assuming frame is of shape (531, 403, 3)
# And skinMask is of shape (527, 401, 3)
# Which is what it is when you do an cv2.imread on your posted images

# First find all the coordinates you want to swap
faceCoords = np.where(skinMask != [0,0,0])  # 0,0,0 is black

# Then swap the values from your bk image like so
frame[faceCoords[0],faceCoords[1],faceCoords[2]] = bk[faceCoords[0],faceCoords[1],faceCoords[2]]

This should generate an image, with the background value replacing the positive part of the mask values.

Upvotes: 1

Related Questions