garvitcoder

motion detector (you are at ("rest or motion")?)

May 2nd, 2026
19
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. import turtle
  2.  
  3. import cv2
  4.  
  5. def detect_motion():
  6. # Start video capture
  7. cap = cv2.VideoCapture(0)
  8.  
  9. # Read the first frame
  10. ret, frame1 = cap.read()
  11. frame1_gray = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY)
  12. frame1_gray = cv2.GaussianBlur(frame1_gray, (21, 21), 0)
  13.  
  14. while True:
  15. # Read next frame
  16. ret, frame2 = cap.read()
  17. frame2_gray = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY)
  18. frame2_gray = cv2.GaussianBlur(frame2_gray, (21, 21), 0)
  19.  
  20. # Compare frames
  21. diff = cv2.absdiff(frame1_gray, frame2_gray)
  22. thresh = cv2.threshold(diff, 25, 255, cv2.THRESH_BINARY)[1]
  23. thresh = cv2.dilate(thresh, None, iterations=2)
  24.  
  25. # Find contours (areas of change)
  26. contours, _ = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  27.  
  28. motion_detected = False
  29. for contour in contours:
  30. if cv2.contourArea(contour) > 500: # Ignore small changes
  31. motion_detected = True
  32. (x, y, w, h) = cv2.boundingRect(contour)
  33. cv2.rectangle(frame2, (x, y), (x+w, y+h), (0, 255, 0), 2)
  34.  
  35. # Show result
  36. status = "Motion" if motion_detected else "Rest"
  37. cv2.putText(frame2, f"State: {status}", (10, 30),
  38. cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
  39.  
  40. cv2.imshow("Surroundings State", frame2)
  41.  
  42. # Update frame1 for next loop
  43. frame1_gray = frame2_gray
  44.  
  45. # Exit on 'q'
  46. if cv2.waitKey(30) & 0xFF == ord('q'):
  47. break
  48.  
  49. cap.release()
  50. cv2.destroyAllWindows()
  51.  
  52. if __name__ == "__main__":
  53. detect_motion()
  54.  
Add Comment
Please, Sign In to add comment