利用掩膜将png图像放在视频流中,并可随帧改变位置,实现图像在视频中滑动效果:
import cv2
import os
import random
def put_the_png_to_webcam(frame, num, img, step, right):
"""
Arguments:
frame: the webcam's one frame
num: the number to record the frequency of the frame
img: the png image to put.
step: distance to move each frame
right: the location for the image to put
Returns:
frame: the frames after processed
"""
h, w= img.shape[:2]
# method 1 使用位操作:
# 创建掩膜
imggray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, mask = cv2.threshold(imggray, 10, 255, cv2.THRESH_BINARY)
mask_inv = cv2.bitwise_not(mask)
# 保留除png图像外的背景
roi = frame[num*step:h+num*step,right:right+w]
frame_bg = cv2.bitwise_and(roi, roi, mask=mask_inv)
img_fg = cv2.bitwise_and(img, img, mask=mask)
dst = cv2.add(frame_bg, img_fg) # 进行融合
frame[num*step:h+num*step,right:right+w] = dst # 融合后放在原图上
# method 2 使用带权重的图像融合:
# alpha = 0.5
# added_image = cv2.addWeighted(frame[num*step:h+num*step,right:right+w,:], alpha, img[0:h,0:w,:], 1-alpha, 0)
# frame[num*step:h+num*step,right:right+w,:] = added_image
return frame
if __name__ == "__main__":
video = cv2.VideoCapture(0)
if not video.isOpened():
print("can't open the camera!")
png_dir = 'textures' # png图像存放目录
num = 0 # 记录帧数,当达到一定帧数后消失
step = 8 # 每帧移动 8px
img_path = os.path.join(png_dir, "1.png") # png图片的存储地址
img = cv2.imread(img_path)
right = 480
while True:
_, frame = video.read()
if num < 28: # 28帧后图片消失
# 调用函数,将png放在视频流中
frame = put_the_png_to_webcam(frame, num, img, step, right)
cv2.imshow("vedio", frame)
if cv2.waitKey(1) == 27 : # 按ESC键退出程序
break
num += 1
video.release()
cv2.destroyAllWindows()