iot-mini/main.py

91 lines
2.9 KiB
Python
Raw Normal View History

2024-10-19 17:30:02 +05:30
from picamera2 import Picamera2
2024-10-18 14:22:24 +05:30
import cv2
2024-10-19 17:30:02 +05:30
import numpy as np
2024-10-18 14:22:24 +05:30
import time
import requests
from datetime import datetime
# ntfy.sh topic (choose your unique topic name)
2024-10-19 21:44:29 +05:30
rpi_ip = "localhost:80"
2024-10-19 18:43:21 +05:30
ntfy_topic = "motion-sensing" # Replace with your ntfy.sh topic
2024-10-19 21:44:29 +05:30
ntfy_url = f"http://{rpi_ip}/{ntfy_topic}"
# If using ntfy.sh server and not the local docker container, set rpi_ip = "ntfy.sh"
2024-10-18 14:22:24 +05:30
2024-10-19 17:30:02 +05:30
# Initialize the camera
picam2 = Picamera2()
picam2.configure(picam2.create_preview_configuration(main={"format": "XRGB8888", "size": (640, 480)}))
picam2.start()
time.sleep(2) # Give the camera some time to initialize
# Read the initial frames
frame1 = picam2.capture_array()
frame2 = picam2.capture_array()
motion_detected = False
2024-10-19 17:30:02 +05:30
while True:
# Calculate the absolute difference between the two frames
2024-10-18 14:22:24 +05:30
diff = cv2.absdiff(frame1, frame2)
2024-10-19 17:30:02 +05:30
# Convert the difference to grayscale
2024-10-18 14:22:24 +05:30
gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)
2024-10-19 17:30:02 +05:30
# Apply a Gaussian blur to the grayscale image
2024-10-18 14:22:24 +05:30
blur = cv2.GaussianBlur(gray, (5, 5), 0)
2024-10-19 17:30:02 +05:30
# Threshold the blurred image to highlight the motion
2024-10-18 14:22:24 +05:30
_, thresh = cv2.threshold(blur, 20, 255, cv2.THRESH_BINARY)
2024-10-19 17:30:02 +05:30
# Dilate the thresholded image to fill in holes
2024-10-18 14:22:24 +05:30
dilated = cv2.dilate(thresh, None, iterations=3)
2024-10-19 17:30:02 +05:30
# Find contours (motion areas) in the dilated image
2024-10-18 14:22:24 +05:30
contours, _ = cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
2024-10-19 17:30:02 +05:30
if cv2.contourArea(contour) < 500:
2024-10-18 14:22:24 +05:30
continue
2024-10-19 17:30:02 +05:30
x, y, w, h = cv2.boundingRect(contour)
cv2.rectangle(frame1, (x, y), (x + w, y + h), (0, 255, 0), 2)
# If motion is detected and not already notified, send a notification
if not motion_detected:
current_time = datetime.now().strftime("%H:%M:%S") # Get current time
message = f"Motion detected in room at {current_time}" # Format message
print("Motion detected! Sending notification...")
try:
response = requests.post(
ntfy_url,
json={"message": message} # Send only the message
)
if response.status_code == 200:
print("Notification sent successfully!")
else:
print(f"Failed to send notification. Status code: {response.status_code}")
except Exception as e:
print(f"Error sending notification: {e}")
motion_detected = True
# If no contours are found, reset the motion_detected flag
if len(contours) == 0:
motion_detected = False
2024-10-19 17:30:02 +05:30
# Display the result
cv2.imshow("Motion Detection", frame1)
2024-10-18 14:22:24 +05:30
2024-10-19 17:30:02 +05:30
# Update frames: frame1 becomes frame2, and a new frame is read as frame2
2024-10-18 14:22:24 +05:30
frame1 = frame2
2024-10-19 17:30:02 +05:30
frame2 = picam2.capture_array()
2024-10-18 14:22:24 +05:30
# Press 'q' to exit the loop
if cv2.waitKey(10) & 0xFF == ord('q'):
break
2024-10-19 17:30:02 +05:30
# Release resources and close all OpenCV windows
picam2.stop()
2024-10-18 14:22:24 +05:30
cv2.destroyAllWindows()