m7mdal7aj commited on
Commit
e68dc65
1 Parent(s): 58b21d4

Upload 2 files

Browse files

completed the detection code and updated some utils functions

Files changed (2) hide show
  1. My_Model/object_detection.py +162 -0
  2. My_Model/utilities.py +277 -0
My_Model/object_detection.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from PIL import Image, ImageDraw, ImageFont
3
+ import numpy as np
4
+ import cv2
5
+ import os
6
+ from utilities import get_path, show_image, show_image_with_matplotlib
7
+ import transformers
8
+
9
+ class ObjectDetector:
10
+ def __init__(self):
11
+ self.model = None
12
+ self.processor = None
13
+ self.model_name = None
14
+
15
+ def load_model(self, model_name='detic', pretrained=True, model_version='yolov5s'):
16
+ """
17
+ Load the specified object detection model.
18
+ :param model_name: Name of the model to load.
19
+ :param pretrained: Boolean indicating if pretrained model should be used.
20
+ :param model_version: Version of the model, applicable for YOLOv5.
21
+ """
22
+ self.model_name = model_name
23
+ if model_name == 'detic':
24
+ self.load_detic_model(pretrained)
25
+ elif model_name == 'yolov5':
26
+ self.load_yolov5_model(pretrained, model_version)
27
+ else:
28
+ raise ValueError("Unsupported model name")
29
+
30
+
31
+ def load_detic_model(self, pretrained):
32
+ """Load the Detic model."""
33
+ try:
34
+ model_path = get_path('deformable-detr-detic', 'Models')
35
+ from transformers import AutoImageProcessor, AutoModelForObjectDetection
36
+ self.processor = AutoImageProcessor.from_pretrained(model_path)
37
+ self.model = AutoModelForObjectDetection.from_pretrained(model_path)
38
+ except Exception as e:
39
+ print(f"Error loading Detic model: {e}")
40
+
41
+
42
+ def load_yolov5_model(self, pretrained, model_version):
43
+ """Load the YOLOv5 model."""
44
+ try:
45
+ model_path = get_path('yolov5', 'Models')
46
+ if model_path and os.path.exists(model_path):
47
+ with os.scandir(model_path) as main_dir:
48
+ self.model = torch.hub.load(model_path, model_version, pretrained=pretrained, source="local")
49
+ else:
50
+ self.model = torch.hub.load('ultralytics/yolov5', model_version, pretrained=pretrained)
51
+ except Exception as e:
52
+ print(f"Error loading YOLOv5 model: {e}")
53
+
54
+
55
+ def process_image(self, image_path: str) -> Image.Image:
56
+ """
57
+ Process the image from the given path.
58
+ :param image_path: Path to the image file.
59
+ :return: Processed image.
60
+ """
61
+ with Image.open(image_path) as image:
62
+ return image.convert("RGB")
63
+
64
+
65
+ def detect_objects(self, image: Image.Image, threshold: float = 0.4):
66
+ """
67
+ Detect objects in the given image.
68
+ :param image: Image in which to detect objects.
69
+ :param threshold: Detection threshold.
70
+ :return: Tuple of detected objects string and list.
71
+ """
72
+ detected_objects_str, detected_objects_list = "", []
73
+ if self.model_name == 'detic':
74
+ detected_objects_str, detected_objects_list = self.detect_with_detic(image, threshold)
75
+ elif self.model_name == 'yolov5':
76
+ detected_objects_str, detected_objects_list = self.detect_with_yolov5(image, threshold)
77
+ return detected_objects_str.strip(), detected_objects_list
78
+
79
+
80
+ def detect_with_detic(self, image: Image.Image, threshold: float):
81
+ """Detect objects using Detic model."""
82
+ inputs = self.processor(images=image, return_tensors="pt")
83
+ outputs = self.model(**inputs)
84
+ target_sizes = torch.tensor([image.size[::-1]])
85
+ results = self.processor.post_process_object_detection(outputs, target_sizes=target_sizes, threshold=threshold)[
86
+ 0]
87
+
88
+ detected_objects_str = ""
89
+ detected_objects_list = []
90
+ for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
91
+ if score >= threshold:
92
+ label_name = self.model.config.id2label[label.item()]
93
+ box_rounded = [round(coord, 2) for coord in box.tolist()]
94
+ certainty = round(score.item() * 100, 2)
95
+ detected_objects_str += f"{{object: {label_name}, bounding box: {box_rounded}, certainty: {certainty}%}}\n"
96
+ detected_objects_list.append((label_name, box_rounded, certainty))
97
+ return detected_objects_str, detected_objects_list
98
+
99
+
100
+ def detect_with_yolov5(self, image: Image.Image, threshold: float):
101
+ """Detect objects using YOLOv5 model."""
102
+
103
+ cv2_img = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
104
+ results = self.model(cv2_img)
105
+
106
+ detected_objects_str = ""
107
+ detected_objects_list = []
108
+ for *bbox, conf, cls in results.xyxy[0]:
109
+ if conf >= threshold:
110
+ label_name = results.names[int(cls)]
111
+ box_rounded = [round(coord.item(), 2) for coord in bbox] # Convert each tensor to float and round
112
+ certainty = round(conf.item() * 100, 2)
113
+ detected_objects_str += f"{{object: {label_name}, bounding box: {box_rounded}, certainty: {certainty}%}}\n"
114
+ detected_objects_list.append((label_name, box_rounded, certainty))
115
+ return detected_objects_str, detected_objects_list
116
+
117
+
118
+ def draw_boxes(self, image: Image.Image, detected_objects: list, show_confidence: bool = True) -> Image.Image:
119
+ """
120
+ Draw bounding boxes around detected objects in the image.
121
+ :param image: Image on which to draw.
122
+ :param detected_objects: List of detected objects.
123
+ :param show_confidence: Boolean to show confidence scores.
124
+ :return: Image with drawn boxes.
125
+ """
126
+ draw = ImageDraw.Draw(image)
127
+ try:
128
+ font = ImageFont.truetype("arial.ttf", 15)
129
+ except IOError:
130
+ font = ImageFont.load_default()
131
+
132
+ colors = ["red", "green", "blue", "yellow", "purple", "orange"]
133
+ label_color_map = {}
134
+
135
+ for label_name, box, score in detected_objects:
136
+ if label_name not in label_color_map:
137
+ label_color_map[label_name] = colors[len(label_color_map) % len(colors)]
138
+
139
+ color = label_color_map[label_name]
140
+ draw.rectangle(box, outline=color, width=3)
141
+
142
+ label_text = f"{label_name}"
143
+ if show_confidence:
144
+ label_text += f" ({round(score, 2)}%)"
145
+ draw.text((box[0], box[1]), label_text, fill=color, font=font)
146
+
147
+ return image
148
+
149
+
150
+ if __name__=="__main__":
151
+
152
+ detector = ObjectDetector()
153
+ image_path = get_path('horse.jpg', 'Sample_Images')
154
+
155
+ detector.load_model('yolov5') # pass either 'detic' or 'yolov5'
156
+
157
+ image = detector.process_image(image_path)
158
+ detected_objects_string, detected_objects_list = detector.detect_objects(image, threshold=0.2)
159
+ image_with_boxes = detector.draw_boxes(image, detected_objects_list, show_confidence=False)
160
+ print(detected_objects_string)
161
+ show_image(image_with_boxes)
162
+ #show_image_with_matplotlib(image_path)
My_Model/utilities.py ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ from collections import Counter
3
+ import json
4
+ import os
5
+ import IPython.display
6
+ from PIL import Image
7
+ import numpy as np
8
+ import torch
9
+ from IPython import get_ipython
10
+ import sys
11
+
12
+
13
+ class VQADataProcessor:
14
+ """
15
+ A class to process OKVQA dataset.
16
+
17
+ Attributes:
18
+ questions_file_path (str): The file path for the questions JSON file.
19
+ annotations_file_path (str): The file path for the annotations JSON file.
20
+ questions (list): List of questions extracted from the JSON file.
21
+ annotations (list): List of annotations extracted from the JSON file.
22
+ df_questions (DataFrame): DataFrame created from the questions list.
23
+ df_answers (DataFrame): DataFrame created from the annotations list.
24
+ merged_df (DataFrame): DataFrame resulting from merging questions and answers.
25
+ """
26
+
27
+ def __init__(self, questions_file_path, annotations_file_path):
28
+ """
29
+ Initializes the VQADataProcessor with file paths for questions and annotations.
30
+
31
+ Parameters:
32
+ questions_file_path (str): The file path for the questions JSON file.
33
+ annotations_file_path (str): The file path for the annotations JSON file.
34
+ """
35
+ self.questions_file_path = questions_file_path
36
+ self.annotations_file_path = annotations_file_path
37
+ self.questions, self.annotations = self.read_json_files()
38
+ self.df_questions = pd.DataFrame(self.questions)
39
+ self.df_answers = pd.DataFrame(self.annotations)
40
+ self.merged_df = None
41
+
42
+ def read_json_files(self):
43
+ """
44
+ Reads the JSON files for questions and annotations.
45
+
46
+ Returns:
47
+ tuple: A tuple containing two lists: questions and annotations.
48
+ """
49
+ with open(self.questions_file_path, 'r') as file:
50
+ data = json.load(file)
51
+ questions = data['questions']
52
+
53
+ with open(self.annotations_file_path, 'r') as file:
54
+ data = json.load(file)
55
+ annotations = data['annotations']
56
+
57
+ return questions, annotations
58
+
59
+ @staticmethod
60
+ def find_most_frequent(my_list):
61
+ """
62
+ Finds the most frequent item in a list.
63
+
64
+ Parameters:
65
+ my_list (list): A list of items.
66
+
67
+ Returns:
68
+ The most frequent item in the list. Returns None if the list is empty.
69
+ """
70
+ if not my_list:
71
+ return None
72
+ counter = Counter(my_list)
73
+ most_common = counter.most_common(1)
74
+ return most_common[0][0]
75
+
76
+ def merge_dataframes(self):
77
+ """
78
+ Merges the questions and answers DataFrames on 'question_id' and 'image_id'.
79
+ """
80
+ self.merged_df = pd.merge(self.df_questions, self.df_answers, on=['question_id', 'image_id'])
81
+
82
+ def join_words_with_hyphen(self, sentence):
83
+
84
+ return '-'.join(sentence.split())
85
+
86
+ def process_answers(self):
87
+ """
88
+ Processes the answers by extracting raw and processed answers and finding the most frequent ones.
89
+ """
90
+ if self.merged_df is not None:
91
+ self.merged_df['raw_answers'] = self.merged_df['answers'].apply(lambda x: [ans['raw_answer'] for ans in x])
92
+ self.merged_df['processed_answers'] = self.merged_df['answers'].apply(
93
+ lambda x: [ans['answer'] for ans in x])
94
+ self.merged_df['most_frequent_raw_answer'] = self.merged_df['raw_answers'].apply(self.find_most_frequent)
95
+ self.merged_df['most_frequent_processed_answer'] = self.merged_df['processed_answers'].apply(
96
+ self.find_most_frequent)
97
+ self.merged_df.drop(columns=['answers'], inplace=True)
98
+ else:
99
+ print("DataFrames have not been merged yet.")
100
+
101
+ # Apply the function to the 'most_frequent_processed_answer' column
102
+ self.merged_df['single_word_answers'] = self.merged_df['most_frequent_processed_answer'].apply(
103
+ self.join_words_with_hyphen)
104
+
105
+ def get_processed_data(self):
106
+ """
107
+ Retrieves the processed DataFrame.
108
+
109
+ Returns:
110
+ DataFrame: The processed DataFrame. Returns None if the DataFrame is empty or not processed.
111
+ """
112
+ if self.merged_df is not None:
113
+ return self.merged_df
114
+ else:
115
+ print("DataFrame is empty or not processed yet.")
116
+ return None
117
+
118
+ def save_to_csv(self, df, saved_file_name):
119
+
120
+ if saved_file_name is not None:
121
+ if ".csv" not in saved_file_name:
122
+ df.to_csv(os.path.join(saved_file_name, ".csv"), index=None)
123
+
124
+ else:
125
+ df.to_csv(saved_file_name, index=None)
126
+
127
+ else:
128
+ df.to_csv("data.csv", index=None)
129
+
130
+ def display_dataframe(self):
131
+ """
132
+ Displays the processed DataFrame.
133
+ """
134
+ if self.merged_df is not None:
135
+ print(self.merged_df)
136
+ else:
137
+ print("DataFrame is empty.")
138
+
139
+
140
+ def process_okvqa_dataset(questions_file_path, annotations_file_path, save_to_csv=False, saved_file_name=None):
141
+ """
142
+ Processes the OK-VQA dataset given the file paths for questions and annotations.
143
+
144
+ Parameters:
145
+ questions_file_path (str): The file path for the questions JSON file.
146
+ annotations_file_path (str): The file path for the annotations JSON file.
147
+
148
+ Returns:
149
+ DataFrame: The processed DataFrame containing merged and processed VQA data.
150
+ """
151
+ # Create an instance of the class
152
+ processor = VQADataProcessor(questions_file_path, annotations_file_path)
153
+
154
+ # Process the data
155
+ processor.merge_dataframes()
156
+ processor.process_answers()
157
+
158
+ # Retrieve the processed DataFrame
159
+ processed_data = processor.get_processed_data()
160
+
161
+ if save_to_csv:
162
+ processor.save_to_csv(processed_data, saved_file_name)
163
+
164
+ return processed_data
165
+
166
+
167
+ def show_image(image):
168
+ """
169
+ Display an image in various environments (Jupyter, PyCharm, Hugging Face Spaces).
170
+ Handles different types of image inputs (file path, PIL Image, numpy array, OpenCV, PyTorch tensor).
171
+
172
+ Args:
173
+ image (str or PIL.Image or numpy.ndarray or torch.Tensor): The image to display.
174
+ """
175
+ in_jupyter = is_jupyter_notebook()
176
+
177
+ # Convert image to PIL Image if it's a file path, numpy array, or PyTorch tensor
178
+ if isinstance(image, str):
179
+
180
+ if os.path.isfile(image):
181
+ image = Image.open(image)
182
+ else:
183
+ raise ValueError("File path provided does not exist.")
184
+ elif isinstance(image, np.ndarray):
185
+
186
+ if image.ndim == 3 and image.shape[2] in [3, 4]:
187
+
188
+ image = Image.fromarray(image[..., ::-1] if image.shape[2] == 3 else image)
189
+ else:
190
+
191
+ image = Image.fromarray(image)
192
+ elif torch.is_tensor(image):
193
+
194
+ image = Image.fromarray(image.permute(1, 2, 0).numpy().astype(np.uint8))
195
+
196
+ # Display the image
197
+ if in_jupyter:
198
+
199
+ from IPython.display import display
200
+ display(image)
201
+ else:
202
+
203
+ image.show()
204
+
205
+ import matplotlib.pyplot as plt
206
+
207
+ def show_image_with_matplotlib(image):
208
+ if isinstance(image, str):
209
+ image = Image.open(image)
210
+ elif isinstance(image, np.ndarray):
211
+ image = Image.fromarray(image)
212
+ elif torch.is_tensor(image):
213
+ image = Image.fromarray(image.permute(1, 2, 0).numpy().astype(np.uint8))
214
+
215
+ plt.imshow(image)
216
+ plt.axis('off') # Turn off axis numbers
217
+ plt.show()
218
+
219
+
220
+ def is_jupyter_notebook():
221
+ """
222
+ Check if the code is running in a Jupyter notebook.
223
+
224
+ Returns:
225
+ bool: True if running in a Jupyter notebook, False otherwise.
226
+ """
227
+ try:
228
+ from IPython import get_ipython
229
+ if 'IPKernelApp' not in get_ipython().config:
230
+ return False
231
+ if 'ipykernel' in str(type(get_ipython())):
232
+ return True # Running in Jupyter Notebook
233
+ except (NameError, AttributeError):
234
+ return False # Not running in Jupyter Notebook
235
+
236
+ return False # Default to False if none of the above conditions are met
237
+
238
+
239
+ def is_pycharm():
240
+ return 'PYCHARM_HOSTED' in os.environ
241
+
242
+
243
+ def is_google_colab():
244
+ return 'COLAB_GPU' in os.environ or 'google.colab' in sys.modules
245
+
246
+
247
+ def get_path(name, path_type):
248
+ """
249
+ Generates a path for models, images, or data based on the specified type.
250
+
251
+ Args:
252
+ name (str): The name of the model, image, or data folder/file.
253
+ path_type (str): The type of path needed ('models', 'images', or 'data').
254
+
255
+ Returns:
256
+ str: The full path to the specified resource.
257
+ """
258
+ # Get the current working directory (assumed to be inside 'code' folder)
259
+ current_dir = os.getcwd()
260
+
261
+ # Get the directory one level up (the parent directory)
262
+ parent_dir = os.path.dirname(current_dir)
263
+
264
+ # Construct the path to the specified folder
265
+ folder_path = os.path.join(parent_dir, path_type)
266
+
267
+ # Construct the full path to the specific resource
268
+ full_path = os.path.join(folder_path, name)
269
+
270
+ return full_path
271
+
272
+
273
+
274
+ if __name__ == "__main__":
275
+ pass
276
+ #val_data = process_okvqa_dataset('OpenEnded_mscoco_val2014_questions.json', 'mscoco_val2014_annotations.json', save_to_csv=True, saved_file_name="okvqa_val.csv")
277
+ #train_data = process_okvqa_dataset('OpenEnded_mscoco_train2014_questions.json', 'mscoco_train2014_annotations.json', save_to_csv=True, saved_file_name="okvqa_train.csv")