python+opencv实现图片的叠加和多个视频帧的叠加

我是使用了三个视频,也就是在其中一个视频的每一帧中添加另外两个视频的每一帧,参考自一篇针对单一图片的文章改写https://blog.csdn.net/qq_36735489/article/details/80917674

如果有opencv知识,逻辑还是好理解的,一些地方也给出了注释

import cv2 as cv


def multy(path1, path2, path3):
    cap1 = cv.VideoCapture(path1)
    cap2 = cv.VideoCapture(path2)
    cap3 = cv.VideoCapture(path3)
    output = 'output.mp4'
    height = int(cap1.get(cv.CAP_PROP_FRAME_HEIGHT))
    weight = int(cap1.get(cv.CAP_PROP_FRAME_WIDTH))
    fps = int(cap1.get(cv.CAP_PROP_FPS))
    fourcc = cv.VideoWriter_fourcc(*'mp4v')  # 设置格式
    videowriter = cv.VideoWriter(output, fourcc, fps, (weight, height))
    while True:
        ret1, frame1 = cap1.read()
        ret2, frame2 = cap2.read()
        ret3, frame3 = cap3.read()
        if ret1 is True and ret2 is True or ret3 is True:
            # Load two images
            cv.namedWindow('res', 0)

            frame2 = cv.resize(frame2, (500, 250))
            frame3 = cv.resize(frame3, (500, 250))

            # I want to put logo on top-left corner, So I create a ROI
            rows, cols, channels = frame2.shape
            roi1 = frame1[0:rows, 0:cols]
            roi2 = frame1[rows:rows*2, 0:cols]

            # Now create a mask of logo and create its inverse mask also
            img2gray2 = cv.cvtColor(frame2, cv.COLOR_BGR2GRAY)
            ret2, mask2 = cv.threshold(img2gray2, 254, 255, cv.THRESH_BINARY)
            mask_inv2 = cv.bitwise_not(mask2)

            img2gray3 = cv.cvtColor(frame3, cv.COLOR_BGR2GRAY)
            ret3, mask3 = cv.threshold(img2gray3, 254, 255, cv.THRESH_BINARY)
            mask_inv3 = cv.bitwise_not(mask3)

            # Now black-out the area of logo in ROI
            img1_bg = cv.bitwise_and(roi1, roi1, mask=mask2)
            img2_bg = cv.bitwise_and(roi2, roi2, mask=mask3)

            # Take only region of logo from logo image.
            img3_fg = cv.bitwise_and(frame2, frame2, mask=mask_inv2)
            img4_fg = cv.bitwise_and(frame3, frame3, mask=mask_inv3)

            # Put logo in ROI and modify the main image
            dst2 = cv.add(img1_bg, img3_fg)
            dst3 = cv.add(img2_bg, img4_fg)
            frame1[0:rows, 0:cols] = dst2
            frame1[rows:rows*2, 0:cols] = dst3

            cv.imshow('res', frame1)
            videowriter.write(frame1)
            cv.waitKey(50)
        else:
            break

    videowriter.release()
    cv.destroyAllWindows()


if __name__ == '__main__':
    path1 = 'video/1_1.mp4'
    path2 = "video/2_1.mp4"
    path3 = "video/2_1.mp4"
    multy(path1, path2, path3)

posted @ 2021-04-28 15:33  小Aer  阅读(32)  评论(0编辑  收藏  举报  来源