Build an Intrusion-Detection-System using Python
Build an Intrusion-Detection-System using Python
https://medium.com/@nawailk/build-an-intrusion-detection-system-using-python-nawail-khan-8b9e09e6cf88
I have built an Intrusion Detection System, which also works real-time to secure any specified area. This program works on the basis of motion detection and uses computer vision techniques to detect intruders and send email notifications to the owner with attached images of the intruder.
For complete code check out my repo: https://github.com/enncyber/Intrusion-Detection-System
Table of Contents:
- Prerequisites
- Reference
- Introduction
- Key Concepts
- Main
- Conclusion
Prerequisites:
Python libraries used:
- OpenCV
- numpy
- smtplib
Reference:
Building Smart Intrusion Detection System With Opencv & Python
This detailed guide introduces core concepts of intrusion detection system, & demonstrates how to build it with OpenCV…
www.turing.com
Introduction:
Intruder Detection System is a Python program that uses computer vision techniques to detect intruders in a given area. It captures video frames from a webcam, compares consecutive frames to identify any changes, and alerts the user if an intruder is detected. The program also sends an email notification to the user with attached images of the intruder.
Key Concepts:
- Computer Vision: Computer vision is a field of study that focuses on enabling computers to understand and interpret visual information from images or videos. It involves techniques such as image processing, object detection, and tracking.
- OpenCV: OpenCV (Open Source Computer Vision Library) is an open-source computer vision and machine learning software library. It provides various functions and algorithms for image and video processing, object detection, and more.
- Email Notification: The program uses the Simple Mail Transfer Protocol (SMTP) to send email notifications to the user. It requires the user’s email address, password, and the recipient’s email address.
- Frame Difference: The program compares consecutive frames to identify any changes. By calculating the absolute difference between two frames, it can detect motion or movement in the video.
- Bounding Rectangle: The program uses bounding rectangles to enclose detected objects or intruders. It calculates the coordinates and dimensions of the rectangle based on the contours of the detected objects.
Code Structure:
- Import necessary libraries.
- Define the
send_email
function:def send_email(image_paths):
# Set up the email parameters
sender_email = "-"
receiver_email = "-"
password = "your-passkey"
subject = "Intruder Alert!"
message = "An intruder has been detected in the area!"
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = receiver_email
msg['Subject'] = subject
msg.attach(MIMEText(message, 'plain'))
for image_path in image_paths:
attachment = open(image_path, 'rb')
img = MIMEBase('application', 'octet-stream')
img.set_payload((attachment).read())
encoders.encode_base64(img)
img.add_header('Content-Disposition', "attachment; filename= %s" % os.path.basename(image_path))
msg.attach(img)
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(sender_email, password)
text = msg.as_string()
server.sendmail(sender_email, receiver_email, text)
server.quit()The
send_email
function accepts a list of image paths, configuring email parameters, creating a MIME message, and attaching both text and images. UsingMIMEMultipart
for the email structure, it attaches the provided message and encodes each image withMIMEBase
. The email, containing both text and attached images, is then sent via the specified SMTP server.3. Define the
check_intruder
function:def check_intruder():
global contours, rect
for contour in contours:
(x, y, w, h) = cv2.boundingRect(contour)
if cv2.contourArea(contour) < 900:
continue
if x < rect[0] or y < rect[1] or x > rect[0] + rect[2] or y > rect[1] + rect[3]:
return True
return FalseThis function checks if an intruder is present in the area. It iterates over the contours (detected objects) and checks if their area is above a certain threshold. It also checks if the contour is within the defined bounding rectangle. If an intruder is found, it returns
True
; otherwise, it returnsFalse
.4. Define the
click_event
function:def click_event(event, x, y, flags, param):
global draw,a,b
if event==cv2.EVENT_LBUTTONDOWN:
a,b = x,y
draw =1
elif event == cv2.EVENT_LBUTTONDOWN:
if draw == 1:
frame = frame1
# cv2. rectangle(frmae1, (a,b), (x,y), (0,255,0), 1)
cv2.imshow("frame", frame1)
cv2.waitKey(0)
# frame1=frame
elif event == cv2.EVENT_LBUTTONUP:
cv2.rectangle(frame1, (a,b), (x,y), (0,0,255), 1)
global rect
rect = a,b,x,y
draw = 0
cv2.imshow("frame", frame1)
cv2.waitKey(0)This function handles mouse events such as left button down, left button up, and left button double click. It captures the coordinates of the mouse pointer and updates the global variables
a
andb
. It also handles the drawing of the bounding rectangle on the frame.5. Initialize global variables; draw, frame and rect.
6. Open the webcam using the cv2.VideoCapture class.
7. Read the first frame using cap.read() function.
8. Display the frame and wait for the user to draw the bounding rectangle using the mouse.
9. Initialize variables for email notifications:
last_email_time
: The time when the last email notification was sent.delay_between_emails
: The delay in seconds between consecutive email notifications.email_sent
: A flag to indicate if an email notification has been sent.10. Main loop:
- The program enters a loop to continuously capture frames from the webcam.
- It calculates the difference between the current frame and the previous frame to detect motion.
- It applies image processing techniques such as grayscale conversion, blurring, and thresholding to enhance the difference image.
- It crops the difference image to the defined bounding rectangle.
- It finds contours in the cropped image and draws bounding rectangles around the detected objects.
- It checks if an intruder is present and sends an email notification if necessary.
- It updates the frame variables and checks for user input to exit the loop.
Conclusion
The Intruder Detection System is a Python program that uses computer vision techniques to detect intruders in a given area. It captures video frames from a webcam, compares consecutive frames to identify any changes, and alerts the user if an intruder is detected. The program also sends an email notification to the user with attached images of the intruder. By understanding the key concepts and code structure, you can customize and enhance the program to suit your specific needs.
That’ll be all, Thank you.
https://github.com/nawailkhan/Intrusion-Detection-System/blob/main/IDS.ipynb
How to develop an intrusion alert system using YOLOv8 ?
https://beethogedeon.medium.com/how-to-develop-an-intrusion-alert-system-using-yolov8-c60fe473a676
In today’s world, ensuring the security of private and public spaces has become increasingly critical. With advancements in artificial intelligence, it’s now possible to build systems that can automatically detect unauthorized entries and respond in real-time.
The Essence of Intruder Detection
Intruder detection systems are designed to monitor environments for unauthorized access. When paired with immediate notifications, these systems can alert property owners or security personnel swiftly, allowing for instant action.
Crafting Your Own Intruder Detection System
To achieve this, we’ll need to create a Python application that utilizes computer vision for detecting individuals and an email notification service for alerting the administrator. We’ve organized our project into sections that include detection logic, notification management, and the main execution script.
Requirements First
Your environment must meet certain prerequisites to successfully implement this project. Make sure to install all necessary Python libraries by running
pip install -r requirements.txt
The content of `requirements.txt` includes:
opencv-python==4.9.0.80
ultralytics==8.0.206
supervision==0.16.0
python-dotenv==0.21.1
torch==2.01These dependencies include OpenCV for image processing, Ultralytics YOLO for object detection models, Supervision for annotation management, python-dotenv for environment variable management, and PyTorch for leveraging deep learning models.
Dive into the code !
To achieve our intrusion alert system, we’ll create three python scripts: notifications.py, detection.py and main.py
Notifications on The Go…
The `notifications.py` script is responsible for email communication. This script defines a `Notification` class that can send an email with attached images whenever an intruder is detected. This operation relies on an established SMTP server and requires appropriate email credentials.
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
import os
class Notification:
def __init__(self, from_email, to_email, password):
self.from_email = from_email
self.to_email = to_email
self.password = password
self.server = None
self.authenticate()
def authenticate(self):
self.server = smtplib.SMTP('smtp.gmail.com: 587')
self.server.starttls()
self.server.login(self.from_email, self.password)
def send_email(self, object_detected=1):
message = MIMEMultipart()
message['From'] = self.from_email
message['To'] = self.to_email
message['Subject'] = "Intrusion Security Alert"
message_body = f'''
<p>ALERT - {object_detected} intruder(s) has been detected !!</p>
'''
message.attach(MIMEText(message_body, 'html'))
# Attach all images to the message
for file in os.listdir("./images"):
img = open(os.path.join("./images/",file), 'rb').read()
image = MIMEImage(img, name=file)
message.attach(image)
# Send the mail
self.server.sendmail(self.from_email, self.to_email, message.as_string())
def quit(self):
self.server.quit()The Core Detection Logic !
The `detection.py` houses the main logic for detecting individuals using AI models. Utilizing YOLOv8 (a state-of-the-art object detection model), the system can identify individuals within the camera’s view. Detected intruders are labeled and their snapshots are saved. Once a new intruder is detected, an email is triggered via the `Notification` class.
from torch.cuda import is_available
import os
import cv2
from time import time
from ultralytics import YOLO
from supervision import LabelAnnotator, Detections, BoxCornerAnnotator, Color
class PersonDetection:
def __init__(self, capture_index, email_notification):
self.capture_index = capture_index
self.currentIntruderDetected = 0
self.email_notification = email_notification
# Load the model
self.model = YOLO("./weights/yolov8n.pt")
# Instanciate Supervision Annotators
self.box_annotator = BoxCornerAnnotator(color=Color.from_hex("#ff0000"),
thickness=6,
corner_length=30)
self.label_annotator = LabelAnnotator(color=Color.from_hex("#ff0000"),
text_color=Color.from_hex("#fff"))
self.device = 'cuda:0' if is_available() else 'cpu'
def predict(self, img):
# Detect and track object using YOLOv8 model
result = self.model.track(img, persist=True, device=self.device)[0]
# Convert result to Supervision Detection object
detections = Detections.from_ultralytics(result)
# In Yolov8 model, objects with class_id 0 refer to a person. So, we should filter objects detected to only consider person
detections = detections[detections.class_id == 0]
return detections
def plot_bboxes(self, detections: Detections, img):
labels = [f"Intruder #{track_id}" for track_id in detections.tracker_id if len(detections.tracker_id) > 0]
# Add the box to the image
annotated_image = self.box_annotator.annotate(
scene=img,
detections=detections
)
# Add the label to the image
annotated_image = self.label_annotator.annotate(
scene=annotated_image,
detections=detections,
labels=labels
)
return annotated_image
def __call__(self):
cap = cv2.VideoCapture(self.capture_index)
assert cap.isOpened()
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 640)
frame_count = 0
try:
while True:
ret, img = cap.read()
if not ret:
print("Failed to grab frame")
break
results = self.predict(img)
if results:
img = self.plot_bboxes(results, img)
if len(results.class_id) > self.currentIntruderDetected: # We will send notication only when new person is detected
# Let's crop each person detected and save it into images folder
for xyxy, track_id in zip(results.xyxy,results.tracker_id):
intruImg = img[int(xyxy[1]-25):int(xyxy[3]),int(xyxy[0]):int(xyxy[2])]
cv2.imwrite(f"./images/intruder_{track_id}.jpg",intruImg)
# Send notification
self.email_notification.send_email(len(results.class_id))
# Then notification sent, we must delete all previous saved images
delete_files("./images/")
self.currentIntruderDetected = len(results.class_id)
else:
self.currentIntruderDetected = 0
cv2.imshow('Intruder Detection', img)
frame_count += 1
if cv2.waitKey(1) == 27: # ESC key to break
break
finally:
cap.release()
cv2.destroyAllWindows()
self.email_notification.quit()
# Function to delete file
def delete_files(path):
files = os.listdir(path)
for file in files:
os.remove(os.path.join(path,file))Putting It All Together
`main.py` is our entry point. It orchestrates the detection and notification system by instantiating the necessary classes and invoking their methods when an intruder is detected. It accepts command-line arguments to accommodate various camera inputs and sends email alerts using credentials loaded from an environment file.
from detection import PersonDetection
from notifications import Notification
import os
from dotenv import load_dotenv
import argparse
def main(capture_index):
# Load environment variables
load_dotenv()
password = os.environ.get("INTRUSALERTS_PASSWORD")
from_email = os.environ.get("INTRUSALERTS_FROM_EMAIL")
to_email = os.environ.get("INTRUSALERTS_TO_EMAIL")
# Instanciate Notification and PersonDetection classes
email_notification = Notification(from_email, to_email, password)
detector = PersonDetection(capture_index=capture_index, email_notification=email_notification)
#Detect
detector()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Run the person detection system.")
parser.add_argument('--capture_index', default=1, help='The index or IP Address of the camera to be used for capture.')
args = parser.parse_args()
main(args.capture_index)Steps to Run the Project
- Set up your environment by installing prerequisites from `requirements.txt`.
pip install -r requirements.txt
2. Before configuring email notifications, you need an app password for your email account. Visit Google App Passwords, create a new app password, and copy the provided password.
3. Fill in `.env` file with necessary details:
INTRUSALERTS_PASSWORD=your_app_password
INTRUSALERTS_FROM_EMAIL=your_email@gmail.com
INTRUSALERTS_TO_EMAIL=admin_email@example.comReplace
your_app_password
with the password generated from Google App Passwords and the other placeholders with your actual email account and the admin's email address.4. Run `main.py` with appropriate ` — capture_index` to specify the camera source.
python main.py --capture_index 1
The Project’s Future and Improvements
While the project presents a fundamental and functional intruder alert system, the prospects for enhancement are vast:
- Multiple camera support for larger areas.
- Integration with additional notification channels like SMS or mobile apps.
- Enhanced AI models to reduce false positives.
- Real-time streaming for remote monitoring.Experiment With The Code
Find all the code you need to start experimenting with your own Intruder Detection System through the GitHub repository. Don’t hesitate to contribute, fork, and adapt this code to fit your personal or professional security needs.
By leveraging modern AI technologies, we can create a safer environment with systems that alert us in real time to potential threats. What’re you waiting for? Build your intelligent Intruder Alert System today and step into the future of security.
DEMO
https://github.com/lohith84/Intrusion-Detection
https://github.com/jaycheney/YOLOv5-Intrusion-Detection-System