Saltar al contenido

Proyecto de sistema de alarma de seguridad mediante Ultralytics YOLOv8

Sistema de alarma de seguridad

El Proyecto de Sistema de Alarma de Seguridad que utiliza Ultralytics YOLOv8 integra capacidades avanzadas de visi贸n por ordenador para mejorar las medidas de seguridad. YOLOv8, desarrollado por Ultralytics, proporciona detecci贸n de objetos en tiempo real, lo que permite al sistema identificar y responder r谩pidamente a posibles amenazas para la seguridad. Este proyecto ofrece varias ventajas:

  • Detecci贸n en tiempo real: la eficacia de YOLOv8 permite al Sistema de Alarma de Seguridad detectar y responder a los incidentes de seguridad en tiempo real, minimizando el tiempo de respuesta.
  • Precisi贸n: YOLOv8 es conocido por su precisi贸n en la detecci贸n de objetos, lo que reduce los falsos positivos y aumenta la fiabilidad del sistema de alarma de seguridad.
  • Capacidad de integraci贸n: El proyecto puede integrarse perfectamente con la infraestructura de seguridad existente, proporcionando una capa mejorada de vigilancia inteligente.



Observa: Proyecto de Sistema de Alarma de Seguridad con Ultralytics YOLOv8 Detecci贸n de Objetos

C贸digo

Bibliotecas de importaci贸n

import torch
import numpy as np
import cv2
from time import time
from ultralytics import YOLO
from ultralytics.utils.plotting import Annotator, colors
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

Configura los par谩metros del mensaje

Nota

La generaci贸n de contrase帽as para aplicaciones es necesaria

  • Navega hasta App Password Generator, designa un nombre de app como "proyecto de seguridad" y obt茅n una contrase帽a de 16 d铆gitos. Copia esta contrase帽a y p茅gala en el campo de contrase帽a designado seg煤n las instrucciones.
password = ""
from_email = ""  # must match the email used to generate the password
to_email = ""  # receiver email

Creaci贸n y autentificaci贸n del servidor

server = smtplib.SMTP('smtp.gmail.com: 587')
server.starttls()
server.login(from_email, password)

Funci贸n de env铆o de correo electr贸nico

def send_email(to_email, from_email, object_detected=1):
    """Sends an email notification indicating the number of objects detected; defaults to 1 object."""
    message = MIMEMultipart()
    message['From'] = from_email
    message['To'] = to_email
    message['Subject'] = "Security Alert"
    # Add in the message body
    message_body = f'ALERT - {object_detected} objects has been detected!!'

    message.attach(MIMEText(message_body, 'plain'))
    server.sendmail(from_email, to_email, message.as_string())

Detecci贸n de objetos y env铆o de alertas

class ObjectDetection:
    def __init__(self, capture_index):
        """Initializes an ObjectDetection instance with a given camera index."""
        self.capture_index = capture_index
        self.email_sent = False

        # model information
        self.model = YOLO("yolov8n.pt")

        # visual information
        self.annotator = None
        self.start_time = 0
        self.end_time = 0

        # device information
        self.device = 'cuda' if torch.cuda.is_available() else 'cpu'

    def predict(self, im0):
        """Run prediction using a YOLO model for the input image `im0`."""
        results = self.model(im0)
        return results

    def display_fps(self, im0):
        """Displays the FPS on an image `im0` by calculating and overlaying as white text on a black rectangle."""
        self.end_time = time()
        fps = 1 / np.round(self.end_time - self.start_time, 2)
        text = f'FPS: {int(fps)}'
        text_size = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, 1.0, 2)[0]
        gap = 10
        cv2.rectangle(im0, (20 - gap, 70 - text_size[1] - gap), (20 + text_size[0] + gap, 70 + gap), (255, 255, 255), -1)
        cv2.putText(im0, text, (20, 70), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 0), 2)

    def plot_bboxes(self, results, im0):
        """Plots bounding boxes on an image given detection results; returns annotated image and class IDs."""
        class_ids = []
        self.annotator = Annotator(im0, 3, results[0].names)
        boxes = results[0].boxes.xyxy.cpu()
        clss = results[0].boxes.cls.cpu().tolist()
        names = results[0].names
        for box, cls in zip(boxes, clss):
            class_ids.append(cls)
            self.annotator.box_label(box, label=names[int(cls)], color=colors(int(cls), True))
        return im0, class_ids

    def __call__(self):
        """Executes object detection on video frames from a specified camera index, plotting bounding boxes and returning modified frames."""
        cap = cv2.VideoCapture(self.capture_index)
        assert cap.isOpened()
        cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
        cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
        frame_count = 0
        while True:
            self.start_time = time()
            ret, im0 = cap.read()
            assert ret
            results = self.predict(im0)
            im0, class_ids = self.plot_bboxes(results, im0)

            if len(class_ids) > 0:  # Only send email If not sent before
                if not self.email_sent:
                    send_email(to_email, from_email, len(class_ids))
                    self.email_sent = True
            else:
                self.email_sent = False

            self.display_fps(im0)
            cv2.imshow('YOLOv8 Detection', im0)
            frame_count += 1
            if cv2.waitKey(5) & 0xFF == 27:
                break
        cap.release()
        cv2.destroyAllWindows()
        server.quit()

Llama a la clase Detecci贸n de Objetos y Ejecuta la Inferencia

detector = ObjectDetection(capture_index=0)
detector()

隆Ya est谩! Cuando ejecutes el c贸digo, recibir谩s una 煤nica notificaci贸n en tu correo electr贸nico si se detecta alg煤n objeto. La notificaci贸n se env铆a inmediatamente, no de forma repetida. No obstante, si茅ntete libre de personalizar el c贸digo para adaptarlo a los requisitos de tu proyecto.

Muestra de correo electr贸nico recibido

Muestra de correo electr贸nico recibido



Creado 2023-12-02, Actualizado 2024-05-03
Autores: glenn-jocher (3), RizwanMunawar (1)

Comentarios