首页 > 编程语言 >Build an Intrusion-Detection-System using Python

Build an Intrusion-Detection-System using Python

时间:2024-12-20 21:58:45浏览次数:3  
标签:img Intrusion Python notification self cv2 System email image

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:

  1. Prerequisites
  2. Reference
  3. Introduction
  4. Key Concepts
  5. Main
  6. Conclusion

Prerequisites:

Python libraries used:

  1. OpenCV
  2. numpy
  3. smtplib
  4. email

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:

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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:

  1. Import necessary libraries.
  2. 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. Using MIMEMultipart for the email structure, it attaches the provided message and encodes each image with MIMEBase. 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 False

This 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 returns False.

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 and b. 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.01

These 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

  1. 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.com

Replace 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

 

标签:img,Intrusion,Python,notification,self,cv2,System,email,image
From: https://www.cnblogs.com/lightsong/p/18620019

相关文章

  • python 绝对导入和相对导入
    参考:https://blog.csdn.net/huaanxiang/article/details/143687649绝对导入:标准库导入假设有a.py这么写:importos这个是从标准库导入。当前文件目录导入如果a.py的同级目录下有一个b.py,b.py中有classB,那么在a.py也可以导入:frombimportB这个是从当前文件......
  • Python中所有子图标签Legend显示详解
    在数据可视化中,图例(legend)是一个非常重要的元素,它能够帮助读者理解图表中不同元素的含义。特别是在使用Python进行可视化时,matplotlib库是一个非常强大的工具,能够轻松创建包含多个子图的图表,并在每个子图中显示图例。本文将详细介绍如何在Python的matplotlib库中为所有子图显示标......
  • Get-WmiObject -Class Win32_SystemEnclosure -Namespace "root\CIMV2" | Select-Obj
    Get-WmiObject-ClassWin32_SystemEnclosure-Namespace"root\CIMV2"|Select-ObjectChassisTypes这条PowerShell命令用于查询计算机的硬件外壳(Chassis)信息,特别是返回系统机箱类型(ChassisTypes)。解释命令的组成部分:Get-WmiObject:这是一个用于查询WindowsManagement......
  • Python中的数据序列(列表,元组,字典,集合)
    目录列表 语法特点 列表的操作方式查操作增操作改操作删操作元组语法运用场景元组的操作字典语法 字典的操作方式增操作删操作 改操作查操作字典的遍历操作集合语法集合的操作方式增操作删操作 查操作 数据序列之间的转换 列表 语法......
  • 使用Python实现两组数据纵向排序
    使用Python实现两组数据纵向排序 本文详细介绍了如何使用Python实现两组数据的纵向排序,包括开发思想、开发流程和代码示例。通过本文的学习,读者可以掌握如何使用Python的内置函数和第三方库进行排序操作,并能够处理各种边界情况。本文提供的代码示例具有实际应用价值,可以用于......
  • python毕设基于架构的信息发布系统管理和运维的实现ahh5z程序+论文
    本系统(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。系统程序文件列表开题报告内容研究背景随着信息技术的迅猛发展,信息传播已成为企业运营中不可或缺的一部分。无论是大型企业还是初创公司,都需要一个高效、稳定的信息发布系统来宣......
  • python毕设基于学生学情管理系统的设计与实现a5ezy程序+论文
    本系统(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。系统程序文件列表开题报告内容研究背景随着教育信息化的不断深入,学生学情管理成为高校教育管理工作中的重要一环。传统的学生学情管理方式往往依赖于纸质记录、人工统计,不仅效率......
  • Python 二分查找
    作者制作不易,关注、点赞、收藏一下吧!1.二分查找的概念和基本步骤二分查找是一种高效的搜索算法,适用于在一个有序数组中查找特定元素。其基本思想是每次将搜索范围缩小一半,从而快速定位目标元素。二分查找要求输入数组必须是有序的。时间复杂度为O(logn)。初始化:设定两......
  • 基于Python+Vue开发的酒店客房预订管理系统,大四期末作业,实习作品
    项目简介该项目是基于Python+Vue开发的酒店客房预订管理系统(前后端分离),这是一项为大学生课程设计作业而开发的项目。该系统旨在帮助大学生学习并掌握Python编程技能,同时锻炼他们的项目设计与开发能力。通过学习基于Python的酒店客房预订管理系统项目,大学生可以在实践中学......
  • 基于Python+Vue开发的口腔牙科预约管理系统 期末作业
    项目简介该项目是基于Python+Vue开发的口腔牙科预约管理系统(前后端分离),这是一项为大学生课程设计作业而开发的项目。该系统旨在帮助大学生学习并掌握Python编程技能,同时锻炼他们的项目设计与开发能力。通过学习基于Python的口腔牙科诊所预约管理系统项目,大学生可以在实践......