简体   繁体   中英

Merging a transparent image to another background

I have 2 images as below, both are in RGBA format背景

目的

I want to overlay the object into a fixed region in the background. However, my codes produces a weird result: 在此处输入图像描述

Can someone have a look at my code to see where I was wrong. Thanks in advance

import numpy as np
import matplotlib.pyplot as plt
import cv2
import glob
from PIL import Image
bg = np.array(Image.open('background.png'))
obj = np.array(Image.open('object.png'))

#RESIZE BACKGROUND
scale_percent = 50 # percent of original size
width = int(bg.shape[1] * scale_percent / 100)
height = int(bg.shape[0] * scale_percent / 100)
dim = (width, height)
bg = resized = cv2.resize(bg, dim, interpolation = cv2.INTER_AREA)

#RESIZE OBJECT
scale_percent = 80 # percent of original size
width = int(obj.shape[1] * scale_percent / 100)
height = int(obj.shape[0] * scale_percent / 100)
dim = (width, height)
# resize image
obj = resized = cv2.resize(obj, dim, interpolation=cv2.INTER_AREA)


#create ROI
rows, cols, channels = obj.shape
bg_rows, bg_cols, bg_channels = bg.shape
roi = bg[bg_rows-rows:bg_rows:, bg_cols-cols:bg_cols:]

img2gray = cv2.cvtColor(obj, cv2.COLOR_BGR2GRAY)
ret, mask = cv2.threshold(img2gray, 220, 255, cv2.THRESH_BINARY_INV)

mask_inv = cv2.bitwise_not(mask)

img1_bg = cv2.bitwise_and(roi, roi, mask=mask_inv)

img2_fg = cv2.bitwise_and(obj, obj, mask=mask)

dst = cv2.add(img1_bg, img2_fg)
bg[bg_rows-rows:bg_rows:, bg_cols-cols:bg_cols:] = dst
Image.fromarray(bg)

You should use ImageDraw() function from the pillow library. It will solve your problem by giving the mode same as the 2nd image.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM