I'm recording a video with motion detection using Python. All motions detected in that recording will be saved into a single mp4 file. The code goes like:
import cv2, time
import os
import numpy as np
from datetime import datetime
FILE_OUTPUT = "video_" + str(datetime.now().strftime('%Y_%m_%d_%H_%M_%S'))
sdThresh = 10
cv2.namedWindow('frame')
cv2.namedWindow('dist')
i = 0
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
output = cv2.VideoWriter(FILE_OUTPUT + ".mp4", fourcc, 10.0, (640,480))
t0 = time.time()
def distMap(frame1, frame2):
# outputs pythagorean distance between two frames
frame1_32 = np.float32(frame1)
frame2_32 = np.float32(frame2)
diff32 = frame1_32 - frame2_32
norm32 = np.sqrt(diff32[:,:,0]**2 + diff32[:,:,1]**2 + diff32[:,:,2]**2)/np.sqrt(255**2 + 255**2 + 255**2)
dist = np.uint8(norm32*255)
return dist
camera = cv2.VideoCapture('rtsp://admin:@camera_ip')
check1, frame1 = camera.read()
check2, frame2 = camera.read()
while True:
# frame object
check3, frame3 = camera.read()
gerakan = False
if check3 == True:
# mirroring kamera biar gak kebalik
frame3 = cv2.flip(frame3,1)
rows, cols, _ = np.shape(frame3)
dist = distMap(frame1, frame3)
frame1 = frame2
frame2 = frame3
mod = cv2.GaussianBlur(dist, (9,9), 0)
_, thresh = cv2.threshold(mod, 100, 255, 0)
_, stDev = cv2.meanStdDev(mod)
cv2.imshow("Merekam", frame2)
else:
break
if stDev > sdThresh:
image = cv2.resize(frame2, (640, 480))
output.write(image)
gerakan = True
t1 = time.time() # current time
duration = t1 - t0 # diff
if duration > 60:
break
elif cv2.waitKey(25) and 0xFF == ord('q'):
break
camera.release()
output.release()
cv2.destroyAllWindows()
if you put attention to the if stdDev > if stdThresh: that is the code for saving every motion detected to a single file.
and the if duration > 60 shows that the code will work only for 60 seconds. after 60secs, the code will exit.
how can I automate the code to run again after every time it exits?
创建一个shell脚本来运行你的等待和循环的python
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.