m7mdal7aj commited on
Commit
68d9c45
1 Parent(s): c86ce90

Update my_model/utilities/gen_utilities.py

Browse files
Files changed (1) hide show
  1. my_model/utilities/gen_utilities.py +94 -15
my_model/utilities/gen_utilities.py CHANGED
@@ -10,15 +10,17 @@ import gc
10
  import streamlit as st
11
 
12
 
13
-
14
- def show_image(image):
15
  """
16
  Display an image in various environments (Jupyter, PyCharm, Hugging Face Spaces).
17
- Handles different types of image inputs (file path, PIL Image, numpy array, OpenCV, PyTorch tensor).
18
 
19
  Args:
20
- image (str or PIL.Image or numpy.ndarray or torch.Tensor): The image to display.
21
- """
 
 
 
22
 
23
  in_jupyter = is_jupyter_notebook()
24
  in_colab = is_google_colab()
@@ -53,7 +55,17 @@ def show_image(image):
53
 
54
 
55
 
56
- def show_image_with_matplotlib(image):
 
 
 
 
 
 
 
 
 
 
57
  if isinstance(image, str):
58
  image = Image.open(image)
59
  elif isinstance(image, np.ndarray):
@@ -66,7 +78,7 @@ def show_image_with_matplotlib(image):
66
  plt.show()
67
 
68
 
69
- def is_jupyter_notebook():
70
  """
71
  Check if the code is running in a Jupyter notebook.
72
 
@@ -85,25 +97,40 @@ def is_jupyter_notebook():
85
  return False # Default to False if none of the above conditions are met
86
 
87
 
88
- def is_pycharm():
 
 
 
 
 
 
 
89
  return 'PYCHARM_HOSTED' in os.environ
90
 
91
 
92
- def is_google_colab():
 
 
 
 
 
 
 
93
  return 'COLAB_GPU' in os.environ or 'google.colab' in sys.modules
94
 
95
 
96
- def get_image_path(name, path_type):
97
  """
98
  Generates a path for models, images, or data based on the specified type.
99
 
100
  Args:
101
- name (str): The name of the model, image, or data folder/file.
102
- path_type (str): The type of path needed ('models', 'images', or 'data').
103
 
104
  Returns:
105
- str: The full path to the specified resource.
106
  """
 
107
  # Get the current working directory (assumed to be inside 'code' folder)
108
  current_dir = os.getcwd()
109
 
@@ -119,7 +146,7 @@ def get_image_path(name, path_type):
119
  return full_path
120
 
121
 
122
- def get_model_path(model_name):
123
  """
124
  Get the path to the specified model folder.
125
 
@@ -129,6 +156,7 @@ def get_model_path(model_name):
129
  Returns:
130
  str: Absolute path to the specified model folder.
131
  """
 
132
  # Directory of the current script
133
  current_script_dir = os.path.dirname(os.path.abspath(__file__))
134
 
@@ -140,11 +168,62 @@ def get_model_path(model_name):
140
 
141
  return model_path
142
 
 
 
 
 
143
 
 
 
 
 
 
144
 
145
- def free_gpu_resources():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
  """
147
  Clears GPU memory.
 
 
 
148
  """
149
 
150
  if torch.cuda.is_available():
 
10
  import streamlit as st
11
 
12
 
13
+ def show_image(image: Union[str, Image.Image, np.ndarray, torch.Tensor]) -> None:
 
14
  """
15
  Display an image in various environments (Jupyter, PyCharm, Hugging Face Spaces).
16
+ Handles different types of image inputs (file path, PIL Image, numpy array, PyTorch tensor).
17
 
18
  Args:
19
+ image (Union[str, Image.Image, np.ndarray, torch.Tensor]): The image to display.
20
+
21
+ Returns:
22
+ None
23
+ """
24
 
25
  in_jupyter = is_jupyter_notebook()
26
  in_colab = is_google_colab()
 
55
 
56
 
57
 
58
+ def show_image_with_matplotlib(image: Union[str, Image.Image, np.ndarray, torch.Tensor]) -> None:
59
+ """
60
+ Display an image using Matplotlib.
61
+
62
+ Args:
63
+ image (Union[str, Image.Image, np.ndarray, torch.Tensor]): The image to display.
64
+
65
+ Returns:
66
+ None
67
+ """
68
+
69
  if isinstance(image, str):
70
  image = Image.open(image)
71
  elif isinstance(image, np.ndarray):
 
78
  plt.show()
79
 
80
 
81
+ def is_jupyter_notebook() -> bool:
82
  """
83
  Check if the code is running in a Jupyter notebook.
84
 
 
97
  return False # Default to False if none of the above conditions are met
98
 
99
 
100
+ def is_pycharm() -> bool:
101
+ """
102
+ Check if the code is running in PyCharm.
103
+
104
+ Returns:
105
+ bool: True if running in PyCharm, False otherwise.
106
+ """
107
+
108
  return 'PYCHARM_HOSTED' in os.environ
109
 
110
 
111
+ def is_google_colab() -> bool:
112
+ """
113
+ Check if the code is running in Google Colab.
114
+
115
+ Returns:
116
+ bool: True if running in Google Colab, False otherwise.
117
+ """
118
+
119
  return 'COLAB_GPU' in os.environ or 'google.colab' in sys.modules
120
 
121
 
122
+ def get_image_path(name: str, path_type: str) -> str:
123
  """
124
  Generates a path for models, images, or data based on the specified type.
125
 
126
  Args:
127
+ name (str): The name of the model, image, or data folder/file.
128
+ path_type (str): The type of path needed ('models', 'images', or 'data').
129
 
130
  Returns:
131
+ str: The full path to the specified resource.
132
  """
133
+
134
  # Get the current working directory (assumed to be inside 'code' folder)
135
  current_dir = os.getcwd()
136
 
 
146
  return full_path
147
 
148
 
149
+ def get_model_path(model_name: str) -> str:
150
  """
151
  Get the path to the specified model folder.
152
 
 
156
  Returns:
157
  str: Absolute path to the specified model folder.
158
  """
159
+
160
  # Directory of the current script
161
  current_script_dir = os.path.dirname(os.path.abspath(__file__))
162
 
 
168
 
169
  return model_path
170
 
171
+ def add_detected_objects_to_dataframe(df: pd.DataFrame, detector_type: str, image_directory: str, detector: object) -> pd.DataFrame:
172
+ """
173
+ Adds a column to the DataFrame with detected objects for each image specified in the 'image_name' column.
174
+ Prints a message every 200 images processed.
175
 
176
+ Args:
177
+ df (pd.DataFrame): DataFrame containing a column 'image_name' with image filenames.
178
+ detector_type (str): The detection model to use ('detic' or 'yolov5').
179
+ image_directory (str): Path to the directory containing images.
180
+ detector (object): An instance of the ObjectDetector class.
181
 
182
+ Returns:
183
+ pd.DataFrame: The original DataFrame with an additional column 'detected_objects'.
184
+ """
185
+
186
+ # Ensure 'image_name' column exists in the DataFrame
187
+ if 'image_name' not in df.columns:
188
+ raise ValueError("DataFrame must contain an 'image_name' column.")
189
+
190
+ detector.load_model(detector_type)
191
+
192
+ # Initialize a counter for images processed
193
+ images_processed = 0
194
+
195
+ # Function to detect objects for a given image filename
196
+ def detect_objects_for_image(image_name):
197
+ nonlocal images_processed # Use the nonlocal keyword to modify the images_processed variable
198
+ image_path = os.path.join(image_directory, image_name)
199
+ if os.path.exists(image_path):
200
+
201
+ image = detector.process_image(image_path)
202
+ detected_objects_str, _ = detector.detect_objects(image, 0.2)
203
+ images_processed += 1
204
+
205
+ # Print message every 2 images processed
206
+ if images_processed % 200 == 0:
207
+ print(f"Completed {images_processed} images detection")
208
+
209
+ return detected_objects_str
210
+ else:
211
+ images_processed += 1
212
+ return "Image not found"
213
+
214
+ # Apply the function to each row in the DataFrame
215
+ df[detector.model_name] = df['image_name'].apply(detect_objects_for_image)
216
+
217
+ return df
218
+
219
+
220
+
221
+ def free_gpu_resources() -> None:
222
  """
223
  Clears GPU memory.
224
+
225
+ Returns:
226
+ None
227
  """
228
 
229
  if torch.cuda.is_available():