Reputation: 25
I want to implement these steps:
Here is my code:
import cv2
from skimage.io import *
import numpy as np
imA = cv2.imread('C.jpg')
kernel = np.ones((3, 3), np.uint8)
imA = cv2.cvtColor(imA, cv2.COLOR_BGR2GRAY)
ret, mask = cv2.threshold(imA, 5, 255, cv2.THRESH_BINARY)
opening = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
imshow(opening)
show()
imF = cv2.imread('157969651.jpg')
imF = cv2.cvtColor(imF, cv2.COLOR_BGR2RGBA)
imB = cv2.imread('images.jpg')
imB = cv2.cvtColor(imB, cv2.COLOR_BGR2RGBA)
imF[:, :, 0] *= opening
imF[:, :, 1] *= opening
imF[:, :, 2] *= opening
imF[:, :, 3] *= opening
imB[:, :, 0] *= (1 - opening)
imB[:, :, 1] *= (1 - opening)
imB[:, :, 2] *= (1 - opening)
imB[:, :, 3] *= (1 - opening)
res = imF + imB
imshow(res)
show()
Result:
I don't know what's wrong in this code. Anyone can see what wrong in my steps?
Upvotes: 2
Views: 4813
Reputation: 243955
Alpha not is a channel, is a mask.
My Solution:
import cv2
import numpy as np
foreground = cv2.imread('foreground.jpg')
background = cv2.imread('background.jpg')
kernel = np.ones((5, 5), np.uint8)
foreground_gray = cv2.cvtColor(foreground, cv2.COLOR_BGR2GRAY)
ret, mask = cv2.threshold(foreground_gray, 240, 255, cv2.THRESH_BINARY)
opening = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
output = np.zeros(foreground.shape, dtype=foreground.dtype)
for i in range(3):
output[:, :, i] = background[:, :, i] *(opening/255) + foreground[:, :, i] *(1-opening/255)
cv2.imshow("img", output)
cv2.waitKey(0)
foreground.jpg
background.jpg
Output:
Upvotes: 2