added main code.

This commit is contained in:
K 2024-10-18 14:22:24 +05:30
parent c109b013bb
commit 148d88c91e
Signed by: notkshitij
GPG Key ID: C5B8BC7530F8F43F
2 changed files with 120 additions and 0 deletions

54
main.py Normal file
View File

@ -0,0 +1,54 @@
import cv2
import requests
import time
# Set up camera
cap = cv2.VideoCapture(0)
# Initialize variables for motion detection
ret, frame1 = cap.read()
ret, frame2 = cap.read()
# URL for ntfy.sh
ntfy_url = "ntfy.sh/K3R3wHq4w9mwcwNd"
def send_notification():
payload = {
'title': 'Motion Detected',
'message': 'Motion detected by Raspberry Pi camera!',
'priority': 'high'
}
try:
response = requests.post(ntfy_url, json=payload)
if response.status_code == 200:
print("Notification sent successfully.")
else:
print("Failed to send notification.")
except Exception as e:
print(f"An error occurred: {e}")
while cap.isOpened():
# Compute difference between two frames
diff = cv2.absdiff(frame1, frame2)
gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5, 5), 0)
_, thresh = cv2.threshold(blur, 20, 255, cv2.THRESH_BINARY)
dilated = cv2.dilate(thresh, None, iterations=3)
contours, _ = cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
if cv2.contourArea(contour) < 5000:
continue
send_notification()
time.sleep(10) # Wait for 10 seconds before sending another notification
frame1 = frame2
ret, frame2 = cap.read()
# Press 'q' to exit the loop
if cv2.waitKey(10) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()

66
motion_detection.py Normal file
View File

@ -0,0 +1,66 @@
import cv2
import numpy as np
import os
import time
import requests
# Function to send notification using notify.sh
def send_notification():
url = "http://<YOUR_RASPBERRY_PI_IP>:<PORT>/notify" # Replace with your Raspberry Pi's IP and port
payload = {
"title": "Motion Detected!",
"message": "Motion has been detected by the camera."
}
headers = {
"Authorization": "Bearer <YOUR_API_TOKEN>" # Replace with your API token
}
try:
response = requests.post(url, json=payload, headers=headers)
if response.status_code == 200:
print("Notification sent successfully!")
else:
print("Failed to send notification:", response.status_code, response.text)
except Exception as e:
print("Error sending notification:", e)
# Initialize the camera
cap = cv2.VideoCapture(0)
# Read the first frame
ret, frame1 = cap.read()
ret, frame2 = cap.read()
while True:
# Calculate the difference between the frames
diff = cv2.absdiff(frame1, frame2)
gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5, 5), 0)
_, thresh = cv2.threshold(blur, 20, 255, cv2.THRESH_BINARY)
dilated = cv2.dilate(thresh, None, iterations=3)
# Find contours
contours, _ = cv2.findContours(dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Check for motion
for contour in contours:
if cv2.contourArea(contour) < 500: # Adjust the threshold as needed
continue
send_notification()
break # Exit after sending notification
# Update frames
frame1 = frame2
ret, frame2 = cap.read()
# Display the video feed (optional)
cv2.imshow("Motion Detection", frame1)
# Break the loop on 'q' key press
if cv2.waitKey(1) == ord('q'):
break
# Release the camera and close windows
cap.release()
cv2.destroyAllWindows()