def copy_image_with_transparency(image, gray_mask, back_image):
# Create an alpha mask from the gray mask
alpha_mask = cv2.cvtColor(gray_mask, cv2.COLOR_GRAY2BGR)
alpha_mask = alpha_mask.astype(float) / 255
# Convert the input image and background image to float
image_float = image.astype(float)
back_image_float = back_image.astype(float)
# Multiply the input image and background image by the alpha mask
image_float = cv2.multiply(alpha_mask, image_float)
back_image_float = cv2.multiply(1.0 - alpha_mask, back_image_float)
# Add the two images together
result = cv2.add(image_float, back_image_float)
# Convert the result to uint8 and return it
return result.astype(np.uint8)
برای اینکار تصویر ماسک را به 3 کاناله تبدیل می کنید. بعد همه تصاویر را float می کنید.بعد از آن هم تصویر foreground را در ماسک جدید ضرب می کنید و به عنوان image_float و بعدش تصویر پس زمینه را در ماسک جدید ضرب می کنید و به عنوان back_image_float نگهداری می کنید سپس این دو تصویر را با هم جمع کنید به هدفتون رسیدید در انتها هم چون همه تصاویر را float کرده بودید تصویر نهایی نیز float شده که باید 8 بیت بشه که خظ آحر این کار را براتون انجام میده.