Skip to content

Commit

Permalink
added log messages to plugins and fixed linting in ObjectDetection.py
Browse files Browse the repository at this point in the history
fixed spelling error

Fixed bugs
  • Loading branch information
sudo-deep committed Feb 27, 2024
1 parent d2f65ae commit a6f96d4
Show file tree
Hide file tree
Showing 4 changed files with 81 additions and 37 deletions.
28 changes: 21 additions & 7 deletions object_detection/object_detection/Detectors/RetinaNet.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,30 +23,43 @@

class RetinaNet(DetectorBase):

def __init__(self):
super.__init__()
def __init__(self, logger):
super().__init__(logger)

# Create a logger instance
self.logger = super().get_logger()

def build_model(self, model_dir_path, weight_file_name):
model_path = os.path.join(model_dir_path, weight_file_name)

try:
self.model = models.load_model(model_path, backbone_name='resnet50')
self.logger.info("[RetinaNet] Model successfully loaded from: {}".format(model_path))
except Exception as e:
print("Loading the model failed with exception {}".format(e))
self.logger.error("[RetinaNet] Loading model failed with exception: {}".format(e))
raise Exception("Error loading given model from path: {}.".format(model_path) +
"Maybe the file doesn't exist?")
" Maybe the file doesn't exist?")

def load_classes(self, model_dir_path):
self.class_list = []
fpath = os.path.join(model_dir_path, 'classes.txt')

with open(model_dir_path + "/classes.txt", "r") as f:
self.class_list = [cname.strip() for cname in f.readlines()]
try:
with open(os.path.join(model_dir_path, "classes.txt"), "r") as f:
self.class_list = [cname.strip() for cname in f.readlines()]
self.logger.info("[RetinaNet] Loaded classes from {}".format(fpath))
except FileNotFoundError:
self.logger.error("[RetinaNet] Classes file not found at path: {}".format(fpath))
raise FileNotFoundError("Classes file not found. Make sure the file exists at the specified path.")
except Exception as e:
self.logger.error("[RetinaNet] Error loading classes with exception: {}".format(e))
raise Exception("Error loading classes from file: {}".format(fpath))

return self.class_list

def get_predictions(self, cv_image):
if cv_image is None:
# TODO: show warning message (different color, maybe)
self.logger.warning("[RetinaNet] Input image is None. No predictions will be generated.")
return None
else:
# copy to draw on
Expand All @@ -71,5 +84,6 @@ def get_predictions(self, cv_image):
boxes = [[int(coord/scale) for coord in box] for box in boxes]

super().create_predictions_list(class_ids, confidences, boxes)
self.logger.debug("[RetinaNet] Object detection successfully performed on the input image.")

return self.predictions
27 changes: 20 additions & 7 deletions object_detection/object_detection/Detectors/YOLOv5.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,31 +21,43 @@

class YOLOv5(DetectorBase):

def __init__(self, conf_threshold=0.7):
super().__init__()
def __init__(self, logger, conf_threshold=0.7):
super().__init__(logger)
self.conf_threshold = conf_threshold

# Create a logger instance
self.logger = super().get_logger()

def build_model(self, model_dir_path, weight_file_name):
try:
model_path = os.path.join(model_dir_path, weight_file_name)
self.model = torch.hub.load('ultralytics/yolov5:v6.0', 'custom', path=model_path,
force_reload=True)
self.logger.info("[YOLOv5] Model successfully loaded from: {}".format(model_path))
except Exception as e:
print("Loading model failed with exception: {}".format(e))
self.logger.error("[YOLOv5] Loading model failed with exception: {}".format(e))
raise Exception("Error loading given model from path: {}.".format(model_path) +
" Maybe the file doesn't exist?")

def load_classes(self, model_dir_path):
self.class_list = []

with open(os.path.join(model_dir_path, 'classes.txt')) as f:
self.class_list = [cname.strip() for cname in f.readlines()]
fpath = os.path.join(model_dir_path, 'classes.txt')
try:
with open(fpath) as f:
self.class_list = [cname.strip() for cname in f.readlines()]
self.logger.info("[YOLOv5] Loaded classes from {}".format(fpath))
except FileNotFoundError:
self.logger.error("[YOLOv5] Classes file not found at path: {}".format(fpath))
raise FileNotFoundError("Classes file not found. Make sure the file exists at the specified path.")
except Exception as e:
self.logger.error("[YOLOv5] Error loading classes with exception: {}".format(e))
raise Exception("Error loading classes from file: {}".format(fpath))

return self.class_list

def get_predictions(self, cv_image):
if cv_image is None:
# TODO: show warning message (different color, maybe)
self.logger.warning("[YOLOv5] Input image is None. No predictions will be generated.")
return None, None
else:
self.frame = cv_image
Expand All @@ -61,5 +73,6 @@ def get_predictions(self, cv_image):
boxes.append([int(xy) for xy in xyxy])

super().create_predictions_list(class_id, confidence, boxes)
self.logger.debug("[YOLOv5] Object detection successfully performed on the input image.")

return self.predictions
49 changes: 32 additions & 17 deletions object_detection/object_detection/Detectors/YOLOv8.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,30 +21,40 @@

class YOLOv8(DetectorBase):

def __init__(self):
def __init__(self, logger):

super().__init__()
super().__init__(logger)

def build_model(self, model_dir_path, weight_file_name):
try:
model_path = os.path.join(model_dir_path, weight_file_name)
self.model = YOLO(model_path)
self.logger.info("[YOLOv8] Model successfully loaded from: {}".format(model_path))
except Exception as e:
print("Loading model failed with exception: {}".format(e))
raise Exception("Error loading given model from path: {}.".format(model_path) +
" Maybe the file doesn't exist?")
self.logger.error("[YOLOv8] Failed to load model with exception: {}".format(e))
raise Exception("Error loading the given model from path: {}.".format(model_path) +
" Make sure the file exists and the format is correct.")

def load_classes(self, model_dir_path):
self.class_list = []
fpath = os.path.join(model_dir_path, "classes.txt")

with open(model_dir_path + "/classes.txt", "r") as f:
self.class_list = [cname.strip() for cname in f.readlines()]
try:
with open(fpath, "r") as f:
self.class_list = [cname.strip() for cname in f.readlines()]
self.logger.info("[YOLOv8] Loaded classes from {}".format(fpath))
except FileNotFoundError:
self.logger.error("[YOLOv8] Classes file not found at path: {}".format(fpath))
raise FileNotFoundError("Classes file not found. Make sure the file exists at the specified path.")
except Exception as e:
self.logger.error("[YOLOv8] Error loading classes with exception: {}".format(e))
raise Exception("Error loading classes from file: {}".format(fpath))

return self.class_list

def get_predictions(self, cv_image):
if cv_image is None:
# TODO: show warning message (different color, maybe)
self.logger.warning("[YOLOv8] Input image is None. No predictions will be generated.")
return None, None
else:
self.frame = cv_image
Expand All @@ -53,14 +63,19 @@ def get_predictions(self, cv_image):
boxes = []

# Perform object detection on image
result = self.model.predict(self.frame, verbose=False) # Perform object detection on image
row = result[0].boxes.cpu()

for box in row:
class_id.append(box.cls.numpy().tolist()[0])
confidence.append(box.conf.numpy().tolist()[0])
boxes.append(box.xyxy.numpy().tolist()[0])

super().create_predictions_list(class_id, confidence, boxes)
try:
result = self.model.predict(self.frame, verbose=False)
row = result[0].boxes.cpu()

for box in row:
class_id.append(box.cls.numpy().tolist()[0])
confidence.append(box.conf.numpy().tolist()[0])
boxes.append(box.xyxy.numpy().tolist()[0])

super().create_predictions_list(class_id, confidence, boxes)
self.logger.debug("[YOLOv8] Object detection successfully performed on the input image.")
except Exception as e:
self.logger.error("[YOLOv8] Object detection failed with exception: {}".format(e))
raise Exception("Error performing object detection on the input image.")

return self.predictions
14 changes: 8 additions & 6 deletions object_detection/object_detection/ObjectDetection.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def __init__(self):
self.available_detectors = []

# Create a logger instance
self.logger = super().get_logger()
self.logger = super().get_logger()

# Declare parameters with default values
self.declare_parameters(
Expand Down Expand Up @@ -86,8 +86,8 @@ def load_parameters(self):
self.show_fps = self.get_parameter('model_params.show_fps').value

self.logger.info("[OBJECT DETECTION] Detector type set to {} and".format(self.detector_type) +
" using weigth file from {}".format(self.model_dir_path + self.weight_file_name))
self.logger.info("[OBJECT DETECTION] Confidence threshold for detection set to: {}".format(self.confidence_threshold))
" using weight file from {}".format(self.model_dir_path + self.weight_file_name))
self.logger.info("[OBJECT DETECTION] Detection confidence threshold set to: {}".format(self.confidence_threshold))

def discover_detectors(self):
curr_dir = os.path.dirname(__file__)
Expand All @@ -102,8 +102,9 @@ def discover_detectors(self):
def load_detector(self):
# Raise an exception if specified detector was not found
if self.detector_type not in self.available_detectors:
self.logger.error("[OBJECT DETECTION] {} Detector was set in parameters but was not found. Check the " +
"Detectors directory for list of available detectors".format(self.detector_type))
self.logger.error("[OBJECT DETECTION]" +
" {} Detector was set in parameters but was not found".format(self.detector_type) +
"Check the Detectors directory for list of available detectors")
raise ModuleNotFoundError(self.detector_type + " Detector specified in config was not found. " +
"Check the Detectors dir for available detectors.")
else:
Expand All @@ -123,7 +124,8 @@ def detection_cb(self, img_msg):
predictions = self.detector.get_predictions(cv_image=cv_image)

if predictions is None:
self.logger.warning("[OBJECT DETECTION] Image input from topic: {} is empty".format(self.input_img_topic), throttle_duration_sec=1)
self.logger.warning("[OBJECT DETECTION] " +
"Image input from topic: {} is empty".format(self.input_img_topic), throttle_duration_sec=1)
else:
for prediction in predictions:
confidence = prediction['confidence']
Expand Down

0 comments on commit a6f96d4

Please sign in to comment.