Ultralytics YOLO26을 활용한 보안 경보 시스템 프로젝트
이 프로젝트는 Ultralytics YOLO26 컴퓨터 비전을 사용해 보안 경보 시스템을 구축합니다. YOLO26은 실시간 객체 감지를 제공하여 시스템이 잠재적인 보안 위협을 신속하게 식별하고 대응할 수 있도록 합니다. 이 프로젝트는 다음과 같은 여러 이점을 제공합니다:
- 실시간 감지: YOLO26의 효율성 덕분에 보안 경보 시스템은 보안 사고를 실시간으로 감지하고 대응하여 대응 시간을 최소화할 수 있습니다.
- 정확도: YOLO26의 정확한 객체 감지는 오탐을 줄이고 보안 경보 시스템의 신뢰성을 높입니다.
- 통합 기능: 이 프로젝트는 기존 보안 카메라에 AI 분석 기능을 추가하여 현재 감시 시스템 위에 지능형 감지 계층을 제공할 수 있습니다.
시청: Ultralytics YOLO26을 사용한 보안 경보 시스템 + 솔루션 객체 감지
YOLO26으로 보안 알림 전송하기#
SecurityAlarm 솔루션은 동영상 피드의 객체를 추적하며, 감지 수가 records 임계값에 도달하는 즉시 주석이 추가된 이미지가 첨부된 이메일 알림을 한 번 전송합니다. 앱 비밀번호로 Gmail 계정을 인증한 다음 소스에 솔루션을 실행하세요.
앱 비밀번호 생성기로 이동해 "security project"와 같은 앱 이름을 지정하고 16자 비밀번호를 발급받으세요. 이 비밀번호를 복사하여 아래 코드의 password 필드에 붙여넣으세요.
import cv2
from ultralytics import solutions
cap = cv2.VideoCapture("path/to/video.mp4")
assert cap.isOpened(), "Error reading video file"
# 비디오 작성기
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" # 발신자 이메일 주소
password = "---- ---- ---- ----" # https://myaccount.google.com/apppasswords에서 생성한 16자 앱 비밀번호
to_email = "xyz@gmail.com" # 수신자 이메일 주소
# 보안 경보 객체 초기화
securityalarm = solutions.SecurityAlarm(
show=True, # 출력을 표시합니다.
model="yolo26n.pt", # 예: yolo26s.pt, yolo26m.pt
records=1, # 이메일을 보낼 총 감지 수
)
securityalarm.authenticate(from_email, password, to_email) # 이메일 서버 인증
# 비디오 처리
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) # 출력에 액세스
video_writer.write(results.plot_im) # 처리된 프레임을 저장합니다.
cap.release()
video_writer.release()
cv2.destroyAllWindows() # 열려 있는 모든 창 닫기코드를 실행하면 객체가 하나라도 감지된 경우 이메일 알림을 한 번 받게 됩니다. 알림은 즉시 전송되며 반복해서 전송되지는 않습니다. 프로젝트 요구 사항에 맞게 코드를 사용자 지정할 수 있습니다.
수신 이메일 예시#
SecurityAlarm 인수#
다음은 SecurityAlarm 인수 표입니다:
| 인수 | 유형 | 기본값 | 설명 |
|---|---|---|---|
model | str | None | Ultralytics YOLO 모델 파일의 경로입니다. |
records | int | 5 | 보안 경보 시스템에서 이메일을 트리거하는 총 감지 횟수입니다. |
line_width | int | 2 | Solution에서 그리는 상자, 키포인트 및 개수 표시의 선 두께입니다. |
verbose | bool | True | 프레임별 입력 형태, 클래스 개수 및 처리 속도 로그를 활성화합니다. 추적 호출 자체는 항상 로그를 출력하지 않습니다. |
SecurityAlarm 솔루션은 다양한 track 매개변수를 지원합니다.
| 인수 | 유형 | 기본값 | 설명 |
|---|---|---|---|
tracker | str | 'tracktrack.yaml' | 사용할 추적 알고리즘을 지정합니다. 기본 제공 옵션: botsort.yaml, bytetrack.yaml, ocsort.yaml, deepocsort.yaml, fasttrack.yaml, tracktrack.yaml. |
conf | float | 0.25 | 탐지에 대한 신뢰도 임계값을 설정합니다. 값을 낮추면 추적할 수 있는 객체가 늘어나지만 오탐이 포함될 수 있습니다. |
iou | float | 0.5 | 중복 탐지를 필터링하기 위한 교집합 대비 합집합 (IoU) 임계값을 설정합니다. |
classes | list | None | 클래스 인덱스로 결과를 필터링합니다. 예를 들어 classes=[0, 2, 3]은 지정된 클래스만 추적합니다. |
device | str | None | 추론에 사용할 장치를 지정합니다(예: cpu, cuda:0 또는 0). 사용자는 모델 실행에 사용할 CPU, 특정 GPU 또는 기타 연산 장치를 선택할 수 있습니다. |
imgsz | int or tuple | 640 | 추론 대상 이미지 크기입니다. 정사각형을 나타내는 정수 또는 (height, width) 쌍을 지정합니다. 모델 stride에 맞춰 형태가 조정됩니다. |
max_det | int | 300 | 추적 전에 프레임별로 유지할 최대 탐지 수를 지정하여 밀집된 장면에서 솔루션이 처리하는 객체 수를 제한합니다. |
quantize | int or str | None | 추론 정밀도: CPU 이외의 환경에서 PyTorch 및 TorchScript 모델은 16(FP16) 또는 32/unset(FP32)을 사용하며, 다른 형식은 아티팩트와 런타임이 선택하는 정밀도를 사용합니다. 더 이상 사용되지 않는 half 인수를 대체합니다. |
또한 다음과 같은 시각화 설정을 사용할 수 있습니다.
| 인수 | 유형 | 기본값 | 설명 |
|---|---|---|---|
show | bool | False | True이면 주석이 추가된 이미지나 비디오를 창에 표시합니다. 개발 또는 테스트 중 즉각적인 시각적 피드백을 얻는 데 유용합니다. |
show_conf | bool | True | 각 감지 결과의 레이블 옆에 신뢰도 점수를 표시합니다. 각 감지 결과에 대한 모델의 확신도를 파악할 수 있습니다. |
show_labels | bool | True | 시각화 출력에 각 감지 결과의 레이블을 표시합니다. 감지된 객체를 즉시 파악할 수 있습니다. |
작동 방식#
Security Alarm System은 객체 추적을 사용하여 비디오 피드를 모니터링하고 잠재적인 보안 위협을 감지합니다. 프레임에서 감지된 객체 수가 지정된 임계값(records 매개변수로 설정)에 도달하면 감지된 객체가 표시된 이미지 첨부 파일과 함께 이메일 알림을 자동으로 전송합니다.
시스템은 다음 메서드를 제공하는 SecurityAlarm 클래스를 활용합니다.
- 프레임을 처리하고 객체 감지 결과를 추출합니다.
- 감지된 객체 주위에 바운딩 박스를 표시하여 프레임에 주석을 추가합니다.
- 감지 임계값에 도달하면 이메일 알림을 전송합니다.
이 구현은 감지된 객체를 즉시 알려주는 것이 중요한 가정 보안, 소매점 감시 및 기타 모니터링 애플리케이션에 적합합니다.
자주 묻는 질문#
Ultralytics YOLO26은 정확한 실시간 객체 감지를 제공하여 오탐을 줄이고, 보안 경보 시스템이 실제 이벤트에 주로 대응하도록 함으로써 보안 경보 시스템을 개선합니다. 관련
classes만 감지하도록 제한하거나(예: 사람만 감지),conf임계값을 높이거나records를 늘려 오경보를 추가로 줄일 수 있습니다.예.
SecurityAlarm솔루션은 OpenCV가 읽을 수 있는 모든 소스의 프레임을 처리합니다. 여기에는 비디오 파일, 웹캠, IP 카메라의 RTSP 스트림이 포함되므로 기존 카메라 구성에 YOLO26 감지 기능을 추가할 수 있습니다.표준 환경에서 Ultralytics YOLO26을 실행하려면 일반적으로 약 5GB의 여유 디스크 공간이 필요합니다. 여기에는 YOLO26 모델과 추가 종속성을 저장할 공간이 포함됩니다. 클라우드 기반 솔루션인 Ultralytics Platform은 프로젝트 관리와 데이터셋 처리를 효율적으로 제공하여 저장 공간 요구 사항을 최적화할 수 있습니다. Pro Plan을 사용하면 저장 공간이 500GB로 늘어납니다.
Ultralytics YOLO26은 실시간 감지 기능과 높은 정확도를 제공하여 Faster R-CNN이나 SSD 같은 모델보다 뛰어납니다. 단일 단계 아키텍처로 정확도를 저하시키지 않으면서 이미지를 훨씬 빠르게 처리하므로 보안 경보 시스템처럼 시간에 민감한 애플리케이션에 적합합니다.
오탐을 줄이려면 Ultralytics YOLO26 모델을 다양하고 주석이 잘 달린 데이터셋으로 충분히 학습해야 합니다. 하이퍼파라미터 튜닝과 새 데이터를 사용한 정기적인 모델 업데이트는 감지 정확도를 크게 향상할 수 있습니다.
댓글153
질문을 하거나 결과를 공유하거나 다른 사람을 도와주세요.
e9l7a5f
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
Glenn JocherUltralytics(수정됨)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
smtplibwith 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.
e9l7a5f
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
Glenn JocherUltralytics(수정됨)@e9l7a5f you can use YOLOv9 models the same way as you currently use YOLOv8 models; see https://docs.ultralytics.com/models/yolov9. For new projects we recommend YOLO26: https://docs.ultralytics.com/models/yolo26/.
aaurelions
% 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 refusedRizwanMunawar
@aaurelions Hi, thanks for sharing it. You will need to configure the parameters first by following the docs: https://docs.ultralytics.com/guides/security-alarm-system/
1
EQUINOX391
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 :
- have input of CCTV from RTSP
- 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
- customize the email messaging like "ALERT 2 people 2 cars detected, Activity Probability : Suspicious - Stealing"
- also send different email if the people stays too long in the frame.
- keep making new notification IF There's new people(s) inside the frame.
- notified if the people or another object is gone from the frame
- is there any pretrain model that detect something related to crime like hammer, crowbar, spraying can, grafitti, gun, etc?
- 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.
Cheikh-Ahmedand
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!
Glenn JocherUltralytics(수정됨)@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.
Cheikh-Ahmedand
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!
Glenn JocherUltralyticsThank 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.
boukosho
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!
Glenn JocherUltralytics(수정됨)@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.
Cheikh-Ahmedand
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 resultsSincelrely Yours!
Glenn JocherUltralytics(수정됨)@Cheikh-Ahmedand to adjust the confidence threshold in your security alarm system, set the
confargument when initializing the solution. For example:security = solutions.SecurityAlarm(model="yolo26n.pt", conf=0.5) # only detections above 0.5 confidenceThis ensures notifications only trigger for detections exceeding your specified confidence level. For more details, refer to the Security Alarm System guide.
Cheikh-Ahmedand
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!
Glenn JocherUltralytics(수정됨)@Cheikh-Ahmedand in your own
ObjectDetectionclass, passconfwhen 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.
Cheikh-Ahmedand
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!
Glenn JocherUltralyticsTo set the confidence threshold in your custom
ObjectDetectionclass, modify yourpredictmethod like this:def predict(self, im0): results = self.model.predict(im0, classes=[0], conf=0.5) # Add conf here return resultsThe
confparameter should be passed during inference rather than model initialization. For more details on prediction arguments, see the Predict mode documentation.
boukosho
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!
Glenn JocherUltralytics(수정됨)To use your webcam or camera stream with OpenCV's
VideoCapture, replace the file path with:0for 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.
boukosho
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!
Glenn JocherUltralytics@boukosho hi! We're happy to help with YOLO security alarm system questions. Our comprehensive Security Alarm System guide at https://docs.ultralytics.com/guides/security-alarm-system/ provides complete implementation code and documentation. For specific issues, feel free to open a GitHub Discussion with details about your implementation and we'll assist there. 😊
boukosho
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!
Glenn JocherUltralytics(수정됨)To use your webcam, laptop camera, or DVR/NVR cameras with
cv2.VideoCapture, modify the source argument:-
Webcam/Laptop Camera:
cap = cv2.VideoCapture(0)(0 for default camera, 1 for secondary, etc.) -
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.
-
boukosho
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!
Glenn JocherUltralytics(수정됨)For webcam/laptop camera use
cap = cv2.VideoCapture(0)(0=default camera index). For IP cameras, use an RTSP URL likecap = cv2.VideoCapture("rtsp://username:password@camera_ip:port/path"). Theassertchecks if the video source opens successfully. You can find specific camera URL formats in your DVR/NVR documentation.
andrewjang2234
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?
andrewjang2234
sorry I sovle that problem if I want to use my laptob cam what do I have to do?
Glenn JocherUltralytics@andrewjang2234 to use your laptop's camera, set the
capture_indexparameter in theObjectDetectionclass to0(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.
andrewjang2234
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?
Glenn JocherUltralytics@andrewjang2234 the
to_emailrefers 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!