1

i have two images, i need to use numpy and opencv to overlay foreground on top of background using numpy masks.

import numpy as np
import cv2
import matplotlib.pyplot as plt

background = cv2.imread("background.jpg")
foreground = cv2.imread("foreground.png")
foreground = cv2.cvtColor(foreground ,cv2.COLOR_BGR2GRAY)
background = cv2.cvtColor(background ,cv2.COLOR_BGR2GRAY)

arr = []
for i in range(foreground.shape[1]): #parse forground pixels
    temp_row = []
    for j in range(foreground.shape[0]):
        if((foreground [i][j] == 0)):#if pixel transperant draw background
            temp_row.append(background[i][j])
        else: # draw forground
            temp_row.append(foreground[i][j])
    arr.append(temp_row)

res_im = np.array(arr)
plt.figure()
plt.imshow(res_im, cmap='gray', vmin=0, vmax=255)
plt.show()

i used this solution but was told i needed to use masks.. help?

1 Answer 1

8

Here is one way to do that in Python/Opencv.

  • Read the transparent foreground image
  • Read the background image
  • Extract the alpha channel from the foreground image
  • Extract the BGR channels from the foreground image
  • Composite them together using np.where conditional
  • Save the result

Front:

enter image description here

Back:

enter image description here

import cv2
import numpy as np

# read foreground image
img = cv2.imread('front.png', cv2.IMREAD_UNCHANGED)

# read background image
back = cv2.imread('back.png')

# extract alpha channel from foreground image as mask and make 3 channels
alpha = img[:,:,3]
alpha = cv2.merge([alpha,alpha,alpha])

# extract bgr channels from foreground image
front = img[:,:,0:3]

# blend the two images using the alpha channel as controlling mask
result = np.where(alpha==(0,0,0), back, front)

# save result
cv2.imwrite("front_back.png", result)

# show result
cv2.imshow("RESULT", result)
cv2.waitKey(0)

Result:

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.