Bắt đầu

Dự án hệ thống báo động an ninh sử dụng Ultralytics YOLO26

AI-powered security alarm system with object detection

Dự án này sử dụng thị giác máy tính Ultralytics YOLO26 để xây dựng hệ thống báo động an ninh. YOLO26 cung cấp khả năng phát hiện đối tượng theo thời gian thực, giúp hệ thống nhanh chóng xác định và ứng phó với các mối đe dọa an ninh tiềm ẩn. Dự án này mang lại một số lợi ích:

  • Phát hiện theo thời gian thực: Hiệu suất của YOLO26 cho phép Hệ thống Báo động An ninh phát hiện và ứng phó với sự cố an ninh theo thời gian thực, giảm thiểu thời gian phản hồi.
  • Độ chính xác: Khả năng phát hiện đối tượng chính xác của YOLO26 giúp giảm dương tính giả và tăng độ tin cậy của hệ thống báo động an ninh.
  • Khả năng tích hợp: Dự án có thể bổ sung phân tích AI vào các camera an ninh hiện có, tạo thêm một lớp phát hiện thông minh cho hệ thống giám sát hiện tại.


Xem: Hệ thống Báo động An ninh với Ultralytics YOLO26 + Giải pháp Phát hiện Đối tượng

Gửi cảnh báo an ninh bằng YOLO26#

Giải pháp SecurityAlarm theo dõi đối tượng trong luồng video và gửi một email cảnh báo duy nhất kèm hình ảnh đã chú thích ngay khi số lượng phát hiện đạt ngưỡng records. Xác thực tài khoản Gmail bằng mật khẩu ứng dụng, sau đó chạy giải pháp trên nguồn dữ liệu.

Yêu cầu mật khẩu ứng dụng

Truy cập Trình tạo mật khẩu ứng dụng, đặt tên ứng dụng, chẳng hạn như "dự án an ninh", rồi lấy mật khẩu gồm 16 ký tự. Sao chép mật khẩu này và dán vào trường password trong đoạn code bên dưới.

Hệ thống báo động an ninh sử dụng Ultralytics YOLO
import cv2

from ultralytics import solutions

cap = cv2.VideoCapture("path/to/video.mp4")
assert cap.isOpened(), "Error reading video file"

# Bộ ghi video
w, h, fps = (int(cap.get(x)) for x in (cv2.CAP_PROP_FRAME_WIDTH, cv2.CAP_PROP_FRAME_HEIGHT, cv2.CAP_PROP_FPS))
video_writer = cv2.VideoWriter("security_output.avi", cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h))

from_email = "abc@gmail.com"  # địa chỉ email người gửi
password = "---- ---- ---- ----"  # mật khẩu ứng dụng gồm 16 ký tự được tạo qua: https://myaccount.google.com/apppasswords
to_email = "xyz@gmail.com"  # địa chỉ email người nhận

# Khởi tạo đối tượng báo động an ninh
securityalarm = solutions.SecurityAlarm(
    show=True,  # hiển thị đầu ra
    model="yolo26n.pt",  # ví dụ: yolo26s.pt, yolo26m.pt
    records=1,  # tổng số detection cần gửi email
)

securityalarm.authenticate(from_email, password, to_email)  # xác thực máy chủ email

# Xử lý video
while cap.isOpened():
    success, im0 = cap.read()

    if not success:
        print("Video frame is empty or video processing has been successfully completed.")
        break

    results = securityalarm(im0)

    # print(results)  # truy cập kết quả đầu ra

    video_writer.write(results.plot_im)  # ghi khung hình đã xử lý.

cap.release()
video_writer.release()
cv2.destroyAllWindows()  # đóng tất cả cửa sổ đang mở

Khi chạy code, bạn sẽ nhận được một thông báo email duy nhất nếu phát hiện bất kỳ đối tượng nào. Thông báo được gửi ngay lập tức, không gửi lặp lại. Bạn có thể tùy chỉnh code cho phù hợp với yêu cầu của dự án.

Mẫu email đã nhận#

Security alert email notification example

Các đối số của SecurityAlarm#

Dưới đây là bảng các đối số của SecurityAlarm:

Đối sốKiểuMặc địnhMô tả
modelstrNoneĐường dẫn đến tệp model Ultralytics YOLO.
recordsint5Tổng số đối tượng phát hiện cần đạt để kích hoạt email cảnh báo từ hệ thống an ninh.
line_widthint2Độ dày đường viền của box, keypoint và số đếm mà giải pháp vẽ.
verboseboolTrueBật nhật ký theo từng frame của giải pháp, gồm shape đầu vào, số lượng class và tốc độ xử lý. Bản thân lệnh gọi tracking luôn không ghi nhật ký.

Giải pháp SecurityAlarm hỗ trợ nhiều tham số track:

Đối sốKiểuMặc địnhMô tả
trackerstr'tracktrack.yaml'Chỉ định thuật toán theo dõi cần sử dụng. Các tùy chọn tích hợp sẵn: botsort.yaml, bytetrack.yaml, ocsort.yaml, deepocsort.yaml, fasttrack.yaml, tracktrack.yaml.
conffloat0.25Đặt ngưỡng confidence cho các đối tượng được phát hiện; giá trị thấp hơn cho phép theo dõi nhiều đối tượng hơn nhưng có thể bao gồm cả kết quả dương tính giả.
ioufloat0.5Đặt ngưỡng Intersection over Union (IoU) để lọc các đối tượng phát hiện bị chồng lấn.
classeslistNoneLọc kết quả theo chỉ mục class. Ví dụ: classes=[0, 2, 3] chỉ theo dõi các class được chỉ định.
devicestrNoneChỉ định thiết bị dùng để suy luận (ví dụ: cpu, cuda:0 hoặc 0). Cho phép người dùng chọn CPU, một GPU cụ thể hoặc thiết bị tính toán khác để chạy model.
imgszint or tuple640Kích thước ảnh suy luận mục tiêu: số nguyên cho ảnh vuông hoặc cặp (height, width). Kích thước sẽ được điều chỉnh theo stride của model.
max_detint300Số lượng đối tượng phát hiện tối đa được giữ lại trong mỗi khung hình trước khi theo dõi, giới hạn số đối tượng mà một giải pháp xử lý trong các cảnh dày đặc.
quantizeint or strNoneĐộ chính xác suy luận: 16 (FP16) hoặc 32/unset (FP32) cho model PyTorch và TorchScript khi chạy ngoài CPU; các định dạng khác sử dụng độ chính xác do artifact và runtime của chúng lựa chọn. Thay thế đối số half đã lỗi thời.

Ngoài ra, bạn có thể sử dụng các cài đặt trực quan hóa sau:

Đối sốKiểuMặc địnhMô tả
showboolFalseNếu True, hiển thị ảnh hoặc video đã được chú thích trong một cửa sổ. Hữu ích để nhận phản hồi trực quan ngay lập tức trong quá trình phát triển hoặc kiểm thử.
show_confboolTrueHiển thị điểm confidence bên cạnh nhãn của mỗi detection. Cho biết mức độ chắc chắn của model đối với từng detection.
show_labelsboolTrueHiển thị nhãn cho mỗi detection trong đầu ra trực quan. Giúp nhận biết ngay các đối tượng được phát hiện.

Cách hoạt động#

Hệ thống báo động an ninh sử dụng theo dõi đối tượng để giám sát luồng video và phát hiện các mối đe dọa an ninh tiềm ẩn. Khi số lượng đối tượng được phát hiện trong một khung hình đạt đến ngưỡng đã chỉ định (được đặt bằng tham số records), hệ thống sẽ tự động gửi thông báo email kèm ảnh đính kèm hiển thị các đối tượng được phát hiện.

Hệ thống tận dụng lớp SecurityAlarm, cung cấp các phương thức để:

  1. Xử lý khung hình và trích xuất các detection đối tượng
  2. Chú thích khung hình bằng các bounding box xung quanh đối tượng được phát hiện
  3. Gửi thông báo email khi đạt ngưỡng detection

Cách triển khai này phù hợp với an ninh gia đình, giám sát bán lẻ và các ứng dụng theo dõi khác cần thông báo ngay khi phát hiện đối tượng.

Câu hỏi thường gặp#

  • Ultralytics YOLO26 cải thiện hệ thống báo động an ninh nhờ khả năng phát hiện đối tượng chính xác theo thời gian thực, giúp giảm dương tính giả để hệ thống chủ yếu phản hồi các sự kiện thực sự. Bạn có thể giảm thêm cảnh báo giả bằng cách giới hạn phát hiện ở các classes liên quan (ví dụ: chỉ người), tăng ngưỡng conf hoặc tăng records.

  • Có. Giải pháp SecurityAlarm xử lý khung hình từ mọi nguồn mà OpenCV có thể đọc, bao gồm tệp video, webcam và luồng RTSP từ camera IP, vì vậy bạn có thể bổ sung khả năng phát hiện của YOLO26 vào hệ thống camera hiện có.

  • Chạy Ultralytics YOLO26 trên cấu hình tiêu chuẩn thường cần khoảng 5 GB dung lượng đĩa trống. Mức dung lượng này bao gồm không gian lưu model YOLO26 và các dependency bổ sung. Với giải pháp đám mây, Ultralytics Platform cung cấp khả năng quản lý dự án và xử lý dataset hiệu quả, giúp tối ưu nhu cầu lưu trữ. Gói Pro tăng dung lượng lưu trữ lên 500 GB.

  • Ultralytics YOLO26 có ưu thế so với các model như Faster R-CNN hoặc SSD nhờ khả năng phát hiện theo thời gian thực và độ chính xác cao hơn. Kiến trúc một giai đoạn xử lý ảnh nhanh hơn nhiều mà không làm giảm độ chính xác, khiến model này phù hợp với các ứng dụng cần phản hồi nhanh như hệ thống báo động an ninh.

  • Để giảm dương tính giả, hãy đảm bảo model Ultralytics YOLO26 được huấn luyện đầy đủ trên một dataset đa dạng và được chú thích tốt. Tinh chỉnh siêu tham số và thường xuyên cập nhật model bằng dữ liệu mới có thể cải thiện đáng kể độ chính xác phát hiện.

Bình luận153

Đặt câu hỏi, chia sẻ kết quả hoặc giúp đỡ người khác.

  1. e9l7a5fGitHub

    hi, i cant do the email setting, of Sign in with app passwords and the authentication part , it looks like google change the setting i cant find them, is there another way?

    1
    1. Glenn JocherUltralytics(đã chỉnh sửa)

      Hey there! 😊 It seems like Google's app password settings have indeed evolved, and I appreciate you reaching out for assistance on this. While the current documentation may reference older interfaces, the essence of setting up app passwords for projects like the Security Alarm System with Ultralytics YOLOv8 remains relevant.

      If you're experiencing difficulties locating the specific options for app passwords on Google, you might consider looking into alternative email sending services that offer API support, such as SendGrid, Mailgun, or even using a local SMTP server setup, depending on your project's complexity and scale.

      For a quick fix using smtplib with Gmail, ensure you've enabled two-factor authentication on your account, and then create an app password here: https://myaccount.google.com/apppasswords.

      Here's a simplified version of how to use an app password:

      import smtplib
      
      EMAIL = "your_email@gmail.com"
      APP_PASSWORD = "your_app_password"
      
      with smtplib.SMTP("smtp.gmail.com", 587) as smtp:
          smtp.starttls()
          smtp.login(EMAIL, APP_PASSWORD)
          subject = "Security Alert"
          body = "Alert description"
          msg = f"Subject: {subject}\n\n{body}"
          smtp.sendmail(EMAIL, "receiver_email@gmail.com", msg)

      Make sure to replace "your_email@gmail.com" and "your_app_password" with your actual Gmail email and the 16-digit app password you generate, respectively.

      It's recommended to review the current Gmail documentation or seek updated guidance if Google's procedures have significantly changed since our last update. Hope this helps! If you have further questions or need more personalized assistance, feel free to ask.

    2. e9l7a5fGitHub

      thanks for replying, i fix it for the yolov8 as the same steps u explained, now i want to use it on yolov9 but i cant with these steps, because i am using the detect.py and i dont know how to deal with it , where to put each code, i dont have that much background in DL and python codes. the email part is working now

  2. aaurelionsGitHub
    % python3.11 main.py
    Ultralytics Solutions: ✅ {'source': None, 'model': 'yolo11n.pt', 'classes': None, 'show_conf': True, 'show_labels': True, 'region': None, 'colormap': 21, 'show_in': True, 'show_out': True, 'up_angle': 145.0, 'down_angle': 90, 'kpts': [6, 8, 10], 'analytics_type': 'line', 'figsize': (12.8, 7.2), 'blur_ratio': 0.5, 'vision_point': (20, 20), 'crop_dir': 'cropped-detections', 'json_file': None, 'line_width': 2, 'records': 1, 'fps': 30.0, 'max_hist': 5, 'meter_per_pixel': 0.05, 'max_speed': 120, 'show': True, 'iou': 0.7, 'conf': 0.25, 'device': None, 'max_det': 300, 'half': False, 'tracker': 'botsort.yaml', 'verbose': True, 'data': 'images'}
    Traceback (most recent call last):
      File "/Users/llama/Developer/sec/main.py", line 23, in <module>
        securityalarm.authenticate(from_email, password, to_email)  # authenticate the email server
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/Users/llama/.venv/3.11/lib/python3.11/site-packages/ultralytics/solutions/security_alarm.py", line 68, in authenticate
        self.server = smtplib.SMTP("smtp.gmail.com: 587")
                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/opt/homebrew/Cellar/python@3.11/3.11.13/Frameworks/Python.framework/Versions/3.11/lib/python3.11/smtplib.py", line 255, in __init__
        (code, msg) = self.connect(host, port)
                      ^^^^^^^^^^^^^^^^^^^^^^^^
      File "/opt/homebrew/Cellar/python@3.11/3.11.13/Frameworks/Python.framework/Versions/3.11/lib/python3.11/smtplib.py", line 341, in connect
        self.sock = self._get_socket(host, port, self.timeout)
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/opt/homebrew/Cellar/python@3.11/3.11.13/Frameworks/Python.framework/Versions/3.11/lib/python3.11/smtplib.py", line 312, in _get_socket
        return socket.create_connection((host, port), timeout,
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/opt/homebrew/Cellar/python@3.11/3.11.13/Frameworks/Python.framework/Versions/3.11/lib/python3.11/socket.py", line 863, in create_connection
        raise exceptions[0]
      File "/opt/homebrew/Cellar/python@3.11/3.11.13/Frameworks/Python.framework/Versions/3.11/lib/python3.11/socket.py", line 848, in create_connection
        sock.connect(sa)
    ConnectionRefusedError: [Errno 61] Connection refused
  3. EQUINOX391GitHub

    Dear ultralytics team! First of all i really appreciate this amazing works, I'm working on my projects for detecting crime and i aalready have a trained resnet 50 model for detecting some crime as dummy, I really wonder can i integrate the Security Alarm System by Ultralytics in my projects and make it like have this functionality :

    1. have input of CCTV from RTSP
    2. when detecting people (or maybe car, bike, etc) , my resnet model will also detecting what they do, after we know what the activity is, we can send it the email
    3. customize the email messaging like "ALERT 2 people 2 cars detected, Activity Probability : Suspicious - Stealing"
    4. also send different email if the people stays too long in the frame.
    5. keep making new notification IF There's new people(s) inside the frame.
    6. notified if the people or another object is gone from the frame
    7. is there any pretrain model that detect something related to crime like hammer, crowbar, spraying can, grafitti, gun, etc?
    8. is there any pretrain model yolo have for pose estimation? i mean there's some but i don't find anything inside the documentation that said it can estimate some general pose like, squat, stand, walk, run, etc

    i have so many question but i think that is the most of it! Thank you, and sorry for my bad english.

  4. Cheikh-AhmedandGitHub

    Hi Glenn-jocher!

    I am very appreciative of your help to your clients as i am one of them.

    in onder to integrate security alarm system in an application, using streamlit package, how can i let the end user input their capture_index value and their email:

    st. input_text ( )

    from_email = "@gmail.com" # must match the email used to generate the password

    st. input_text ( )

    detector = ObjectDetection(capture_index=0) detector()

    with examples, please!

    Best regards!

    1. Glenn JocherUltralytics(đã chỉnh sửa)

      @Cheikh-Ahmedand thank you for your support! For Streamlit integration, you can collect user inputs like this:

      import cv2
      import streamlit as st
      from ultralytics import solutions
      
      # User inputs
      from_email = st.text_input("Sender Email")
      password = st.text_input("App Password", type="password")
      to_email = st.text_input("Receiver Email")
      capture_source = st.text_input("Camera Index/Video Path", "0")
      
      # Initialize SecurityAlarm with user inputs
      security = solutions.SecurityAlarm(show=True, model="yolo26n.pt", records=1)
      security.authenticate(from_email, password, to_email)
      cap = cv2.VideoCapture(int(capture_source) if capture_source.isdigit() else capture_source)

      The SecurityAlarm implementation details remain as shown in our security alarm system guide. For email setup, ensure users follow the App Password Generator instructions.

    2. Cheikh-AhmedandGitHub

      Hello there, glenn-jocher!

      Thanks for your nice Help!

      I would like st.input_text for end users for from_emails /to_email and detector = ObjectDetection(capture_index=0) in the below code, not for the code you gave an example on:

      Securiy Alarm System

      password = " " from_email = "@gmail.com" # must match the email used to generate the password to_email = "@gmail.com" # receiver email

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

      from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage

      def send_email(to_email, from_email, image_path, object_detected=1): """Sends an email with an image attachment.""" message = MIMEMultipart() message["From"] = from_email message["To"] = to_email message["Subject"] = "Security Alert" message_body = f"ALERT - {object_detected} objects have been detected!" message.attach(MIMEText(message_body, "plain")) with open(image_path, 'rb') as img_file: img = MIMEImage(img_file.read()) message.attach(img) server.sendmail(from_email, to_email, message.as_string())

      from time import time

      import cv2 import torch from ultralytics import YOLO from ultralytics.utils.plotting import Annotator, colors

      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("yolo11n.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, classes=[0])
          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 / 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):
          """Run object detection on video frames from a camera stream, plotting and showing the results."""
          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:
                 image_path = f"detected_frame_{frame_count}.jpg"
                 cv2.imwrite(image_path, im0)
                 if not self.email_sent:
                  send_email(to_email, from_email, image_path, len(class_ids))
                  self.email_sent = True
              else:
                  self.email_sent = False
      
              self.display_fps(im0)
              cv2.imshow("YOLO11 Detection", im0)
              frame_count += 1
              if cv2.waitKey(5) & 0xFF == 27:
                  break
          cap.release()
          cv2.destroyAllWindows()
          server.quit()

      detector = ObjectDetection(capture_index=0) detector()

      would you please give an example of st. input_text for end users letting them write their emails and capture_index on the above code?

      Sincerely Yours!

    3. Glenn JocherUltralytics

      Thank you for your question! For Streamlit integration with user inputs in your security system, here's how to modify your code:

      import streamlit as st
      
      # User inputs
      from_email = st.text_input("Sender Email")
      to_email = st.text_input("Receiver Email")
      password = st.text_input("App Password", type="password")
      capture_index = st.text_input("Camera Index/Video Path", "0")
      
      # Initialize detector with user inputs
      detector = ObjectDetection(capture_index=int(capture_index) if capture_index.isdigit() else capture_index)

      This allows users to specify their email credentials and camera source through Streamlit's interactive interface. The Security Alarm System guide shows how these inputs integrate with YOLO11's detection capabilities. For email setup requirements, please ensure users follow the App Password Generator instructions from our security alarm documentation.

    4. boukoshoGitHub

      Hey glenn-jocher!

      As you know, ML models need frequent check so as their data remain undriffed and their distribution remain unchanged.

      To frequently monitor deployed ml models by streamlit in case it is deployed to aws ec2, Google Cloud, or streamlit community cloud or in local server, what should I do ?

      Please give an example!

      Thanks!

    5. Glenn JocherUltralytics(đã chỉnh sửa)

      @boukosho for monitoring deployed YOLO11 models across cloud platforms, consider implementing a heartbeat system with performance metrics logging. Our Security Alarm System guide shows email alert integration that could be adapted for drift detection notifications. For production deployments, Ultralytics Platform provides monitoring for deployed endpoints; see the Platform monitoring documentation. A minimal implementation might track inference statistics and trigger alerts via our solutions.SecurityAlarm class when thresholds are exceeded.

  5. Cheikh-AhmedandGitHub

    Hello there glenn-jocher!

    Thanks for your respectful responses!

    If I want the alarm system to only notify me when it is confident of more than 0.3 % .

    So how to do it, with examples, please!

     # model information
    
        self.model = YOLO("yolo11.pt")
    
        # visual information
    
        self.annotator = None
    
        self.start_t        ime = 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, classes=[0])
    
         return results

    Sincelrely Yours!

    1. Glenn JocherUltralytics(đã chỉnh sửa)

      @Cheikh-Ahmedand to adjust the confidence threshold in your security alarm system, set the conf argument when initializing the solution. For example:

      security = solutions.SecurityAlarm(model="yolo26n.pt", conf=0.5)  # only detections above 0.5 confidence

      This ensures notifications only trigger for detections exceeding your specified confidence level. For more details, refer to the Security Alarm System guide.

    2. Cheikh-AhmedandGitHub

      hey!

      Thanks glenn-jocher for your respectful response.

      security = solutions.SecurityAlarm(model="yolo11n.pt", conf=0.5) # Set confidence threshold >0.3 security.model.conf = 0.5 # Alternative direct method

      N.B, I would like to add conf=0.5 for the below function (self.model = YOLO("yolo11n.pt"), not for the above one

      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("yolo11n.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"

      How to do so with examples, please!

      Sincerely Yours!

    3. Glenn JocherUltralytics(đã chỉnh sửa)

      @Cheikh-Ahmedand in your own ObjectDetection class, pass conf when you run inference rather than when loading the model:

      self.model = YOLO("yolo26n.pt")
      results = self.model.predict(im0, conf=0.5)

      For more details on model arguments, see the Predict mode documentation.

    4. Cheikh-AhmedandGitHub

      Hey glenn- jocher!

      Thanks lots for your respectful response.

      self.model = YOLO("yolo11n.pt", task="detect").set({"conf": 0.5})

      When i run the above code, an error has been occured:

      (AttributeError: 'DetectionModel' object has no attribute 'set')

      What should i do instead? With examples, Please.

      Best Regards!

    5. Glenn JocherUltralytics

      To set the confidence threshold in your custom ObjectDetection class, modify your predict method like this:

      def predict(self, im0):
          results = self.model.predict(im0, classes=[0], conf=0.5)  # Add conf here
          return results

      The conf parameter should be passed during inference rather than model initialization. For more details on prediction arguments, see the Predict mode documentation.

  6. boukoshoGitHub

    Hello there! What do you mean by the below function?

    cap = cv2.VideoCapture("Path/to/video/file.mp4") assert cap.isOpened(), "Error reading video file"

    Namely, I have a Webcam or the laptop camera or dvr/nvr cameras and I want to attach them to the above function. How to do so? With examples, please!! . Sincerely Yours!

    1. Glenn JocherUltralytics(đã chỉnh sửa)

      To use your webcam or camera stream with OpenCV's VideoCapture, replace the file path with:

      • 0 for default laptop camera (e.g., cap = cv2.VideoCapture(0))
      • RTSP URL for network cameras (e.g., cap = cv2.VideoCapture("rtsp://username:password@camera_ip:port/stream"))

      For DVR/NVR cameras, use your camera's RTSP stream URL. See OpenCV VideoCapture docs for more input formats.

  7. boukoshoGitHub

    Hay!

    Glenn-jocher I asked you questions here, you haven't answered me yet? Do you still respond kindly to questions regarding yolo security alarm system here? Or you no longer do so?

    Best Regards!

    1. boukoshoGitHub

      Hello there! What do you mean by the below function?

      cap = cv2.VideoCapture("Path/to/video/file.mp4") assert cap.isOpened(), "Error reading video file"

      Namely, I have a Webcam or the laptop camera or dvr/nvr cameras and I want to attach them to the above function. How to do so? With examples, please!! . Sincerely Yours!

    2. Glenn JocherUltralytics(đã chỉnh sửa)

      To use your webcam, laptop camera, or DVR/NVR cameras with cv2.VideoCapture, modify the source argument:

      1. Webcam/Laptop Camera:
        cap = cv2.VideoCapture(0) (0 for default camera, 1 for secondary, etc.)

      2. IP/DVR/NVR Cameras:
        Use RTSP/HTTP stream URLs like:
        cap = cv2.VideoCapture("rtsp://username:password@camera_ip:port/stream")

      The rest of the security alarm code remains unchanged. Ensure your camera feed is accessible and credentials are correctly formatted in URLs. For more details on video sources, see our Object Detection and Tracking guide.

  8. boukoshoGitHub

    Hello there! What do you mean by the below function?

    cap = cv2.VideoCapture("Path/to/video/file.mp4") assert cap.isOpened(), "Error reading video file"

    Namely, I have a Webcam or the laptop camera or dvr/nvr cameras and I want to attach them to the above function. How to do so? With examples, please!! . Sincerely Yours!

    1. Glenn JocherUltralytics(đã chỉnh sửa)

      For webcam/laptop camera use cap = cv2.VideoCapture(0) (0=default camera index). For IP cameras, use an RTSP URL like cap = cv2.VideoCapture("rtsp://username:password@camera_ip:port/path"). The assert checks if the video source opens successfully. You can find specific camera URL formats in your DVR/NVR documentation.

  9. andrewjang2234GitHub

    Traceback (most recent call last): File "C:\Users\User\class-iot\apps\iot07\security.py", line 17, in server.login(from_email, password) File "C:\Users\User\miniconda3\envs\class-iot061\lib\smtplib.py", line 750, in login raise last_exception File "C:\Users\User\miniconda3\envs\class-iot061\lib\smtplib.py", line 739, in login (code, resp) = self.auth( File "C:\Users\User\miniconda3\envs\class-iot061\lib\smtplib.py", line 662, in auth raise SMTPAuthenticationError(code, resp) smtplib.SMTPAuthenticationError: (534, b'5.7.9 Application-specific password required. For more information, go to\n5.7.9 https://support.google.com/mail/?p=InvalidSecondFactor 41be03b00d2f7-7fd430cec7bsm8095565a12.67 - gsmtp')

    I don't know why this error is keep causing.......... what is the problem?

    1. Glenn JocherUltralytics

      @andrewjang2234 to use your laptop's camera, set the capture_index parameter in the ObjectDetection class to 0 (e.g., ObjectDetection(capture_index=0)). This should automatically access your default webcam. If issues persist, ensure your camera is not being used by another application.

  10. andrewjang2234GitHub

    I have a question. what exactly 'to_email' is? 'from_email' is my main emial, and 'password' is 'from_email's password and what is to_email?

    1. Glenn JocherUltralytics

      @andrewjang2234 the to_email refers to the recipient's email address where the alert or notification will be sent. If you have further questions about this setup, feel free to ask!