2017-01-21 42 views
1

目的保存視頻片段:檢測的運動,只有在保存文件中的運動時間與起始時間名。OpenCV的 - 基於certion條件

現在我遇到了關於如何將視頻保存到具有視頻開始時間的文件的問題。

我測試

我的一部分測試了我的計劃的一部分。看起來,除了保存部分以外,每個部分都工作得很好。

運行狀態:沒有錯誤。但在保存文件夾中,沒有視頻。如果我使用靜態保存路徑,視頻將被成功保存,但視頻將被下一個視頻覆蓋。我的代碼如下所示:

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) 
+0

爲了避免覆蓋已保存的視頻,請使用「for」循環。嘗試在'for'循環中包含'if'和'else'條件。 –

+0

對不起,請您說清楚,我仍然....不能解決問題 – Guang

回答

0

我的意思是:

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() 

如果你看到的代碼會有一個for循環,其內保存的過程中完成的。

我不知道確切的語法涉及循環與幀,但我希望你有它的要點。您必須找到視頻中存在的幀數,並將其設置爲for循環中的範圍。

每個幀得到保存唯一(請參閱else條件。)正如我所說我不知道​​的語法。請參閱並遵循此過程。

乾杯!

+0

謝謝您的解釋。 – Guang

+0

謝謝你的解釋。問題是,我們不知道視頻有多長,因爲它完全取決於運動停止的時間。我認爲我們需要找到一個可以臨時存儲圖像序列的空間,直到運動停止,最後與目標文件夾相同。我不確定numpy數組是否可以做到這一點。我會先試試這個。 – Guang

+0

很高興我能幫上忙 –