首页 > 解决方案 > 发布 BG 减法(使用 opencv-python)并保存,输出视频为 2 GB。如何确保它不爆炸尺寸?

问题描述

# 下面这段代码是读取一个叫做v1.mp4(大小约14MB)的视频文件,对其进行背景减法,旋转帧并保存。

import cv2
import argparse
import datetime
import imutils
import time
import numpy as np
cap = cv2.VideoCapture("C:\\Users\\212458792\\Music\\Downloads\\BasketVideos\\v1.mp4") #Open video file

fgbg = cv2.createBackgroundSubtractorMOG2(detectShadows = True) #Create the background substractor

size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))

# now creating video writer object  
bgsubvideo = cv2.VideoWriter('C:\\Users\\212458792\\Music\\Downloads\\BasketVideos\\bgsubvideo.avi', -1, 20.0,size)
#using any other codec like divx or xvid or mpeg for fourcc did create and video #file and write it, but i couldn't play the file. hence using -1

逐帧执行背景减法

while True:

    ret, frame = cap.read()#read a frame

    if ret==True:

        fgmask = fgbg.apply(frame) #Use the substractor
        cv.Flip(fgmask, flipMode=-1)
        bgsubvideo.write(fgmask)

    else:
        break

cap.release() #release video file
cv2.destroyAllWindows() #close all openCV windows
bgsubvideo.release()

标签: pythonopencvvideo-processingbackground-subtraction

解决方案


推荐阅读