之前把两张图片重叠起来做成头像,但是没有买PS软件,用windows自带的画图软件处理无背景图片会bug,网上找到的代码又不能达到我想要的效果,就自己写了一个
希望把这两张图片重叠起来:
我的代码如下:
import cv2
import numpy as np
def img_overlap(back,front,x_bais,y_bais,zoom):
back = np.array(back)
taget_shape = (int(back.shape[1]*zoom),int(back.shape[0]*zoom))
front = cv2.resize(front,taget_shape)
front = np.array(front)
front = front[int((front.shape[0]-back.shape[0])/2):int((front.shape[0]-back.shape[0])/2+back.shape[0]),
int((front.shape[1]-back.shape[1])/2):int((front.shape[1]-back.shape[1])/2+back.shape[1]),:]
front2 = np.array(front)
for a in range(front2.shape[0]):
for b in range(front2.shape[1]):
for c in range(front2.shape[2]):
if front2[a][b][c] == 0:
front2[a][b][c] = 1
else:
front2[a][b][c] = 0
back[max(0,y_bais):min(back.shape[0],back.shape[0]+y_bais),max(0,x_bais):min(back.shape[1],back.shape[1]+x_bais),:] *= front2[max(0,-y_bais):min(back.shape[0],back.shape[0]-y_bais),
max(0,-x_bais):min(back.shape[1],back.shape[1]-x_bais),:]
back[max(0,y_bais):min(back.shape[0],back.shape[0]+y_bais),max(0,x_bais):min(back.shape[1],back.shape[1]+x_bais),:] += front[max(0,-y_bais):min(back.shape[0],back.shape[0]-y_bais),
max(0,-x_bais) : min(back.shape[1],back.shape[1]-x_bais), :]
return back
if __name__ == '__main__':
back = cv2.imread('lgd.png')
front = cv2.imread('tx.png')
x_bais = 0
y_bais = 0
zoom = 1
result = img_overlap(back, front, x_bais, y_bais, zoom)
cv2.imshow('result',result)
cv2.waitKey(0)
cv2.imwrite('result.png',result)
可以设置重叠图片在横向、纵向的偏移量已经重叠图片的放大倍数(此处只能放,没有写缩小,需要缩小可以手动在画图里拉大画布),此处我的背景图片和重叠图片的尺寸分别是300x300和1080x1080,设置初始参数得到的图片如下 为了达到目标效果,将y_bias设置为38,zoom设置为1.13即可得到目标图像
|