python how to save videos by different names?

对着背影说爱祢 提交于 2020-01-25 10:13:06

问题


My aim is recording stream and saving that stream into folders. The problem is, I have to save every 5 seconds long of stream into different folders. I mean for a 30 seconds long stream, there should be 6 folders. My code is working but I can't measure the seconds correctly, I divided the frames (a) into fps. But it did not give the correct result. Also I cannot save videos into different folders by using different names. I have to give different names but I don't know how to do it.

import numpy as np
import cv2, time
import os

cap = cv2.VideoCapture(0)
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))

out = cv2.VideoWriter('output.avi',cv2.VideoWriter_fourcc('M','J','P','G'), 10, (frame_width,frame_height))
a=0
n=0
while(cap.isOpened()):
    a=a+1
    fps = cap.get(cv2.CAP_PROP_FPS)
    sec = a / fps
    ret, frame = cap.read()
    n=n+1

    if ret==True:
        if sec%5==0:
            out = cv2.VideoWriter('output.avi2', cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'), 10,
                                  (frame_width, frame_height))
        else:
            out.write(frame)

        cv2.imshow('frame',frame)

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    else:
        break

print(a)
print('fps= '+str(fps))
print('second= '+str(sec))
cap.release()
out.release()
cv2.destroyAllWindows()

回答1:


You can't measure seconds correctly because your script takes time to execute and since python is a relatively slow programming language, the time needed to execute your code is enough to cause a significant delay if you are dealing with libraries. Try importing datetime module and measuring time with it

import datetime


time_to_wait = datetime.timedelta(seconds=5)

while(cap.isOpened()):
    last = datetime.datetime.now()
    # do your stuff
    if ret==True:
       if datetime.datetime.now() - last >= time_to_wait:
           last = datetime.datetime.now()
           # do your stuff

regarding your naming issue I have no sure solution, but you could try using classes and lists, but I'm not sure



来源:https://stackoverflow.com/questions/59522039/python-how-to-save-videos-by-different-names

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