ultralytics-opencv-headless 8.3.246__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- tests/__init__.py +23 -0
- tests/conftest.py +59 -0
- tests/test_cli.py +131 -0
- tests/test_cuda.py +216 -0
- tests/test_engine.py +157 -0
- tests/test_exports.py +309 -0
- tests/test_integrations.py +151 -0
- tests/test_python.py +777 -0
- tests/test_solutions.py +371 -0
- ultralytics/__init__.py +48 -0
- ultralytics/assets/bus.jpg +0 -0
- ultralytics/assets/zidane.jpg +0 -0
- ultralytics/cfg/__init__.py +1026 -0
- ultralytics/cfg/datasets/Argoverse.yaml +78 -0
- ultralytics/cfg/datasets/DOTAv1.5.yaml +37 -0
- ultralytics/cfg/datasets/DOTAv1.yaml +36 -0
- ultralytics/cfg/datasets/GlobalWheat2020.yaml +68 -0
- ultralytics/cfg/datasets/HomeObjects-3K.yaml +32 -0
- ultralytics/cfg/datasets/ImageNet.yaml +2025 -0
- ultralytics/cfg/datasets/Objects365.yaml +447 -0
- ultralytics/cfg/datasets/SKU-110K.yaml +58 -0
- ultralytics/cfg/datasets/VOC.yaml +102 -0
- ultralytics/cfg/datasets/VisDrone.yaml +87 -0
- ultralytics/cfg/datasets/african-wildlife.yaml +25 -0
- ultralytics/cfg/datasets/brain-tumor.yaml +22 -0
- ultralytics/cfg/datasets/carparts-seg.yaml +44 -0
- ultralytics/cfg/datasets/coco-pose.yaml +64 -0
- ultralytics/cfg/datasets/coco.yaml +118 -0
- ultralytics/cfg/datasets/coco128-seg.yaml +101 -0
- ultralytics/cfg/datasets/coco128.yaml +101 -0
- ultralytics/cfg/datasets/coco8-grayscale.yaml +103 -0
- ultralytics/cfg/datasets/coco8-multispectral.yaml +104 -0
- ultralytics/cfg/datasets/coco8-pose.yaml +47 -0
- ultralytics/cfg/datasets/coco8-seg.yaml +101 -0
- ultralytics/cfg/datasets/coco8.yaml +101 -0
- ultralytics/cfg/datasets/construction-ppe.yaml +32 -0
- ultralytics/cfg/datasets/crack-seg.yaml +22 -0
- ultralytics/cfg/datasets/dog-pose.yaml +52 -0
- ultralytics/cfg/datasets/dota8-multispectral.yaml +38 -0
- ultralytics/cfg/datasets/dota8.yaml +35 -0
- ultralytics/cfg/datasets/hand-keypoints.yaml +50 -0
- ultralytics/cfg/datasets/kitti.yaml +27 -0
- ultralytics/cfg/datasets/lvis.yaml +1240 -0
- ultralytics/cfg/datasets/medical-pills.yaml +21 -0
- ultralytics/cfg/datasets/open-images-v7.yaml +663 -0
- ultralytics/cfg/datasets/package-seg.yaml +22 -0
- ultralytics/cfg/datasets/signature.yaml +21 -0
- ultralytics/cfg/datasets/tiger-pose.yaml +41 -0
- ultralytics/cfg/datasets/xView.yaml +155 -0
- ultralytics/cfg/default.yaml +130 -0
- ultralytics/cfg/models/11/yolo11-cls-resnet18.yaml +17 -0
- ultralytics/cfg/models/11/yolo11-cls.yaml +33 -0
- ultralytics/cfg/models/11/yolo11-obb.yaml +50 -0
- ultralytics/cfg/models/11/yolo11-pose.yaml +51 -0
- ultralytics/cfg/models/11/yolo11-seg.yaml +50 -0
- ultralytics/cfg/models/11/yolo11.yaml +50 -0
- ultralytics/cfg/models/11/yoloe-11-seg.yaml +48 -0
- ultralytics/cfg/models/11/yoloe-11.yaml +48 -0
- ultralytics/cfg/models/12/yolo12-cls.yaml +32 -0
- ultralytics/cfg/models/12/yolo12-obb.yaml +48 -0
- ultralytics/cfg/models/12/yolo12-pose.yaml +49 -0
- ultralytics/cfg/models/12/yolo12-seg.yaml +48 -0
- ultralytics/cfg/models/12/yolo12.yaml +48 -0
- ultralytics/cfg/models/rt-detr/rtdetr-l.yaml +53 -0
- ultralytics/cfg/models/rt-detr/rtdetr-resnet101.yaml +45 -0
- ultralytics/cfg/models/rt-detr/rtdetr-resnet50.yaml +45 -0
- ultralytics/cfg/models/rt-detr/rtdetr-x.yaml +57 -0
- ultralytics/cfg/models/v10/yolov10b.yaml +45 -0
- ultralytics/cfg/models/v10/yolov10l.yaml +45 -0
- ultralytics/cfg/models/v10/yolov10m.yaml +45 -0
- ultralytics/cfg/models/v10/yolov10n.yaml +45 -0
- ultralytics/cfg/models/v10/yolov10s.yaml +45 -0
- ultralytics/cfg/models/v10/yolov10x.yaml +45 -0
- ultralytics/cfg/models/v3/yolov3-spp.yaml +49 -0
- ultralytics/cfg/models/v3/yolov3-tiny.yaml +40 -0
- ultralytics/cfg/models/v3/yolov3.yaml +49 -0
- ultralytics/cfg/models/v5/yolov5-p6.yaml +62 -0
- ultralytics/cfg/models/v5/yolov5.yaml +51 -0
- ultralytics/cfg/models/v6/yolov6.yaml +56 -0
- ultralytics/cfg/models/v8/yoloe-v8-seg.yaml +48 -0
- ultralytics/cfg/models/v8/yoloe-v8.yaml +48 -0
- ultralytics/cfg/models/v8/yolov8-cls-resnet101.yaml +28 -0
- ultralytics/cfg/models/v8/yolov8-cls-resnet50.yaml +28 -0
- ultralytics/cfg/models/v8/yolov8-cls.yaml +32 -0
- ultralytics/cfg/models/v8/yolov8-ghost-p2.yaml +58 -0
- ultralytics/cfg/models/v8/yolov8-ghost-p6.yaml +60 -0
- ultralytics/cfg/models/v8/yolov8-ghost.yaml +50 -0
- ultralytics/cfg/models/v8/yolov8-obb.yaml +49 -0
- ultralytics/cfg/models/v8/yolov8-p2.yaml +57 -0
- ultralytics/cfg/models/v8/yolov8-p6.yaml +59 -0
- ultralytics/cfg/models/v8/yolov8-pose-p6.yaml +60 -0
- ultralytics/cfg/models/v8/yolov8-pose.yaml +50 -0
- ultralytics/cfg/models/v8/yolov8-rtdetr.yaml +49 -0
- ultralytics/cfg/models/v8/yolov8-seg-p6.yaml +59 -0
- ultralytics/cfg/models/v8/yolov8-seg.yaml +49 -0
- ultralytics/cfg/models/v8/yolov8-world.yaml +51 -0
- ultralytics/cfg/models/v8/yolov8-worldv2.yaml +49 -0
- ultralytics/cfg/models/v8/yolov8.yaml +49 -0
- ultralytics/cfg/models/v9/yolov9c-seg.yaml +41 -0
- ultralytics/cfg/models/v9/yolov9c.yaml +41 -0
- ultralytics/cfg/models/v9/yolov9e-seg.yaml +64 -0
- ultralytics/cfg/models/v9/yolov9e.yaml +64 -0
- ultralytics/cfg/models/v9/yolov9m.yaml +41 -0
- ultralytics/cfg/models/v9/yolov9s.yaml +41 -0
- ultralytics/cfg/models/v9/yolov9t.yaml +41 -0
- ultralytics/cfg/trackers/botsort.yaml +21 -0
- ultralytics/cfg/trackers/bytetrack.yaml +12 -0
- ultralytics/data/__init__.py +26 -0
- ultralytics/data/annotator.py +66 -0
- ultralytics/data/augment.py +2801 -0
- ultralytics/data/base.py +435 -0
- ultralytics/data/build.py +437 -0
- ultralytics/data/converter.py +855 -0
- ultralytics/data/dataset.py +834 -0
- ultralytics/data/loaders.py +704 -0
- ultralytics/data/scripts/download_weights.sh +18 -0
- ultralytics/data/scripts/get_coco.sh +61 -0
- ultralytics/data/scripts/get_coco128.sh +18 -0
- ultralytics/data/scripts/get_imagenet.sh +52 -0
- ultralytics/data/split.py +138 -0
- ultralytics/data/split_dota.py +344 -0
- ultralytics/data/utils.py +798 -0
- ultralytics/engine/__init__.py +1 -0
- ultralytics/engine/exporter.py +1578 -0
- ultralytics/engine/model.py +1124 -0
- ultralytics/engine/predictor.py +508 -0
- ultralytics/engine/results.py +1522 -0
- ultralytics/engine/trainer.py +974 -0
- ultralytics/engine/tuner.py +448 -0
- ultralytics/engine/validator.py +384 -0
- ultralytics/hub/__init__.py +166 -0
- ultralytics/hub/auth.py +151 -0
- ultralytics/hub/google/__init__.py +174 -0
- ultralytics/hub/session.py +422 -0
- ultralytics/hub/utils.py +162 -0
- ultralytics/models/__init__.py +9 -0
- ultralytics/models/fastsam/__init__.py +7 -0
- ultralytics/models/fastsam/model.py +79 -0
- ultralytics/models/fastsam/predict.py +169 -0
- ultralytics/models/fastsam/utils.py +23 -0
- ultralytics/models/fastsam/val.py +38 -0
- ultralytics/models/nas/__init__.py +7 -0
- ultralytics/models/nas/model.py +98 -0
- ultralytics/models/nas/predict.py +56 -0
- ultralytics/models/nas/val.py +38 -0
- ultralytics/models/rtdetr/__init__.py +7 -0
- ultralytics/models/rtdetr/model.py +63 -0
- ultralytics/models/rtdetr/predict.py +88 -0
- ultralytics/models/rtdetr/train.py +89 -0
- ultralytics/models/rtdetr/val.py +216 -0
- ultralytics/models/sam/__init__.py +25 -0
- ultralytics/models/sam/amg.py +275 -0
- ultralytics/models/sam/build.py +365 -0
- ultralytics/models/sam/build_sam3.py +377 -0
- ultralytics/models/sam/model.py +169 -0
- ultralytics/models/sam/modules/__init__.py +1 -0
- ultralytics/models/sam/modules/blocks.py +1067 -0
- ultralytics/models/sam/modules/decoders.py +495 -0
- ultralytics/models/sam/modules/encoders.py +794 -0
- ultralytics/models/sam/modules/memory_attention.py +298 -0
- ultralytics/models/sam/modules/sam.py +1160 -0
- ultralytics/models/sam/modules/tiny_encoder.py +979 -0
- ultralytics/models/sam/modules/transformer.py +344 -0
- ultralytics/models/sam/modules/utils.py +512 -0
- ultralytics/models/sam/predict.py +3940 -0
- ultralytics/models/sam/sam3/__init__.py +3 -0
- ultralytics/models/sam/sam3/decoder.py +546 -0
- ultralytics/models/sam/sam3/encoder.py +529 -0
- ultralytics/models/sam/sam3/geometry_encoders.py +415 -0
- ultralytics/models/sam/sam3/maskformer_segmentation.py +286 -0
- ultralytics/models/sam/sam3/model_misc.py +199 -0
- ultralytics/models/sam/sam3/necks.py +129 -0
- ultralytics/models/sam/sam3/sam3_image.py +339 -0
- ultralytics/models/sam/sam3/text_encoder_ve.py +307 -0
- ultralytics/models/sam/sam3/vitdet.py +547 -0
- ultralytics/models/sam/sam3/vl_combiner.py +160 -0
- ultralytics/models/utils/__init__.py +1 -0
- ultralytics/models/utils/loss.py +466 -0
- ultralytics/models/utils/ops.py +315 -0
- ultralytics/models/yolo/__init__.py +7 -0
- ultralytics/models/yolo/classify/__init__.py +7 -0
- ultralytics/models/yolo/classify/predict.py +90 -0
- ultralytics/models/yolo/classify/train.py +202 -0
- ultralytics/models/yolo/classify/val.py +216 -0
- ultralytics/models/yolo/detect/__init__.py +7 -0
- ultralytics/models/yolo/detect/predict.py +122 -0
- ultralytics/models/yolo/detect/train.py +227 -0
- ultralytics/models/yolo/detect/val.py +507 -0
- ultralytics/models/yolo/model.py +430 -0
- ultralytics/models/yolo/obb/__init__.py +7 -0
- ultralytics/models/yolo/obb/predict.py +56 -0
- ultralytics/models/yolo/obb/train.py +79 -0
- ultralytics/models/yolo/obb/val.py +302 -0
- ultralytics/models/yolo/pose/__init__.py +7 -0
- ultralytics/models/yolo/pose/predict.py +65 -0
- ultralytics/models/yolo/pose/train.py +110 -0
- ultralytics/models/yolo/pose/val.py +248 -0
- ultralytics/models/yolo/segment/__init__.py +7 -0
- ultralytics/models/yolo/segment/predict.py +109 -0
- ultralytics/models/yolo/segment/train.py +69 -0
- ultralytics/models/yolo/segment/val.py +307 -0
- ultralytics/models/yolo/world/__init__.py +5 -0
- ultralytics/models/yolo/world/train.py +173 -0
- ultralytics/models/yolo/world/train_world.py +178 -0
- ultralytics/models/yolo/yoloe/__init__.py +22 -0
- ultralytics/models/yolo/yoloe/predict.py +162 -0
- ultralytics/models/yolo/yoloe/train.py +287 -0
- ultralytics/models/yolo/yoloe/train_seg.py +122 -0
- ultralytics/models/yolo/yoloe/val.py +206 -0
- ultralytics/nn/__init__.py +27 -0
- ultralytics/nn/autobackend.py +958 -0
- ultralytics/nn/modules/__init__.py +182 -0
- ultralytics/nn/modules/activation.py +54 -0
- ultralytics/nn/modules/block.py +1947 -0
- ultralytics/nn/modules/conv.py +669 -0
- ultralytics/nn/modules/head.py +1183 -0
- ultralytics/nn/modules/transformer.py +793 -0
- ultralytics/nn/modules/utils.py +159 -0
- ultralytics/nn/tasks.py +1768 -0
- ultralytics/nn/text_model.py +356 -0
- ultralytics/py.typed +1 -0
- ultralytics/solutions/__init__.py +41 -0
- ultralytics/solutions/ai_gym.py +108 -0
- ultralytics/solutions/analytics.py +264 -0
- ultralytics/solutions/config.py +107 -0
- ultralytics/solutions/distance_calculation.py +123 -0
- ultralytics/solutions/heatmap.py +125 -0
- ultralytics/solutions/instance_segmentation.py +86 -0
- ultralytics/solutions/object_blurrer.py +89 -0
- ultralytics/solutions/object_counter.py +190 -0
- ultralytics/solutions/object_cropper.py +87 -0
- ultralytics/solutions/parking_management.py +280 -0
- ultralytics/solutions/queue_management.py +93 -0
- ultralytics/solutions/region_counter.py +133 -0
- ultralytics/solutions/security_alarm.py +151 -0
- ultralytics/solutions/similarity_search.py +219 -0
- ultralytics/solutions/solutions.py +828 -0
- ultralytics/solutions/speed_estimation.py +114 -0
- ultralytics/solutions/streamlit_inference.py +260 -0
- ultralytics/solutions/templates/similarity-search.html +156 -0
- ultralytics/solutions/trackzone.py +88 -0
- ultralytics/solutions/vision_eye.py +67 -0
- ultralytics/trackers/__init__.py +7 -0
- ultralytics/trackers/basetrack.py +115 -0
- ultralytics/trackers/bot_sort.py +257 -0
- ultralytics/trackers/byte_tracker.py +469 -0
- ultralytics/trackers/track.py +116 -0
- ultralytics/trackers/utils/__init__.py +1 -0
- ultralytics/trackers/utils/gmc.py +339 -0
- ultralytics/trackers/utils/kalman_filter.py +482 -0
- ultralytics/trackers/utils/matching.py +154 -0
- ultralytics/utils/__init__.py +1450 -0
- ultralytics/utils/autobatch.py +118 -0
- ultralytics/utils/autodevice.py +205 -0
- ultralytics/utils/benchmarks.py +728 -0
- ultralytics/utils/callbacks/__init__.py +5 -0
- ultralytics/utils/callbacks/base.py +233 -0
- ultralytics/utils/callbacks/clearml.py +146 -0
- ultralytics/utils/callbacks/comet.py +625 -0
- ultralytics/utils/callbacks/dvc.py +197 -0
- ultralytics/utils/callbacks/hub.py +110 -0
- ultralytics/utils/callbacks/mlflow.py +134 -0
- ultralytics/utils/callbacks/neptune.py +126 -0
- ultralytics/utils/callbacks/platform.py +313 -0
- ultralytics/utils/callbacks/raytune.py +42 -0
- ultralytics/utils/callbacks/tensorboard.py +123 -0
- ultralytics/utils/callbacks/wb.py +188 -0
- ultralytics/utils/checks.py +1006 -0
- ultralytics/utils/cpu.py +85 -0
- ultralytics/utils/dist.py +123 -0
- ultralytics/utils/downloads.py +529 -0
- ultralytics/utils/errors.py +35 -0
- ultralytics/utils/events.py +113 -0
- ultralytics/utils/export/__init__.py +7 -0
- ultralytics/utils/export/engine.py +237 -0
- ultralytics/utils/export/imx.py +315 -0
- ultralytics/utils/export/tensorflow.py +231 -0
- ultralytics/utils/files.py +219 -0
- ultralytics/utils/git.py +137 -0
- ultralytics/utils/instance.py +484 -0
- ultralytics/utils/logger.py +501 -0
- ultralytics/utils/loss.py +849 -0
- ultralytics/utils/metrics.py +1563 -0
- ultralytics/utils/nms.py +337 -0
- ultralytics/utils/ops.py +664 -0
- ultralytics/utils/patches.py +201 -0
- ultralytics/utils/plotting.py +1045 -0
- ultralytics/utils/tal.py +403 -0
- ultralytics/utils/torch_utils.py +984 -0
- ultralytics/utils/tqdm.py +440 -0
- ultralytics/utils/triton.py +112 -0
- ultralytics/utils/tuner.py +160 -0
- ultralytics_opencv_headless-8.3.246.dist-info/METADATA +374 -0
- ultralytics_opencv_headless-8.3.246.dist-info/RECORD +298 -0
- ultralytics_opencv_headless-8.3.246.dist-info/WHEEL +5 -0
- ultralytics_opencv_headless-8.3.246.dist-info/entry_points.txt +3 -0
- ultralytics_opencv_headless-8.3.246.dist-info/licenses/LICENSE +661 -0
- ultralytics_opencv_headless-8.3.246.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import cv2
|
|
9
|
+
import numpy as np
|
|
10
|
+
|
|
11
|
+
from ultralytics.solutions.solutions import BaseSolution, SolutionAnnotator, SolutionResults
|
|
12
|
+
from ultralytics.utils import LOGGER
|
|
13
|
+
from ultralytics.utils.checks import check_imshow
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ParkingPtsSelection:
|
|
17
|
+
"""A class for selecting and managing parking zone points on images using a Tkinter-based UI.
|
|
18
|
+
|
|
19
|
+
This class provides functionality to upload an image, select points to define parking zones, and save the selected
|
|
20
|
+
points to a JSON file. It uses Tkinter for the graphical user interface.
|
|
21
|
+
|
|
22
|
+
Attributes:
|
|
23
|
+
tk (module): The Tkinter module for GUI operations.
|
|
24
|
+
filedialog (module): Tkinter's filedialog module for file selection operations.
|
|
25
|
+
messagebox (module): Tkinter's messagebox module for displaying message boxes.
|
|
26
|
+
master (tk.Tk): The main Tkinter window.
|
|
27
|
+
canvas (tk.Canvas): The canvas widget for displaying the image and drawing bounding boxes.
|
|
28
|
+
image (PIL.Image.Image): The uploaded image.
|
|
29
|
+
canvas_image (ImageTk.PhotoImage): The image displayed on the canvas.
|
|
30
|
+
rg_data (list[list[tuple[int, int]]]): List of bounding boxes, each defined by 4 points.
|
|
31
|
+
current_box (list[tuple[int, int]]): Temporary storage for the points of the current bounding box.
|
|
32
|
+
imgw (int): Original width of the uploaded image.
|
|
33
|
+
imgh (int): Original height of the uploaded image.
|
|
34
|
+
canvas_max_width (int): Maximum width of the canvas.
|
|
35
|
+
canvas_max_height (int): Maximum height of the canvas.
|
|
36
|
+
|
|
37
|
+
Methods:
|
|
38
|
+
initialize_properties: Initialize properties for image, canvas, bounding boxes, and dimensions.
|
|
39
|
+
upload_image: Upload and display an image on the canvas, resizing it to fit within specified dimensions.
|
|
40
|
+
on_canvas_click: Handle mouse clicks to add points for bounding boxes on the canvas.
|
|
41
|
+
draw_box: Draw a bounding box on the canvas using the provided coordinates.
|
|
42
|
+
remove_last_bounding_box: Remove the last bounding box from the list and redraw the canvas.
|
|
43
|
+
redraw_canvas: Redraw the canvas with the image and all bounding boxes.
|
|
44
|
+
save_to_json: Save the selected parking zone points to a JSON file with scaled coordinates.
|
|
45
|
+
|
|
46
|
+
Examples:
|
|
47
|
+
>>> parking_selector = ParkingPtsSelection()
|
|
48
|
+
>>> # Use the GUI to upload an image, select parking zones, and save the data
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
def __init__(self) -> None:
|
|
52
|
+
"""Initialize the ParkingPtsSelection class, setting up UI and properties for parking zone point selection."""
|
|
53
|
+
try: # Check if tkinter is installed
|
|
54
|
+
import tkinter as tk
|
|
55
|
+
from tkinter import filedialog, messagebox
|
|
56
|
+
except ImportError: # Display error with recommendations
|
|
57
|
+
import platform
|
|
58
|
+
|
|
59
|
+
install_cmd = {
|
|
60
|
+
"Linux": "sudo apt install python3-tk (Debian/Ubuntu) | sudo dnf install python3-tkinter (Fedora) | "
|
|
61
|
+
"sudo pacman -S tk (Arch)",
|
|
62
|
+
"Windows": "reinstall Python and enable the checkbox `tcl/tk and IDLE` on **Optional Features** during installation",
|
|
63
|
+
"Darwin": "reinstall Python from https://www.python.org/downloads/macos/ or `brew install python-tk`",
|
|
64
|
+
}.get(platform.system(), "Unknown OS. Check your Python installation.")
|
|
65
|
+
|
|
66
|
+
LOGGER.warning(f" Tkinter is not configured or supported. Potential fix: {install_cmd}")
|
|
67
|
+
return
|
|
68
|
+
|
|
69
|
+
if not check_imshow(warn=True):
|
|
70
|
+
return
|
|
71
|
+
|
|
72
|
+
self.tk, self.filedialog, self.messagebox = tk, filedialog, messagebox
|
|
73
|
+
self.master = self.tk.Tk() # Reference to the main application window
|
|
74
|
+
self.master.title("Ultralytics Parking Zones Points Selector")
|
|
75
|
+
self.master.resizable(False, False)
|
|
76
|
+
|
|
77
|
+
self.canvas = self.tk.Canvas(self.master, bg="white") # Canvas widget for displaying images
|
|
78
|
+
self.canvas.pack(side=self.tk.BOTTOM)
|
|
79
|
+
|
|
80
|
+
self.image = None # Variable to store the loaded image
|
|
81
|
+
self.canvas_image = None # Reference to the image displayed on the canvas
|
|
82
|
+
self.canvas_max_width = None # Maximum allowed width for the canvas
|
|
83
|
+
self.canvas_max_height = None # Maximum allowed height for the canvas
|
|
84
|
+
self.rg_data = None # Data for region annotation management
|
|
85
|
+
self.current_box = None # Stores the currently selected bounding box
|
|
86
|
+
self.imgh = None # Height of the current image
|
|
87
|
+
self.imgw = None # Width of the current image
|
|
88
|
+
|
|
89
|
+
# Button frame with buttons
|
|
90
|
+
button_frame = self.tk.Frame(self.master)
|
|
91
|
+
button_frame.pack(side=self.tk.TOP)
|
|
92
|
+
|
|
93
|
+
for text, cmd in [
|
|
94
|
+
("Upload Image", self.upload_image),
|
|
95
|
+
("Remove Last Bounding Box", self.remove_last_bounding_box),
|
|
96
|
+
("Save", self.save_to_json),
|
|
97
|
+
]:
|
|
98
|
+
self.tk.Button(button_frame, text=text, command=cmd).pack(side=self.tk.LEFT)
|
|
99
|
+
|
|
100
|
+
self.initialize_properties()
|
|
101
|
+
self.master.mainloop()
|
|
102
|
+
|
|
103
|
+
def initialize_properties(self) -> None:
|
|
104
|
+
"""Initialize properties for image, canvas, bounding boxes, and dimensions."""
|
|
105
|
+
self.image = self.canvas_image = None
|
|
106
|
+
self.rg_data, self.current_box = [], []
|
|
107
|
+
self.imgw = self.imgh = 0
|
|
108
|
+
self.canvas_max_width, self.canvas_max_height = 1280, 720
|
|
109
|
+
|
|
110
|
+
def upload_image(self) -> None:
|
|
111
|
+
"""Upload and display an image on the canvas, resizing it to fit within specified dimensions."""
|
|
112
|
+
from PIL import Image, ImageTk # Scoped import because ImageTk requires tkinter package
|
|
113
|
+
|
|
114
|
+
file = self.filedialog.askopenfilename(filetypes=[("Image Files", "*.png *.jpg *.jpeg")])
|
|
115
|
+
if not file:
|
|
116
|
+
LOGGER.info("No image selected.")
|
|
117
|
+
return
|
|
118
|
+
|
|
119
|
+
self.image = Image.open(file)
|
|
120
|
+
self.imgw, self.imgh = self.image.size
|
|
121
|
+
aspect_ratio = self.imgw / self.imgh
|
|
122
|
+
canvas_width = (
|
|
123
|
+
min(self.canvas_max_width, self.imgw) if aspect_ratio > 1 else int(self.canvas_max_height * aspect_ratio)
|
|
124
|
+
)
|
|
125
|
+
canvas_height = (
|
|
126
|
+
min(self.canvas_max_height, self.imgh) if aspect_ratio <= 1 else int(canvas_width / aspect_ratio)
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
self.canvas.config(width=canvas_width, height=canvas_height)
|
|
130
|
+
self.canvas_image = ImageTk.PhotoImage(self.image.resize((canvas_width, canvas_height)))
|
|
131
|
+
self.canvas.create_image(0, 0, anchor=self.tk.NW, image=self.canvas_image)
|
|
132
|
+
self.canvas.bind("<Button-1>", self.on_canvas_click)
|
|
133
|
+
|
|
134
|
+
self.rg_data.clear(), self.current_box.clear()
|
|
135
|
+
|
|
136
|
+
def on_canvas_click(self, event) -> None:
|
|
137
|
+
"""Handle mouse clicks to add points for bounding boxes on the canvas."""
|
|
138
|
+
self.current_box.append((event.x, event.y))
|
|
139
|
+
self.canvas.create_oval(event.x - 3, event.y - 3, event.x + 3, event.y + 3, fill="red")
|
|
140
|
+
if len(self.current_box) == 4:
|
|
141
|
+
self.rg_data.append(self.current_box.copy())
|
|
142
|
+
self.draw_box(self.current_box)
|
|
143
|
+
self.current_box.clear()
|
|
144
|
+
|
|
145
|
+
def draw_box(self, box: list[tuple[int, int]]) -> None:
|
|
146
|
+
"""Draw a bounding box on the canvas using the provided coordinates."""
|
|
147
|
+
for i in range(4):
|
|
148
|
+
self.canvas.create_line(box[i], box[(i + 1) % 4], fill="blue", width=2)
|
|
149
|
+
|
|
150
|
+
def remove_last_bounding_box(self) -> None:
|
|
151
|
+
"""Remove the last bounding box from the list and redraw the canvas."""
|
|
152
|
+
if not self.rg_data:
|
|
153
|
+
self.messagebox.showwarning("Warning", "No bounding boxes to remove.")
|
|
154
|
+
return
|
|
155
|
+
self.rg_data.pop()
|
|
156
|
+
self.redraw_canvas()
|
|
157
|
+
|
|
158
|
+
def redraw_canvas(self) -> None:
|
|
159
|
+
"""Redraw the canvas with the image and all bounding boxes."""
|
|
160
|
+
self.canvas.delete("all")
|
|
161
|
+
self.canvas.create_image(0, 0, anchor=self.tk.NW, image=self.canvas_image)
|
|
162
|
+
for box in self.rg_data:
|
|
163
|
+
self.draw_box(box)
|
|
164
|
+
|
|
165
|
+
def save_to_json(self) -> None:
|
|
166
|
+
"""Save the selected parking zone points to a JSON file with scaled coordinates."""
|
|
167
|
+
scale_w, scale_h = self.imgw / self.canvas.winfo_width(), self.imgh / self.canvas.winfo_height()
|
|
168
|
+
data = [{"points": [(int(x * scale_w), int(y * scale_h)) for x, y in box]} for box in self.rg_data]
|
|
169
|
+
|
|
170
|
+
from io import StringIO # Function level import, as it's only required to store coordinates
|
|
171
|
+
|
|
172
|
+
write_buffer = StringIO()
|
|
173
|
+
json.dump(data, write_buffer, indent=4)
|
|
174
|
+
with open("bounding_boxes.json", "w", encoding="utf-8") as f:
|
|
175
|
+
f.write(write_buffer.getvalue())
|
|
176
|
+
self.messagebox.showinfo("Success", "Bounding boxes saved to bounding_boxes.json")
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
class ParkingManagement(BaseSolution):
|
|
180
|
+
"""Manages parking occupancy and availability using YOLO model for real-time monitoring and visualization.
|
|
181
|
+
|
|
182
|
+
This class extends BaseSolution to provide functionality for parking lot management, including detection of occupied
|
|
183
|
+
spaces, visualization of parking regions, and display of occupancy statistics.
|
|
184
|
+
|
|
185
|
+
Attributes:
|
|
186
|
+
json_file (str): Path to the JSON file containing parking region details.
|
|
187
|
+
json (list[dict]): Loaded JSON data containing parking region information.
|
|
188
|
+
pr_info (dict[str, int]): Dictionary storing parking information (Occupancy and Available spaces).
|
|
189
|
+
arc (tuple[int, int, int]): BGR color tuple for available region visualization.
|
|
190
|
+
occ (tuple[int, int, int]): BGR color tuple for occupied region visualization.
|
|
191
|
+
dc (tuple[int, int, int]): BGR color tuple for centroid visualization of detected objects.
|
|
192
|
+
|
|
193
|
+
Methods:
|
|
194
|
+
process: Process the input image for parking lot management and visualization.
|
|
195
|
+
|
|
196
|
+
Examples:
|
|
197
|
+
>>> from ultralytics.solutions import ParkingManagement
|
|
198
|
+
>>> parking_manager = ParkingManagement(model="yolo11n.pt", json_file="parking_regions.json")
|
|
199
|
+
>>> print(f"Occupied spaces: {parking_manager.pr_info['Occupancy']}")
|
|
200
|
+
>>> print(f"Available spaces: {parking_manager.pr_info['Available']}")
|
|
201
|
+
"""
|
|
202
|
+
|
|
203
|
+
def __init__(self, **kwargs: Any) -> None:
|
|
204
|
+
"""Initialize the parking management system with a YOLO model and visualization settings."""
|
|
205
|
+
super().__init__(**kwargs)
|
|
206
|
+
|
|
207
|
+
self.json_file = self.CFG["json_file"] # Load parking regions JSON data
|
|
208
|
+
if not self.json_file:
|
|
209
|
+
LOGGER.warning("ParkingManagement requires `json_file` with parking region coordinates.")
|
|
210
|
+
raise ValueError("❌ JSON file path cannot be empty.")
|
|
211
|
+
|
|
212
|
+
with open(self.json_file, encoding="utf-8") as f:
|
|
213
|
+
self.json = json.load(f)
|
|
214
|
+
|
|
215
|
+
self.pr_info = {"Occupancy": 0, "Available": 0} # Dictionary for parking information
|
|
216
|
+
|
|
217
|
+
self.arc = (0, 0, 255) # Available region color
|
|
218
|
+
self.occ = (0, 255, 0) # Occupied region color
|
|
219
|
+
self.dc = (255, 0, 189) # Centroid color for each box
|
|
220
|
+
|
|
221
|
+
def process(self, im0: np.ndarray) -> SolutionResults:
|
|
222
|
+
"""Process the input image for parking lot management and visualization.
|
|
223
|
+
|
|
224
|
+
This function analyzes the input image, extracts tracks, and determines the occupancy status of parking regions
|
|
225
|
+
defined in the JSON file. It annotates the image with occupied and available parking spots, and updates the
|
|
226
|
+
parking information.
|
|
227
|
+
|
|
228
|
+
Args:
|
|
229
|
+
im0 (np.ndarray): The input inference image.
|
|
230
|
+
|
|
231
|
+
Returns:
|
|
232
|
+
(SolutionResults): Contains processed image `plot_im`, 'filled_slots' (number of occupied parking slots),
|
|
233
|
+
'available_slots' (number of available parking slots), and 'total_tracks' (total number of
|
|
234
|
+
tracked objects).
|
|
235
|
+
|
|
236
|
+
Examples:
|
|
237
|
+
>>> parking_manager = ParkingManagement(json_file="parking_regions.json")
|
|
238
|
+
>>> image = cv2.imread("parking_lot.jpg")
|
|
239
|
+
>>> results = parking_manager.process(image)
|
|
240
|
+
"""
|
|
241
|
+
self.extract_tracks(im0) # Extract tracks from im0
|
|
242
|
+
available_slots, occupied_slots = len(self.json), 0
|
|
243
|
+
annotator = SolutionAnnotator(im0, self.line_width) # Initialize annotator
|
|
244
|
+
|
|
245
|
+
for region in self.json:
|
|
246
|
+
# Convert points to a NumPy array with the correct dtype and reshape properly
|
|
247
|
+
region_polygon = np.array(region["points"], dtype=np.int32).reshape((-1, 1, 2))
|
|
248
|
+
region_occupied = False
|
|
249
|
+
for box, cls in zip(self.boxes, self.clss):
|
|
250
|
+
xc, yc = int((box[0] + box[2]) / 2), int((box[1] + box[3]) / 2)
|
|
251
|
+
inside_distance = cv2.pointPolygonTest(region_polygon, (xc, yc), False)
|
|
252
|
+
if inside_distance >= 0:
|
|
253
|
+
# cv2.circle(im0, (xc, yc), radius=self.line_width * 4, color=self.dc, thickness=-1)
|
|
254
|
+
annotator.display_objects_labels(
|
|
255
|
+
im0, self.model.names[int(cls)], (104, 31, 17), (255, 255, 255), xc, yc, 10
|
|
256
|
+
)
|
|
257
|
+
region_occupied = True
|
|
258
|
+
break
|
|
259
|
+
if region_occupied:
|
|
260
|
+
occupied_slots += 1
|
|
261
|
+
available_slots -= 1
|
|
262
|
+
# Plot regions
|
|
263
|
+
cv2.polylines(
|
|
264
|
+
im0, [region_polygon], isClosed=True, color=self.occ if region_occupied else self.arc, thickness=2
|
|
265
|
+
)
|
|
266
|
+
|
|
267
|
+
self.pr_info["Occupancy"], self.pr_info["Available"] = occupied_slots, available_slots
|
|
268
|
+
|
|
269
|
+
annotator.display_analytics(im0, self.pr_info, (104, 31, 17), (255, 255, 255), 10)
|
|
270
|
+
|
|
271
|
+
plot_im = annotator.result()
|
|
272
|
+
self.display_output(plot_im) # Display output with base class function
|
|
273
|
+
|
|
274
|
+
# Return SolutionResults
|
|
275
|
+
return SolutionResults(
|
|
276
|
+
plot_im=plot_im,
|
|
277
|
+
filled_slots=self.pr_info["Occupancy"],
|
|
278
|
+
available_slots=self.pr_info["Available"],
|
|
279
|
+
total_tracks=len(self.track_ids),
|
|
280
|
+
)
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from ultralytics.solutions.solutions import BaseSolution, SolutionAnnotator, SolutionResults
|
|
6
|
+
from ultralytics.utils.plotting import colors
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class QueueManager(BaseSolution):
|
|
10
|
+
"""Manages queue counting in real-time video streams based on object tracks.
|
|
11
|
+
|
|
12
|
+
This class extends BaseSolution to provide functionality for tracking and counting objects within a specified region
|
|
13
|
+
in video frames.
|
|
14
|
+
|
|
15
|
+
Attributes:
|
|
16
|
+
counts (int): The current count of objects in the queue.
|
|
17
|
+
rect_color (tuple[int, int, int]): BGR color tuple for drawing the queue region rectangle.
|
|
18
|
+
region_length (int): The number of points defining the queue region.
|
|
19
|
+
track_line (list[tuple[int, int]]): List of track line coordinates.
|
|
20
|
+
track_history (dict[int, list[tuple[int, int]]]): Dictionary storing tracking history for each object.
|
|
21
|
+
|
|
22
|
+
Methods:
|
|
23
|
+
initialize_region: Initialize the queue region.
|
|
24
|
+
process: Process a single frame for queue management.
|
|
25
|
+
extract_tracks: Extract object tracks from the current frame.
|
|
26
|
+
store_tracking_history: Store the tracking history for an object.
|
|
27
|
+
display_output: Display the processed output.
|
|
28
|
+
|
|
29
|
+
Examples:
|
|
30
|
+
>>> cap = cv2.VideoCapture("path/to/video.mp4")
|
|
31
|
+
>>> queue_manager = QueueManager(region=[100, 100, 200, 200, 300, 300])
|
|
32
|
+
>>> while cap.isOpened():
|
|
33
|
+
... success, im0 = cap.read()
|
|
34
|
+
... if not success:
|
|
35
|
+
... break
|
|
36
|
+
... results = queue_manager.process(im0)
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
def __init__(self, **kwargs: Any) -> None:
|
|
40
|
+
"""Initialize the QueueManager with parameters for tracking and counting objects in a video stream."""
|
|
41
|
+
super().__init__(**kwargs)
|
|
42
|
+
self.initialize_region()
|
|
43
|
+
self.counts = 0 # Queue counts information
|
|
44
|
+
self.rect_color = (255, 255, 255) # Rectangle color for visualization
|
|
45
|
+
self.region_length = len(self.region) # Store region length for further usage
|
|
46
|
+
|
|
47
|
+
def process(self, im0) -> SolutionResults:
|
|
48
|
+
"""Process queue management for a single frame of video.
|
|
49
|
+
|
|
50
|
+
Args:
|
|
51
|
+
im0 (np.ndarray): Input image for processing, typically a frame from a video stream.
|
|
52
|
+
|
|
53
|
+
Returns:
|
|
54
|
+
(SolutionResults): Contains processed image `im0`, 'queue_count' (int, number of objects in the queue) and
|
|
55
|
+
'total_tracks' (int, total number of tracked objects).
|
|
56
|
+
|
|
57
|
+
Examples:
|
|
58
|
+
>>> queue_manager = QueueManager()
|
|
59
|
+
>>> frame = cv2.imread("frame.jpg")
|
|
60
|
+
>>> results = queue_manager.process(frame)
|
|
61
|
+
"""
|
|
62
|
+
self.counts = 0 # Reset counts every frame
|
|
63
|
+
self.extract_tracks(im0) # Extract tracks from the current frame
|
|
64
|
+
annotator = SolutionAnnotator(im0, line_width=self.line_width) # Initialize annotator
|
|
65
|
+
annotator.draw_region(reg_pts=self.region, color=self.rect_color, thickness=self.line_width * 2) # Draw region
|
|
66
|
+
|
|
67
|
+
for box, track_id, cls, conf in zip(self.boxes, self.track_ids, self.clss, self.confs):
|
|
68
|
+
# Draw bounding box and counting region
|
|
69
|
+
annotator.box_label(box, label=self.adjust_box_label(cls, conf, track_id), color=colors(track_id, True))
|
|
70
|
+
self.store_tracking_history(track_id, box) # Store track history
|
|
71
|
+
|
|
72
|
+
# Cache frequently accessed attributes
|
|
73
|
+
track_history = self.track_history.get(track_id, [])
|
|
74
|
+
|
|
75
|
+
# Store previous position of track and check if the object is inside the counting region
|
|
76
|
+
prev_position = None
|
|
77
|
+
if len(track_history) > 1:
|
|
78
|
+
prev_position = track_history[-2]
|
|
79
|
+
if self.region_length >= 3 and prev_position and self.r_s.contains(self.Point(self.track_line[-1])):
|
|
80
|
+
self.counts += 1
|
|
81
|
+
|
|
82
|
+
# Display queue counts
|
|
83
|
+
annotator.queue_counts_display(
|
|
84
|
+
f"Queue Counts : {self.counts}",
|
|
85
|
+
points=self.region,
|
|
86
|
+
region_color=self.rect_color,
|
|
87
|
+
txt_color=(104, 31, 17),
|
|
88
|
+
)
|
|
89
|
+
plot_im = annotator.result()
|
|
90
|
+
self.display_output(plot_im) # Display output with base class function
|
|
91
|
+
|
|
92
|
+
# Return a SolutionResults object with processed data
|
|
93
|
+
return SolutionResults(plot_im=plot_im, queue_count=self.counts, total_tracks=len(self.track_ids))
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
|
|
9
|
+
from ultralytics.solutions.solutions import BaseSolution, SolutionAnnotator, SolutionResults
|
|
10
|
+
from ultralytics.utils.plotting import colors
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class RegionCounter(BaseSolution):
|
|
14
|
+
"""A class for real-time counting of objects within user-defined regions in a video stream.
|
|
15
|
+
|
|
16
|
+
This class inherits from `BaseSolution` and provides functionality to define polygonal regions in a video frame,
|
|
17
|
+
track objects, and count those objects that pass through each defined region. Useful for applications requiring
|
|
18
|
+
counting in specified areas, such as monitoring zones or segmented sections.
|
|
19
|
+
|
|
20
|
+
Attributes:
|
|
21
|
+
region_template (dict): Template for creating new counting regions with default attributes including name,
|
|
22
|
+
polygon coordinates, and display colors.
|
|
23
|
+
counting_regions (list): List storing all defined regions, where each entry is based on `region_template` and
|
|
24
|
+
includes specific region settings like name, coordinates, and color.
|
|
25
|
+
region_counts (dict): Dictionary storing the count of objects for each named region.
|
|
26
|
+
|
|
27
|
+
Methods:
|
|
28
|
+
add_region: Add a new counting region with specified attributes.
|
|
29
|
+
process: Process video frames to count objects in each region.
|
|
30
|
+
initialize_regions: Initialize zones to count the objects in each one. Zones could be multiple as well.
|
|
31
|
+
|
|
32
|
+
Examples:
|
|
33
|
+
Initialize a RegionCounter and add a counting region
|
|
34
|
+
>>> counter = RegionCounter()
|
|
35
|
+
>>> counter.add_region("Zone1", [(100, 100), (200, 100), (200, 200), (100, 200)], (255, 0, 0), (255, 255, 255))
|
|
36
|
+
>>> results = counter.process(frame)
|
|
37
|
+
>>> print(f"Total tracks: {results.total_tracks}")
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
def __init__(self, **kwargs: Any) -> None:
|
|
41
|
+
"""Initialize the RegionCounter for real-time object counting in user-defined regions."""
|
|
42
|
+
super().__init__(**kwargs)
|
|
43
|
+
self.region_template = {
|
|
44
|
+
"name": "Default Region",
|
|
45
|
+
"polygon": None,
|
|
46
|
+
"counts": 0,
|
|
47
|
+
"region_color": (255, 255, 255),
|
|
48
|
+
"text_color": (0, 0, 0),
|
|
49
|
+
}
|
|
50
|
+
self.region_counts = {}
|
|
51
|
+
self.counting_regions = []
|
|
52
|
+
self.initialize_regions()
|
|
53
|
+
|
|
54
|
+
def add_region(
|
|
55
|
+
self,
|
|
56
|
+
name: str,
|
|
57
|
+
polygon_points: list[tuple],
|
|
58
|
+
region_color: tuple[int, int, int],
|
|
59
|
+
text_color: tuple[int, int, int],
|
|
60
|
+
) -> dict[str, Any]:
|
|
61
|
+
"""Add a new region to the counting list based on the provided template with specific attributes.
|
|
62
|
+
|
|
63
|
+
Args:
|
|
64
|
+
name (str): Name assigned to the new region.
|
|
65
|
+
polygon_points (list[tuple]): List of (x, y) coordinates defining the region's polygon.
|
|
66
|
+
region_color (tuple[int, int, int]): BGR color for region visualization.
|
|
67
|
+
text_color (tuple[int, int, int]): BGR color for the text within the region.
|
|
68
|
+
|
|
69
|
+
Returns:
|
|
70
|
+
(dict[str, Any]): Region information including name, polygon, and display colors.
|
|
71
|
+
"""
|
|
72
|
+
region = self.region_template.copy()
|
|
73
|
+
region.update(
|
|
74
|
+
{
|
|
75
|
+
"name": name,
|
|
76
|
+
"polygon": self.Polygon(polygon_points),
|
|
77
|
+
"region_color": region_color,
|
|
78
|
+
"text_color": text_color,
|
|
79
|
+
}
|
|
80
|
+
)
|
|
81
|
+
self.counting_regions.append(region)
|
|
82
|
+
return region
|
|
83
|
+
|
|
84
|
+
def initialize_regions(self):
|
|
85
|
+
"""Initialize regions from `self.region` only once."""
|
|
86
|
+
if self.region is None:
|
|
87
|
+
self.initialize_region()
|
|
88
|
+
if not isinstance(self.region, dict): # Ensure self.region is initialized and structured as a dictionary
|
|
89
|
+
self.region = {"Region#01": self.region}
|
|
90
|
+
for i, (name, pts) in enumerate(self.region.items()):
|
|
91
|
+
region = self.add_region(name, pts, colors(i, True), (255, 255, 255))
|
|
92
|
+
region["prepared_polygon"] = self.prep(region["polygon"])
|
|
93
|
+
|
|
94
|
+
def process(self, im0: np.ndarray) -> SolutionResults:
|
|
95
|
+
"""Process the input frame to detect and count objects within each defined region.
|
|
96
|
+
|
|
97
|
+
Args:
|
|
98
|
+
im0 (np.ndarray): Input image frame where objects and regions are annotated.
|
|
99
|
+
|
|
100
|
+
Returns:
|
|
101
|
+
(SolutionResults): Contains processed image `plot_im`, 'total_tracks' (int, total number of tracked
|
|
102
|
+
objects), and 'region_counts' (dict, counts of objects per region).
|
|
103
|
+
"""
|
|
104
|
+
self.extract_tracks(im0)
|
|
105
|
+
annotator = SolutionAnnotator(im0, line_width=self.line_width)
|
|
106
|
+
|
|
107
|
+
for box, cls, track_id, conf in zip(self.boxes, self.clss, self.track_ids, self.confs):
|
|
108
|
+
annotator.box_label(box, label=self.adjust_box_label(cls, conf, track_id), color=colors(track_id, True))
|
|
109
|
+
center = self.Point(((box[0] + box[2]) / 2, (box[1] + box[3]) / 2))
|
|
110
|
+
for region in self.counting_regions:
|
|
111
|
+
if region["prepared_polygon"].contains(center):
|
|
112
|
+
region["counts"] += 1
|
|
113
|
+
self.region_counts[region["name"]] = region["counts"]
|
|
114
|
+
|
|
115
|
+
# Display region counts
|
|
116
|
+
for region in self.counting_regions:
|
|
117
|
+
poly = region["polygon"]
|
|
118
|
+
pts = list(map(tuple, np.array(poly.exterior.coords, dtype=np.int32)))
|
|
119
|
+
(x1, y1), (x2, y2) = [(int(poly.centroid.x), int(poly.centroid.y))] * 2
|
|
120
|
+
annotator.draw_region(pts, region["region_color"], self.line_width * 2)
|
|
121
|
+
annotator.adaptive_label(
|
|
122
|
+
[x1, y1, x2, y2],
|
|
123
|
+
label=str(region["counts"]),
|
|
124
|
+
color=region["region_color"],
|
|
125
|
+
txt_color=region["text_color"],
|
|
126
|
+
margin=self.line_width * 4,
|
|
127
|
+
shape="rect",
|
|
128
|
+
)
|
|
129
|
+
region["counts"] = 0 # Reset for next frame
|
|
130
|
+
plot_im = annotator.result()
|
|
131
|
+
self.display_output(plot_im)
|
|
132
|
+
|
|
133
|
+
return SolutionResults(plot_im=plot_im, total_tracks=len(self.track_ids), region_counts=self.region_counts)
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from ultralytics.solutions.solutions import BaseSolution, SolutionAnnotator, SolutionResults
|
|
6
|
+
from ultralytics.utils import LOGGER
|
|
7
|
+
from ultralytics.utils.plotting import colors
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class SecurityAlarm(BaseSolution):
|
|
11
|
+
"""A class to manage security alarm functionalities for real-time monitoring.
|
|
12
|
+
|
|
13
|
+
This class extends the BaseSolution class and provides features to monitor objects in a frame, send email
|
|
14
|
+
notifications when specific thresholds are exceeded for total detections, and annotate the output frame for
|
|
15
|
+
visualization.
|
|
16
|
+
|
|
17
|
+
Attributes:
|
|
18
|
+
email_sent (bool): Flag to track if an email has already been sent for the current event.
|
|
19
|
+
records (int): Threshold for the number of detected objects to trigger an alert.
|
|
20
|
+
server (smtplib.SMTP): SMTP server connection for sending email alerts.
|
|
21
|
+
to_email (str): Recipient's email address for alerts.
|
|
22
|
+
from_email (str): Sender's email address for alerts.
|
|
23
|
+
|
|
24
|
+
Methods:
|
|
25
|
+
authenticate: Set up email server authentication for sending alerts.
|
|
26
|
+
send_email: Send an email notification with details and an image attachment.
|
|
27
|
+
process: Monitor the frame, process detections, and trigger alerts if thresholds are crossed.
|
|
28
|
+
|
|
29
|
+
Examples:
|
|
30
|
+
>>> security = SecurityAlarm()
|
|
31
|
+
>>> security.authenticate("abc@gmail.com", "1111222233334444", "xyz@gmail.com")
|
|
32
|
+
>>> frame = cv2.imread("frame.jpg")
|
|
33
|
+
>>> results = security.process(frame)
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
def __init__(self, **kwargs: Any) -> None:
|
|
37
|
+
"""Initialize the SecurityAlarm class with parameters for real-time object monitoring.
|
|
38
|
+
|
|
39
|
+
Args:
|
|
40
|
+
**kwargs (Any): Additional keyword arguments passed to the parent class.
|
|
41
|
+
"""
|
|
42
|
+
super().__init__(**kwargs)
|
|
43
|
+
self.email_sent = False
|
|
44
|
+
self.records = self.CFG["records"]
|
|
45
|
+
self.server = None
|
|
46
|
+
self.to_email = ""
|
|
47
|
+
self.from_email = ""
|
|
48
|
+
|
|
49
|
+
def authenticate(self, from_email: str, password: str, to_email: str) -> None:
|
|
50
|
+
"""Authenticate the email server for sending alert notifications.
|
|
51
|
+
|
|
52
|
+
This method initializes a secure connection with the SMTP server and logs in using the provided credentials.
|
|
53
|
+
|
|
54
|
+
Args:
|
|
55
|
+
from_email (str): Sender's email address.
|
|
56
|
+
password (str): Password for the sender's email account.
|
|
57
|
+
to_email (str): Recipient's email address.
|
|
58
|
+
|
|
59
|
+
Examples:
|
|
60
|
+
>>> alarm = SecurityAlarm()
|
|
61
|
+
>>> alarm.authenticate("sender@example.com", "password123", "recipient@example.com")
|
|
62
|
+
"""
|
|
63
|
+
import smtplib
|
|
64
|
+
|
|
65
|
+
self.server = smtplib.SMTP("smtp.gmail.com: 587")
|
|
66
|
+
self.server.starttls()
|
|
67
|
+
self.server.login(from_email, password)
|
|
68
|
+
self.to_email = to_email
|
|
69
|
+
self.from_email = from_email
|
|
70
|
+
|
|
71
|
+
def send_email(self, im0, records: int = 5) -> None:
|
|
72
|
+
"""Send an email notification with an image attachment indicating the number of objects detected.
|
|
73
|
+
|
|
74
|
+
This method encodes the input image, composes the email message with details about the detection, and sends it
|
|
75
|
+
to the specified recipient.
|
|
76
|
+
|
|
77
|
+
Args:
|
|
78
|
+
im0 (np.ndarray): The input image or frame to be attached to the email.
|
|
79
|
+
records (int, optional): The number of detected objects to be included in the email message.
|
|
80
|
+
|
|
81
|
+
Examples:
|
|
82
|
+
>>> alarm = SecurityAlarm()
|
|
83
|
+
>>> frame = cv2.imread("path/to/image.jpg")
|
|
84
|
+
>>> alarm.send_email(frame, records=10)
|
|
85
|
+
"""
|
|
86
|
+
from email.mime.image import MIMEImage
|
|
87
|
+
from email.mime.multipart import MIMEMultipart
|
|
88
|
+
from email.mime.text import MIMEText
|
|
89
|
+
|
|
90
|
+
import cv2
|
|
91
|
+
|
|
92
|
+
img_bytes = cv2.imencode(".jpg", im0)[1].tobytes() # Encode the image as JPEG
|
|
93
|
+
|
|
94
|
+
# Create the email
|
|
95
|
+
message = MIMEMultipart()
|
|
96
|
+
message["From"] = self.from_email
|
|
97
|
+
message["To"] = self.to_email
|
|
98
|
+
message["Subject"] = "Security Alert"
|
|
99
|
+
|
|
100
|
+
# Add the text message body
|
|
101
|
+
message_body = f"Ultralytics alert: {records} object(s) detected."
|
|
102
|
+
message.attach(MIMEText(message_body))
|
|
103
|
+
|
|
104
|
+
# Attach the image
|
|
105
|
+
image_attachment = MIMEImage(img_bytes, name="ultralytics.jpg")
|
|
106
|
+
message.attach(image_attachment)
|
|
107
|
+
|
|
108
|
+
# Send the email
|
|
109
|
+
try:
|
|
110
|
+
self.server.send_message(message)
|
|
111
|
+
LOGGER.info("Email sent successfully!")
|
|
112
|
+
except Exception as e:
|
|
113
|
+
LOGGER.error(f"Failed to send email: {e}")
|
|
114
|
+
|
|
115
|
+
def process(self, im0) -> SolutionResults:
|
|
116
|
+
"""Monitor the frame, process object detections, and trigger alerts if thresholds are exceeded.
|
|
117
|
+
|
|
118
|
+
This method processes the input frame, extracts detections, annotates the frame with bounding boxes, and sends
|
|
119
|
+
an email notification if the number of detected objects surpasses the specified threshold and an alert has not
|
|
120
|
+
already been sent.
|
|
121
|
+
|
|
122
|
+
Args:
|
|
123
|
+
im0 (np.ndarray): The input image or frame to be processed and annotated.
|
|
124
|
+
|
|
125
|
+
Returns:
|
|
126
|
+
(SolutionResults): Contains processed image `plot_im`, 'total_tracks' (total number of tracked objects) and
|
|
127
|
+
'email_sent' (whether an email alert was triggered).
|
|
128
|
+
|
|
129
|
+
Examples:
|
|
130
|
+
>>> alarm = SecurityAlarm()
|
|
131
|
+
>>> frame = cv2.imread("path/to/image.jpg")
|
|
132
|
+
>>> results = alarm.process(frame)
|
|
133
|
+
"""
|
|
134
|
+
self.extract_tracks(im0) # Extract tracks
|
|
135
|
+
annotator = SolutionAnnotator(im0, line_width=self.line_width) # Initialize annotator
|
|
136
|
+
|
|
137
|
+
# Iterate over bounding boxes and classes index
|
|
138
|
+
for box, cls in zip(self.boxes, self.clss):
|
|
139
|
+
# Draw bounding box
|
|
140
|
+
annotator.box_label(box, label=self.names[cls], color=colors(cls, True))
|
|
141
|
+
|
|
142
|
+
total_det = len(self.clss)
|
|
143
|
+
if total_det >= self.records and not self.email_sent: # Only send email if not sent before
|
|
144
|
+
self.send_email(im0, total_det)
|
|
145
|
+
self.email_sent = True
|
|
146
|
+
|
|
147
|
+
plot_im = annotator.result()
|
|
148
|
+
self.display_output(plot_im) # Display output with base class function
|
|
149
|
+
|
|
150
|
+
# Return a SolutionResults
|
|
151
|
+
return SolutionResults(plot_im=plot_im, total_tracks=len(self.track_ids), email_sent=self.email_sent)
|