Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # This program uses the camera feed from the first available webcam and only records when motion is detected
- # It could be used to detect motion on a pre-recorded video, just replace cv2.VideoCapture(0) with cv2.VideoCapture('<Path to video>')
- # This program outputs a .avi file that contains any recorded motion
- import cv2
- import numpy as np
- cap = cv2.VideoCapture(0)
- fgbg = cv2.createBackgroundSubtractorMOG2()
- if cap.isOpened() == False:
- print('Unable to read camera feed')
- width = int(cap.get(3))
- height = int(cap.get(4))
- print(width, height)
- fps = 30.0
- fourcc = cv2.VideoWriter_fourcc(*'XVID')
- out = cv2.VideoWriter('out.avi', fourcc, fps, (width, height))
- kernel = np.ones((15, 15), np.float32)/225
- while True:
- ret, frame = cap.read()
- if ret:
- gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
- mask = fgbg.apply(gray)
- retval, threshold = cv2.threshold(mask, 150, 255, cv2.THRESH_BINARY)
- smooth = cv2.filter2D(threshold, -1, kernel)
- cv2.imshow('Smoothed', smooth)
- cv2.imshow('Masked', mask)
- cv2.imshow('Frame', frame)
- if cv2.countNonZero(mask) >= 1000:
- print('Recording')
- out.write(frame)
- else:
- print('Not Recording')
- if cv2.waitKey(1) & 0xFF == ord('q'):
- break
- else:
- break
- cap.release()
- out.release()
- cv2.destroyAllWindows()
Advertisement
Add Comment
Please, Sign In to add comment