使用OpenCV进行png图像的叠加 Python

利用掩膜将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() 

参考资料

https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_core/py_image_arithmetics/py_image_arithmetics.html

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值