import cv2
import face_recognition
import os
import requests
import RPi.GPIO as GPIO
# GPIO Setup
GPIO.setmode(GPIO.BCM)
BUZZER = 18
RELAY = 23
GPIO.setup(BUZZER, GPIO.OUT)
GPIO.setup(RELAY, GPIO.OUT)
# Telegram config
TOKEN = "YOUR_BOT_TOKEN"
CHAT_ID = "YOUR_CHAT_ID"
def send_alert(image_path):
url = f"https://api.telegram.org/bot{TOKEN}/sendPhoto"
with open(image_path, 'rb') as img:
requests.post(url, data={"chat_id": CHAT_ID}, files={"photo": img})
# Load known faces
known_encodings = []
known_names = []
dataset_path = "dataset"
for person in os.listdir(dataset_path):
for img_name in os.listdir(f"{dataset_path}/{person}"):
img = face_recognition.load_image_file(f"{dataset_path}/{person}/{img_name}")
enc = face_recognition.face_encodings(img)[0]
known_encodings.append(enc)
known_names.append(person)
# Start camera
video = cv2.VideoCapture(0)
while True:
ret, frame = video.read()
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
faces = face_recognition.face_locations(rgb)
encodings = face_recognition.face_encodings(rgb, faces)
for (top, right, bottom, left), face_encoding in zip(faces, encodings):
matches = face_recognition.compare_faces(known_encodings, face_encoding)
name = "Unknown"
if True in matches:
name = known_names[matches.index(True)]
GPIO.output(RELAY, GPIO.HIGH)
else:
GPIO.output(BUZZER, GPIO.HIGH)
cv2.imwrite("alert.jpg", frame)
send_alert("alert.jpg")
cv2.rectangle(frame, (left, top), (right, bottom), (0,255,0), 2)
cv2.putText(frame, name, (left, top-10),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0,255,0), 2)
cv2.imshow("Smart Guardian", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video.release()
cv2.destroyAllWindows()
GPIO.cleanup()