From a6f96d458b920bae05c798559e31bac026a4ff7a Mon Sep 17 00:00:00 2001 From: deepansh Date: Tue, 27 Feb 2024 22:16:45 +0530 Subject: [PATCH] added log messages to plugins and fixed linting in ObjectDetection.py fixed spelling error Fixed bugs --- .../object_detection/Detectors/RetinaNet.py | 28 ++++++++--- .../object_detection/Detectors/YOLOv5.py | 27 +++++++--- .../object_detection/Detectors/YOLOv8.py | 49 ++++++++++++------- .../object_detection/ObjectDetection.py | 14 +++--- 4 files changed, 81 insertions(+), 37 deletions(-) diff --git a/object_detection/object_detection/Detectors/RetinaNet.py b/object_detection/object_detection/Detectors/RetinaNet.py index c2bf844..d873085 100755 --- a/object_detection/object_detection/Detectors/RetinaNet.py +++ b/object_detection/object_detection/Detectors/RetinaNet.py @@ -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 @@ -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 diff --git a/object_detection/object_detection/Detectors/YOLOv5.py b/object_detection/object_detection/Detectors/YOLOv5.py index 4553004..cc5cccb 100755 --- a/object_detection/object_detection/Detectors/YOLOv5.py +++ b/object_detection/object_detection/Detectors/YOLOv5.py @@ -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 @@ -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 diff --git a/object_detection/object_detection/Detectors/YOLOv8.py b/object_detection/object_detection/Detectors/YOLOv8.py index 41ebb9f..d23afda 100755 --- a/object_detection/object_detection/Detectors/YOLOv8.py +++ b/object_detection/object_detection/Detectors/YOLOv8.py @@ -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 @@ -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 diff --git a/object_detection/object_detection/ObjectDetection.py b/object_detection/object_detection/ObjectDetection.py index 18c65e5..6954ca8 100644 --- a/object_detection/object_detection/ObjectDetection.py +++ b/object_detection/object_detection/ObjectDetection.py @@ -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( @@ -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__) @@ -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: @@ -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']