security_alarm.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
  2. from ultralytics.solutions.solutions import BaseSolution
  3. from ultralytics.utils import LOGGER
  4. from ultralytics.utils.plotting import Annotator, colors
  5. class SecurityAlarm(BaseSolution):
  6. """
  7. A class to manage security alarm functionalities for real-time monitoring.
  8. This class extends the BaseSolution class and provides features to monitor
  9. objects in a frame, send email notifications when specific thresholds are
  10. exceeded for total detections, and annotate the output frame for visualization.
  11. Attributes:
  12. email_sent (bool): Flag to track if an email has already been sent for the current event.
  13. records (int): Threshold for the number of detected objects to trigger an alert.
  14. Methods:
  15. authenticate: Sets up email server authentication for sending alerts.
  16. send_email: Sends an email notification with details and an image attachment.
  17. monitor: Monitors the frame, processes detections, and triggers alerts if thresholds are crossed.
  18. Examples:
  19. >>> security = SecurityAlarm()
  20. >>> security.authenticate("abc@gmail.com", "1111222233334444", "xyz@gmail.com")
  21. >>> frame = cv2.imread("frame.jpg")
  22. >>> processed_frame = security.monitor(frame)
  23. """
  24. def __init__(self, **kwargs):
  25. """Initializes the SecurityAlarm class with parameters for real-time object monitoring."""
  26. super().__init__(**kwargs)
  27. self.email_sent = False
  28. self.records = self.CFG["records"]
  29. self.server = None
  30. self.to_email = ""
  31. self.from_email = ""
  32. def authenticate(self, from_email, password, to_email):
  33. """
  34. Authenticates the email server for sending alert notifications.
  35. Args:
  36. from_email (str): Sender's email address.
  37. password (str): Password for the sender's email account.
  38. to_email (str): Recipient's email address.
  39. This method initializes a secure connection with the SMTP server
  40. and logs in using the provided credentials.
  41. Examples:
  42. >>> alarm = SecurityAlarm()
  43. >>> alarm.authenticate("sender@example.com", "password123", "recipient@example.com")
  44. """
  45. import smtplib
  46. self.server = smtplib.SMTP("smtp.gmail.com: 587")
  47. self.server.starttls()
  48. self.server.login(from_email, password)
  49. self.to_email = to_email
  50. self.from_email = from_email
  51. def send_email(self, im0, records=5):
  52. """
  53. Sends an email notification with an image attachment indicating the number of objects detected.
  54. Args:
  55. im0 (numpy.ndarray): The input image or frame to be attached to the email.
  56. records (int): The number of detected objects to be included in the email message.
  57. This method encodes the input image, composes the email message with
  58. details about the detection, and sends it to the specified recipient.
  59. Examples:
  60. >>> alarm = SecurityAlarm()
  61. >>> frame = cv2.imread("path/to/image.jpg")
  62. >>> alarm.send_email(frame, records=10)
  63. """
  64. from email.mime.image import MIMEImage
  65. from email.mime.multipart import MIMEMultipart
  66. from email.mime.text import MIMEText
  67. import cv2
  68. img_bytes = cv2.imencode(".jpg", im0)[1].tobytes() # Encode the image as JPEG
  69. # Create the email
  70. message = MIMEMultipart()
  71. message["From"] = self.from_email
  72. message["To"] = self.to_email
  73. message["Subject"] = "Security Alert"
  74. # Add the text message body
  75. message_body = f"Ultralytics ALERT!!! {records} objects have been detected!!"
  76. message.attach(MIMEText(message_body))
  77. # Attach the image
  78. image_attachment = MIMEImage(img_bytes, name="ultralytics.jpg")
  79. message.attach(image_attachment)
  80. # Send the email
  81. try:
  82. self.server.send_message(message)
  83. LOGGER.info("✅ Email sent successfully!")
  84. except Exception as e:
  85. print(f"❌ Failed to send email: {e}")
  86. def monitor(self, im0):
  87. """
  88. Monitors the frame, processes object detections, and triggers alerts if thresholds are exceeded.
  89. Args:
  90. im0 (numpy.ndarray): The input image or frame to be processed and annotated.
  91. This method processes the input frame, extracts detections, annotates the frame
  92. with bounding boxes, and sends an email notification if the number of detected objects
  93. surpasses the specified threshold and an alert has not already been sent.
  94. Returns:
  95. (numpy.ndarray): The processed frame with annotations.
  96. Examples:
  97. >>> alarm = SecurityAlarm()
  98. >>> frame = cv2.imread("path/to/image.jpg")
  99. >>> processed_frame = alarm.monitor(frame)
  100. """
  101. self.annotator = Annotator(im0, line_width=self.line_width) # Initialize annotator
  102. self.extract_tracks(im0) # Extract tracks
  103. # Iterate over bounding boxes, track ids and classes index
  104. for box, cls in zip(self.boxes, self.clss):
  105. # Draw bounding box
  106. self.annotator.box_label(box, label=self.names[cls], color=colors(cls, True))
  107. total_det = len(self.clss)
  108. if total_det > self.records and not self.email_sent: # Only send email If not sent before
  109. self.send_email(im0, total_det)
  110. self.email_sent = True
  111. self.display_output(im0) # display output with base class function
  112. return im0 # return output image for more usage