OpenCV - Save video segments based on certion condition

时光总嘲笑我的痴心妄想 提交于 2021-02-07 09:26:30

问题


Aim : Detect the motion and save only the motion periods in files with names of the starting time.

Now I met the issue about how to save the video to the files with video starting time.

What I tested :

I tested my program part by part. It seems that each part works well except the saving part.

Running status: No error. But in the saving folder, there is no video. If I use a static saving path instead, the video will be saved successfully, but the video will be override by the next video. My codes are below:

import cv2
import numpy as np
import time
cap = cv2.VideoCapture( 0 )
bgst = cv2.createBackgroundSubtractorMOG2()
fourcc=cv2.VideoWriter_fourcc(*'DIVX') 
size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
n = "start_time"

while True:
    ret, frame = cap.read()
    dst = bgst.apply(frame)
    dst = np.array(dst, np.int8)

    if np.count_nonzero(dst)>3000:  # use this value to adjust the "Sensitivity“

        print('something is moving %s' %(time.ctime()))

        path = r'E:\OpenCV\Motion_Detection\%s.avi' %n
        out = cv2.VideoWriter( path, fourcc, 50, size )
        out.write(frame)

        key = cv2.waitKey(3)
        if key == 32:
            break

else:
    out.release()
    n = time.ctime()
    print("No motion Detected %s" %n)

回答1:


What I meant is:

import cv2
import numpy as np
import time
cap = cv2.VideoCapture( 0 )
bgst = cv2.createBackgroundSubtractorMOG2()

fourcc=cv2.VideoWriter_fourcc(*'DIVX') 
size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
path = r'E:\OpenCV\Motion_Detection\%s.avi' %(time.ctime())
out = cv2.VideoWriter( path, fourcc, 16, size )

while True:
    ret, frame = cap.read()
    dst = bgst.apply(frame)
    dst = np.array(dst, np.int8)

    for i in range(number of frames in the video):
        if np.count_nonzero(dst)<3000:  # use this value to adjust the "Sensitivity“

            print("No Motion Detected")
            out.release()

        else:

            print('something is moving %s' %(time.ctime()))
            #label each frame you want to output here 
            out.write(frame(i))

    key = cv2.waitKey(1)
    if key == 32:
        break 

cap.release()
cv2.destroyAllWindows()

If you see the code there will be a for loop, within which the process of saving is done.

I do not know the exact syntax involving for loop with frames, but I hope you have the gist of it. You have to find the number of frames present in the video and set that as the range in the for loop.

Each frame gets saved uniquely (see the else condition.) As I said I do not know the syntax. Please refer and follow this procedure.

Cheers!



来源:https://stackoverflow.com/questions/41778112/opencv-save-video-segments-based-on-certion-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!