将两张图片(一张是有透明背景的png图片)合成一张
效果图如下:
原理
- cv2.img 是一个3维的数组/矩阵 有3通道和4通道前3个通道是rgb颜色 第四个通道是透明通道
- cv2.imread IMREAD_UNCHANGED (-1) 保证了读取4通道
ps:
- 起因是 看了一个视频 把蔡徐坤的脸换成篮球, 篮球换成徐坤的脸, up主一点一点扣的
- 想用keras 识别篮球, dlib识别脸, opencv 做替换和视频输出 自动化处理一个视频
- 刚碰到这个问题, 找了C++的代码才明白具体怎么解决
代码:
import cv2
cv2.namedWindow("logo")# 定义一个窗口
frame = cv2.imread('F:\\testimg\\2.jpg', cv2.IMREAD_COLOR)# 捕获图像1
#IMREAD_UNCHANGED If set, return the loaded image as is (with alpha channel, otherwise it gets cropped).
#因此Png必须是4通道的IMREAD_UNCHANGED
logo = cv2.imread('F:\\testimg\\logo.png', cv2.IMREAD_UNCHANGED)
rows, cols, channels = logo.shape
dx, dy =120, 150
roi = frame[dx:dx + rows, dy:dy + cols]
for iin range(rows):
for jin range(cols):
if not (logo[i, j][3] ==0):#透明的意思
roi[i, j][0] = logo[i, j][0]
roi[i, j][1] = logo[i, j][1]
roi[i, j][2] = logo[i, j][2]
frame[dx:dx + rows, dy:dy + cols] = roi
cv2.imshow("logo", frame)# 显示轮廓
cv2.waitKey(0)
cv2.destroyAllWindows()
参考:
https://blog.csdn.net/xiongwen_li/article/details/78662234
https://blog.csdn.net/m0_37606112/article/details/78632896
https://docs.opencv.org/3.1.0/d4/da8/group__imgcodecs.html
https://docs.opencv.org/master/d0/d86/tutorial_py_image_arithmetics.html