|
| 1 | +import logging |
| 2 | +import numpy as np |
| 3 | +import torch |
| 4 | + |
| 5 | +from mmdet.apis import init_detector, inference_detector |
| 6 | +from .mmdet_utils import xyxy_to_xywh |
| 7 | + |
| 8 | +class MMDet(object): |
| 9 | + def __init__(self, cfg_file, checkpoint_file, score_thresh=0.7, |
| 10 | + is_xywh=False, use_cuda=True): |
| 11 | + # net definition |
| 12 | + self.device = "cuda" if use_cuda else "cpu" |
| 13 | + self.net = init_detector(cfg_file, checkpoint_file, device=self.device) |
| 14 | + logger = logging.getLogger("root.detector") |
| 15 | + logger.info('Loading weights from %s... Done!' % (checkpoint_file)) |
| 16 | + |
| 17 | + #constants |
| 18 | + self.score_thresh = score_thresh |
| 19 | + self.use_cuda = use_cuda |
| 20 | + self.is_xywh = is_xywh |
| 21 | + self.class_names = self.net.CLASSES |
| 22 | + self.num_classes = len(self.class_names) |
| 23 | + |
| 24 | + def __call__(self, ori_img): |
| 25 | + # forward |
| 26 | + bbox_result = inference_detector(self.net, ori_img) |
| 27 | + bboxes = np.vstack(bbox_result) |
| 28 | + |
| 29 | + if len(bboxes) == 0: |
| 30 | + bbox = np.array([]).reshape([0, 4]) |
| 31 | + cls_conf = np.array([]) |
| 32 | + cls_ids = np.array([]) |
| 33 | + return bbox, cls_conf, cls_ids |
| 34 | + |
| 35 | + bbox = bboxes[:, :4] |
| 36 | + cls_conf = bboxes[:, 4] |
| 37 | + cls_ids = [ |
| 38 | + np.full(bbox.shape[0], i, dtype=np.int32) |
| 39 | + for i, bbox in enumerate(bbox_result) |
| 40 | + ] |
| 41 | + cls_ids = np.concatenate(cls_ids) |
| 42 | + |
| 43 | + selected_idx = cls_conf > self.score_thresh |
| 44 | + bbox = bbox[selected_idx, :] |
| 45 | + cls_conf = cls_conf[selected_idx] |
| 46 | + cls_ids = cls_ids[selected_idx] |
| 47 | + |
| 48 | + if self.is_xywh: |
| 49 | + bbox = xyxy_to_xywh(bbox) |
| 50 | + |
| 51 | + return bbox, cls_conf, cls_ids |
| 52 | + |
| 53 | + |
| 54 | + |
| 55 | + |
0 commit comments