Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import turtle
- import cv2
- def detect_motion():
- # Start video capture
- cap = cv2.VideoCapture(0)
- # Read the first frame
- ret, frame1 = cap.read()
- frame1_gray = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY)
- frame1_gray = cv2.GaussianBlur(frame1_gray, (21, 21), 0)
- while True:
- # Read next frame
- ret, frame2 = cap.read()
- frame2_gray = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY)
- frame2_gray = cv2.GaussianBlur(frame2_gray, (21, 21), 0)
- # Compare frames
- diff = cv2.absdiff(frame1_gray, frame2_gray)
- thresh = cv2.threshold(diff, 25, 255, cv2.THRESH_BINARY)[1]
- thresh = cv2.dilate(thresh, None, iterations=2)
- # Find contours (areas of change)
- contours, _ = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
- motion_detected = False
- for contour in contours:
- if cv2.contourArea(contour) > 500: # Ignore small changes
- motion_detected = True
- (x, y, w, h) = cv2.boundingRect(contour)
- cv2.rectangle(frame2, (x, y), (x+w, y+h), (0, 255, 0), 2)
- # Show result
- status = "Motion" if motion_detected else "Rest"
- cv2.putText(frame2, f"State: {status}", (10, 30),
- cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
- cv2.imshow("Surroundings State", frame2)
- # Update frame1 for next loop
- frame1_gray = frame2_gray
- # Exit on 'q'
- if cv2.waitKey(30) & 0xFF == ord('q'):
- break
- cap.release()
- cv2.destroyAllWindows()
- if __name__ == "__main__":
- detect_motion()
Add Comment
Please, Sign In to add comment