Given the following images:
I'd like to blend them into the following (result.png):
I already know how to do this with Python PIL, but how do I do it with Python OpenCV?
Here is the Python PIL code for reference:
from PIL import Image
original = Image.open('original.png').convert('RGB')
background = Image.open('background.png').convert('RGB')
mask = Image.open('mask.png').convert('L')
result = Image.composite(original, background, mask)
result.save('result.png')
Can somebody help me fill in the following?:
import cv2
original = cv2.imread('original.png')
background = cv2.imread('background.png')
mask = cv2.imread('mask.png', 0)
result = ???? # What to do here?
cv2.imwrite('result.png', result)
CodePudding user response:
The easiest solution that I know in Python/OpenCV/Numpy is to use Numpy where. This uses original where the mask is white and the background where the mask is black. If mask is not made grayscale, (i.e. kept 3 channel), then
result = np.where(mask==(255,255,255), original.png, background.png)
CodePudding user response:
Answer courtesy of @fmw42:
import cv2
original = cv2.imread('original.png').astype(np.float64)
background = cv2.imread('background.png').astype(np.float64)
mask = cv2.imread('mask.png')
mask = cv2.blur(mask, (5, 5))
inv_mask = cv2.bitwise_not(mask).astype(np.float64)
mask = mask.astype(np.float64)
img1 = cv2.multiply(mask, original) / 255.0
img2 = cv2.multiply(inv_mask, background) / 255.0
result = (cv2.add(img1, img2)).astype(np.uint8)
cv2.imwrite('result.png', result)