leo-bourrel commited on
Commit
911c0ac
Β·
1 Parent(s): 801ce15

feat: split prediction into YOLO predictions

Browse files
src/data_models/__pycache__/bbox_manager.cpython-312.pyc ADDED
Binary file (2.53 kB). View file
 
src/data_models/__pycache__/image_manager.cpython-312.pyc ADDED
Binary file (4.76 kB). View file
 
src/data_models/__pycache__/park_manager.cpython-312.pyc ADDED
Binary file (3.93 kB). View file
 
src/data_models/__pycache__/sql_connection.cpython-312.pyc ADDED
Binary file (1.4 kB). View file
 
src/{models β†’ data_models}/bbox_manager.py RENAMED
@@ -2,7 +2,7 @@
2
 
3
  from sqlalchemy import text
4
 
5
- from models.sql_connection import get_db_connection
6
 
7
 
8
  class BoundingBoxManager:
@@ -62,3 +62,32 @@ class BoundingBoxManager:
62
  def close_connection(self):
63
  """Close the connection."""
64
  self.session.close()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
  from sqlalchemy import text
4
 
5
+ from data_models.sql_connection import get_db_connection
6
 
7
 
8
  class BoundingBoxManager:
 
62
  def close_connection(self):
63
  """Close the connection."""
64
  self.session.close()
65
+
66
+
67
+ def add_bboxes_to_db(result, bbox_manager, image_id):
68
+ """
69
+ Adds bounding boxes from a YOLO result to the database.
70
+
71
+ Args:
72
+ result: YOLO result object containing the bounding box details.
73
+ bbox_manager (BoundingBoxManager): Instance of BoundingBoxManager to interact with the database.
74
+ image_id (int): The ID of the associated image.
75
+
76
+ Returns:
77
+ None
78
+ """
79
+ for box in result.boxes:
80
+ try:
81
+ print(f"Adding bounding box for image ID: {image_id}...")
82
+ bbox_manager.add_bbox(
83
+ confidence=box.conf[0].numpy().item(),
84
+ class_id=int(box.cls[0].numpy().item()),
85
+ img_id=image_id,
86
+ x_min=box.xyxy[0][0].numpy().item(),
87
+ y_min=box.xyxy[0][1].numpy().item(),
88
+ x_max=box.xyxy[0][2].numpy().item(),
89
+ y_max=box.xyxy[0][3].numpy().item(),
90
+ )
91
+ print(f"Bounding box added to DB for image ID: {image_id}")
92
+ except Exception as e:
93
+ print(f"Error inserting bounding box into DB: {e}")
src/{models β†’ data_models}/image_manager.py RENAMED
@@ -1,8 +1,9 @@
1
- """Mnages images table in the database."""
2
 
 
3
  from sqlalchemy import text
4
 
5
- from models.sql_connection import get_db_connection
6
 
7
 
8
  class ImageManager:
@@ -97,3 +98,32 @@ class ImageManager:
97
  def close_connection(self):
98
  """Close the connection."""
99
  self.session.close()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Manages images table in the database."""
2
 
3
+ from datetime import datetime
4
  from sqlalchemy import text
5
 
6
+ from data_models.sql_connection import get_db_connection
7
 
8
 
9
  class ImageManager:
 
98
  def close_connection(self):
99
  """Close the connection."""
100
  self.session.close()
101
+
102
+
103
+ def add_image_to_db(result, image_manager, park_id):
104
+ """
105
+ Adds an image to the database.
106
+
107
+ Args:
108
+ result: YOLO result object containing the image details.
109
+ image_manager (ImageManager): Instance of ImageManager to interact with the database.
110
+ park_id (int): The ID of the associated park.
111
+
112
+ Returns:
113
+ int: The ID of the added image.
114
+ """
115
+ image_name = result.path.split("/")[-1]
116
+ current_datetime = datetime.now()
117
+ created_at = current_datetime.strftime("%Y-%m-%d %H:%M:%S")
118
+
119
+ try:
120
+ print(f"Adding image '{image_name}' to the database...")
121
+ image = image_manager.add_image(
122
+ name=image_name, created_at=created_at, park_id=park_id
123
+ )
124
+ image_id = image_manager.get_image_id(image_name)
125
+ print(f"Image '{image_name}' added with ID: {image_id}")
126
+ return image_id
127
+ except Exception as e:
128
+ print(f"Error adding image '{image_name}' to the database: {e}")
129
+ return None
src/{models β†’ data_models}/park_manager.py RENAMED
@@ -2,7 +2,7 @@
2
 
3
  from sqlalchemy import text
4
 
5
- from models.sql_connection import get_db_connection
6
 
7
 
8
  class ParkManager:
 
2
 
3
  from sqlalchemy import text
4
 
5
+ from data_models.sql_connection import get_db_connection
6
 
7
 
8
  class ParkManager:
src/{models β†’ data_models}/sql_connection.py RENAMED
File without changes
src/predict.py CHANGED
@@ -1,115 +1,10 @@
1
- from datetime import datetime
2
-
3
- from ultralytics import YOLO
4
-
5
- from models.bbox_manager import BoundingBoxManager
6
- from models.image_manager import ImageManager
7
- from models.park_manager import ParkManager
8
-
9
-
10
- def add_image_to_db(result, image_manager, park_id):
11
- """
12
- Adds an image to the database.
13
-
14
- Args:
15
- result: YOLO result object containing the image details.
16
- image_manager (ImageManager): Instance of ImageManager to interact with the database.
17
- park_id (int): The ID of the associated park.
18
-
19
- Returns:
20
- int: The ID of the added image.
21
- """
22
- image_name = result.path.split("/")[-1]
23
- current_datetime = datetime.now()
24
- created_at = current_datetime.strftime("%Y-%m-%d %H:%M:%S")
25
-
26
- try:
27
- print(f"Adding image '{image_name}' to the database...")
28
- image = image_manager.add_image(
29
- name=image_name, created_at=created_at, park_id=park_id
30
- )
31
- image_id = image_manager.get_image_id(image_name)
32
- print(f"Image '{image_name}' added with ID: {image_id}")
33
- return image_id
34
- except Exception as e:
35
- print(f"Error adding image '{image_name}' to the database: {e}")
36
- return None
37
-
38
-
39
- def add_bboxes_to_db(result, bbox_manager, image_id):
40
- """
41
- Adds bounding boxes from a YOLO result to the database.
42
-
43
- Args:
44
- result: YOLO result object containing the bounding box details.
45
- bbox_manager (BoundingBoxManager): Instance of BoundingBoxManager to interact with the database.
46
- image_id (int): The ID of the associated image.
47
-
48
- Returns:
49
- None
50
- """
51
- for box in result.boxes:
52
- try:
53
- print(f"Adding bounding box for image ID: {image_id}...")
54
- bbox_manager.add_bbox(
55
- confidence=box.conf[0].numpy().item(),
56
- class_id=int(box.cls[0].numpy().item()),
57
- img_id=image_id,
58
- x_min=box.xyxy[0][0].numpy().item(),
59
- y_min=box.xyxy[0][1].numpy().item(),
60
- x_max=box.xyxy[0][2].numpy().item(),
61
- y_max=box.xyxy[0][3].numpy().item(),
62
- )
63
- print(f"Bounding box added to DB for image ID: {image_id}")
64
- except Exception as e:
65
- print(f"Error inserting bounding box into DB: {e}")
66
-
67
-
68
- def process_predictions(list_folder, model_file):
69
- """
70
- Process predictions for a list of image folders, adding images and bounding boxes to the database.
71
-
72
- Args:
73
- list_folder (list): List of image folders.
74
- model_file (str): Path to the YOLO model.
75
-
76
- Raises:
77
- Exception: If an error occurs during processing.
78
- """
79
- print(f"Initializing processing of predictions...")
80
- bbox_manager = BoundingBoxManager()
81
- image_manager = ImageManager()
82
- park_manager = ParkManager()
83
-
84
- model = YOLO(model_file)
85
-
86
- for folder in list_folder:
87
- print(f"Processing folder: {folder}...")
88
- park_name = folder.split("/")[-1]
89
-
90
- print(f"Retrieving park ID for '{park_name}'...")
91
- park_id = park_manager.get_park_id(park_name)
92
- if not park_id:
93
- print(f"Park '{park_name}' not found in the database. Skipping folder.")
94
- continue
95
-
96
- predictions = model(folder, stream=True, show=False)
97
-
98
- for result in predictions:
99
- print(f"Processing result for image: {result.path.split('/')[-1]}...")
100
- image_id = add_image_to_db(result, image_manager, park_id)
101
-
102
- if image_id:
103
- print(f"Adding bounding boxes to the database...")
104
- add_bboxes_to_db(result, bbox_manager, image_id)
105
-
106
- print(f"Processing complete. Closing database connections.")
107
- bbox_manager.close_connection()
108
- image_manager.close_connection()
109
- park_manager.close_connection()
110
 
111
 
112
  if __name__ == "__main__":
113
- list_folder = ["../images/Al Khaldiyah Park", "../images/Family Park"]
114
- model_file = "yolov5s.pt"
115
- process_predictions(list_folder, model_file)
 
 
1
+ import os
2
+ from tqdm import tqdm
3
+ from yolo_predictions import process_YOLO_predictions
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
 
6
  if __name__ == "__main__":
7
+ list_folder = ["./images/Al Khaldiyah Park", "./images/Family Park"]
8
+ model_file = "yolo11s.pt"
9
+
10
+ process_YOLO_predictions(list_folder, model_file)
src/yolo_predictions.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from data_models.bbox_manager import BoundingBoxManager, add_bboxes_to_db
2
+ from data_models.image_manager import ImageManager, add_image_to_db
3
+ from data_models.park_manager import ParkManager
4
+ from ultralytics import YOLO
5
+
6
+
7
+ def load_model(model_file):
8
+ """
9
+ Load the YOLO model.
10
+
11
+ Args:
12
+ model_file (str): Path to the YOLO model.
13
+
14
+ Returns:
15
+ YOLO: The YOLO model.
16
+ """
17
+ try:
18
+ print(f"Loading YOLO model from file: {model_file}...")
19
+ model = YOLO(model_file)
20
+ print(f"Model loaded successfully!")
21
+ return model
22
+ except Exception as e:
23
+ print(f"Error loading YOLO model: {e}")
24
+ return None
25
+
26
+
27
+ def process_YOLO_predictions(list_folder: list[str], model_file: str):
28
+ """
29
+ Process predictions for a list of image folders, adding images and bounding boxes to the database using the YOLO model.
30
+
31
+ Args:
32
+ list_folder (list): List of image folders.
33
+ model_file (str): Path to the YOLO model.
34
+
35
+ Raises:
36
+ Exception: If an error occurs during processing.
37
+ """
38
+ print(f"Initializing processing of predictions...")
39
+ bbox_manager = BoundingBoxManager()
40
+ image_manager = ImageManager()
41
+ park_manager = ParkManager()
42
+
43
+ model = load_model(model_file)
44
+ if not model:
45
+ raise Exception("Error loading YOLO model. Aborting processing.")
46
+
47
+ for folder in list_folder:
48
+ print(f"Processing folder: {folder}...")
49
+ park_name = folder.split("/")[-1]
50
+
51
+ print(f"Retrieving park ID for '{park_name}'...")
52
+ park_id = park_manager.get_park_id(park_name)
53
+ if not park_id:
54
+ print(f"Park '{park_name}' not found in the database. Skipping folder.")
55
+ continue
56
+
57
+ predictions = model(folder, stream=True, show=False)
58
+
59
+ for result in predictions:
60
+ print(f"Processing result for image: {result.path.split('/')[-1]}...")
61
+ image_id = add_image_to_db(result, image_manager, park_id)
62
+
63
+ if image_id:
64
+ print(f"Adding bounding boxes to the database...")
65
+ add_bboxes_to_db(result, bbox_manager, image_id)
66
+
67
+ print(f"Processing complete. Closing database connections.")
68
+ bbox_manager.close_connection()
69
+ image_manager.close_connection()
70
+ park_manager.close_connection()