def boxlist_box_voting(top_boxlist, all_boxlist, thresh, scoring_method='ID', beta=1.0, score_field="scores"): if thresh <= 0: return top_boxlist mode = top_boxlist.mode top_boxes = top_boxlist.convert("xyxy").bbox.cpu() all_boxes = all_boxlist.convert("xyxy").bbox.cpu() top_score = top_boxlist.get_field(score_field).cpu() all_score = all_boxlist.get_field(score_field).cpu() top_dets = np.hstack((top_boxes, top_score[:, np.newaxis])).astype(np.float32, copy=False) all_dets = np.hstack((all_boxes, all_score[:, np.newaxis])).astype(np.float32, copy=False) dets = box_utils.box_voting(top_dets, all_dets, thresh, scoring_method, beta) boxlist = BoxList(torch.from_numpy(dets[:, :4]).cuda(), all_boxlist.size, mode="xyxy") boxlist.add_field("scores", torch.from_numpy(dets[:, -1]).cuda()) return boxlist.convert(mode)
def cat_boxlist(bboxes): """ Concatenates a list of BoxList (having the same image size) into a single BoxList Arguments: bboxes (list[BoxList]) """ assert isinstance(bboxes, (list, tuple)) assert all(isinstance(bbox, BoxList) for bbox in bboxes) size = bboxes[0].size assert all(bbox.size == size for bbox in bboxes) mode = bboxes[0].mode assert all(bbox.mode == mode for bbox in bboxes) fields = set(bboxes[0].fields()) assert all(set(bbox.fields()) == fields for bbox in bboxes) cat_boxes = BoxList(_cat([bbox.bbox for bbox in bboxes], dim=0), size, mode) for field in fields: data = _cat([bbox.get_field(field) for bbox in bboxes], dim=0) cat_boxes.add_field(field, data) return cat_boxes
def boxlist_soft_nms(boxlist, sigma=0.5, overlap_thresh=0.3, score_thresh=0.001, method='linear', score_field="scores"): """ Performs non-maximum suppression on a boxlist, with scores specified in a boxlist field via score_field. Arguments: boxlist(BoxList) nms_thresh (float) max_proposals (int): if > 0, then only the top max_proposals are kept after non-maximum suppression score_field (str) """ if overlap_thresh <= 0: return boxlist mode = boxlist.mode boxlist = boxlist.convert("xyxy") boxes = boxlist.bbox.cpu() score = boxlist.get_field(score_field).cpu() dets = np.hstack((boxes, score[:, np.newaxis])).astype(np.float32, copy=False) dets, _ = box_utils.soft_nms(dets, sigma, overlap_thresh, score_thresh, method) boxlist = BoxList(torch.from_numpy(dets[:, :4]).cuda(), boxlist.size, mode="xyxy") boxlist.add_field("scores", torch.from_numpy(dets[:, -1]).cuda()) return boxlist.convert(mode)
def boxlist_soft_nms(boxlist, sigma=0.5, overlap_thresh=0.3, score_thresh=0.001, method='linear', score_field="scores"): """ Performs non-maximum suppression on a boxlist, with scores specified in a boxlist field via score_field. Arguments: boxlist(BoxList) nms_thresh (float) max_proposals (int): if > 0, then only the top max_proposals are kept after non-maximum suppression score_field (str) """ if overlap_thresh <= 0: return boxlist mode = boxlist.mode boxlist = boxlist.convert("xyxy") boxes = boxlist.bbox.cpu() score = boxlist.get_field(score_field).cpu() dets, scores, _ = _box_soft_nms(boxes, score, sigma, overlap_thresh, score_thresh, method) boxlist = BoxList(dets.cuda(), boxlist.size, mode="xyxy") boxlist.add_field("scores", scores.cuda()) return boxlist.convert(mode)
def forward_for_single_feature_map(self, anchors, objectness, box_regression): """ Arguments: anchors: list[BoxList] objectness: tensor of size N, A, H, W box_regression: tensor of size N, A * 4, H, W """ device = objectness.device N, A, H, W = objectness.shape # put in the same format as anchors objectness = permute_and_flatten(objectness, N, A, 1, H, W).view(N, -1) objectness = objectness.sigmoid() box_regression = permute_and_flatten(box_regression, N, A, 4, H, W) num_anchors = A * H * W pre_nms_top_n = min(self.pre_nms_top_n, num_anchors) objectness, topk_idx = objectness.topk(pre_nms_top_n, dim=1, sorted=True) batch_idx = torch.arange(N, device=device)[:, None] box_regression = box_regression[batch_idx, topk_idx] image_shapes = [box.size for box in anchors] concat_anchors = torch.cat([a.bbox for a in anchors], dim=0) concat_anchors = concat_anchors.reshape(N, -1, 4)[batch_idx, topk_idx] proposals = self.box_coder.decode(box_regression.view(-1, 4), concat_anchors.view(-1, 4)) proposals = proposals.view(N, -1, 4) result = [] for proposal, score, im_shape in zip(proposals, objectness, image_shapes): boxlist = BoxList(proposal, im_shape, mode="xyxy") boxlist.add_field("objectness", score) boxlist = boxlist.clip_to_image(remove_empty=False) boxlist = remove_small_boxes(boxlist, self.min_size) boxlist = boxlist_nms( boxlist, self.nms_thresh, max_proposals=self.post_nms_top_n, score_field="objectness", ) result.append(boxlist) return result
def boxlist_box_voting(top_boxlist, all_boxlist, thresh, scoring_method='ID', beta=1.0, score_field="scores"): if thresh <= 0: return top_boxlist mode = top_boxlist.mode top_boxes = top_boxlist.convert("xyxy").bbox all_boxes = all_boxlist.convert("xyxy").bbox top_score = top_boxlist.get_field(score_field) all_score = all_boxlist.get_field(score_field) boxes, scores = _box_voting(top_boxes, top_score, all_boxes, all_score, thresh, scoring_method, beta) boxlist = BoxList(boxes, all_boxlist.size, mode="xyxy") boxlist.add_field("scores", scores) return boxlist.convert(mode)
def prepare_boxlist(self, boxes, scores, image_shape): """ Returns BoxList from `boxes` and adds probability scores information as an extra field `boxes` has shape (#detections, 4 * #classes), where each row represents a list of predicted bounding boxes for each of the object classes in the dataset (including the background class). The detections in each row originate from the same object proposal. `scores` has shape (#detection, #classes), where each row represents a list of object detection confidence scores for each of the object classes in the dataset (including the background class). `scores[i, j]`` corresponds to the box at `boxes[i, j * 4:(j + 1) * 4]`. """ boxes = boxes.reshape(-1, 4) scores = scores.reshape(-1) boxlist = BoxList(boxes, image_shape, mode="xyxy") boxlist.add_field("scores", scores) return boxlist
def filter_results(self, boxlist, num_classes): """Returns bounding-box detection results by thresholding on scores and applying non-maximum suppression (NMS). """ # unwrap the boxlist to avoid additional overhead. # if we had multi-class NMS, we could perform this directly on the boxlist boxes = boxlist.bbox.reshape(-1, num_classes * 4) scores = boxlist.get_field("scores").reshape(-1, num_classes) device = scores.device result = [] # Apply threshold on detection probabilities and apply NMS # Skip j = 0, because it's the background class inds_all = scores > self.score_thresh for j in range(1, num_classes): inds = inds_all[:, j].nonzero().squeeze(1) scores_j = scores[inds, j] boxes_j = boxes[inds, j * 4 : (j + 1) * 4] boxlist_for_class = BoxList(boxes_j, boxlist.size, mode="xyxy") boxlist_for_class.add_field("scores", scores_j) boxlist_for_class_old = boxlist_for_class if cfg.TEST.SOFT_NMS.ENABLED: boxlist_for_class = boxlist_soft_nms( boxlist_for_class, sigma=cfg.TEST.SOFT_NMS.SIGMA, overlap_thresh=self.nms, score_thresh=0.0001, method=cfg.TEST.SOFT_NMS.METHOD ) else: boxlist_for_class = boxlist_nms( boxlist_for_class, self.nms ) # Refine the post-NMS boxes using bounding-box voting if cfg.TEST.BBOX_VOTE.ENABLED and boxes_j.shape[0] > 0: boxlist_for_class = boxlist_box_voting( boxlist_for_class, boxlist_for_class_old, cfg.TEST.BBOX_VOTE.VOTE_TH, scoring_method=cfg.TEST.BBOX_VOTE.SCORING_METHOD ) num_labels = len(boxlist_for_class) boxlist_for_class.add_field( "labels", torch.full((num_labels,), j, dtype=torch.int64, device=device) ) result.append(boxlist_for_class) result = cat_boxlist(result) number_of_detections = len(result) # Limit to max_per_image detections **over all classes** if number_of_detections > self.detections_per_img > 0: cls_scores = result.get_field("scores") image_thresh, _ = torch.kthvalue( cls_scores.cpu(), number_of_detections - self.detections_per_img + 1 ) keep = cls_scores >= image_thresh.item() keep = torch.nonzero(keep).squeeze(1) result = result[keep] return result
def __getitem__(self, idx): img, anno = super(COCODataset, self).__getitem__(idx) # filter crowd annotations # TODO might be better to add an extra field if 'iscrowd' in anno[0]: anno = [obj for obj in anno if obj["iscrowd"] == 0] boxes = [obj["bbox"] for obj in anno] boxes = torch.as_tensor(boxes).reshape(-1, 4) # guard against no boxes target = BoxList(boxes, img.size, mode="xywh").convert("xyxy") classes = [obj["category_id"] for obj in anno] classes = [self.json_category_id_to_contiguous_id[c] for c in classes] classes = torch.tensor(classes) target.add_field("labels", classes) target = target.clip_to_image(remove_empty=True) if self._transforms is not None: img, target = self._transforms(img, target) return img, target, idx
def forward(self, image_list, feature_maps): grid_sizes = [feature_map.shape[-2:] for feature_map in feature_maps] anchors_over_all_feature_maps = self.grid_anchors(grid_sizes) anchors = [] for i, (image_height, image_width) in enumerate(image_list.image_sizes): anchors_in_image = [] for anchors_per_feature_map in anchors_over_all_feature_maps: boxlist = BoxList(anchors_per_feature_map, (image_width, image_height), mode="xyxy") self.add_visibility_to(boxlist) anchors_in_image.append(boxlist) anchors.append(anchors_in_image) return anchors
def parse_anns(self, image_size, anns): boxes = [ann['bbox'] for ann in anns] boxes = torch.as_tensor(boxes).reshape(-1, 4) # guard against no boxes bbox = BoxList(boxes, image_size, mode="xywh").convert("xyxy") classes = [ann['category_id'] for ann in anns] classes = torch.tensor(classes) bbox.add_field("labels", classes) masks = [ann['segmentation'] for ann in anns] masks = Mask(masks, image_size, mode='poly') bbox.add_field("masks", masks) parsing = [ann['parsing'] for ann in anns] parsing = ParsingPoly(parsing, image_size) bbox.add_field("parsing", parsing) return bbox
def evaluate_box_proposals(predictions, dataset, thresholds=None, area="all", limit=None): """Evaluate detection proposal recall metrics. This function is a much faster alternative to the official COCO API recall evaluation code. However, it produces slightly different results. """ # Record max overlap value for each gt box # Return vector of overlap values areas = { "all": 0, "small": 1, "medium": 2, "large": 3, "96-128": 4, "128-256": 5, "256-512": 6, "512-inf": 7, } area_ranges = [ [0**2, 1e5**2], # all [0**2, 32**2], # small [32**2, 96**2], # medium [96**2, 1e5**2], # large [96**2, 128**2], # 96-128 [128**2, 256**2], # 128-256 [256**2, 512**2], # 256-512 [512**2, 1e5**2], ] # 512-inf assert area in areas, "Unknown area range: {}".format(area) area_range = area_ranges[areas[area]] gt_overlaps = [] num_pos = 0 for image_id, prediction in enumerate(predictions): original_id = dataset.id_to_img_map[image_id] img_info = dataset.get_img_info(image_id) image_width = img_info["width"] image_height = img_info["height"] prediction = prediction.resize((image_width, image_height)) # sort predictions in descending order # TODO maybe remove this and make it explicit in the documentation inds = prediction.get_field("objectness").sort(descending=True)[1] prediction = prediction[inds] ann_ids = dataset.coco.getAnnIds(imgIds=original_id) anno = dataset.coco.loadAnns(ann_ids) gt_boxes = [obj["bbox"] for obj in anno if obj["iscrowd"] == 0] gt_boxes = torch.as_tensor(gt_boxes).reshape( -1, 4) # guard against no boxes gt_boxes = BoxList(gt_boxes, (image_width, image_height), mode="xywh").convert("xyxy") gt_areas = torch.as_tensor( [obj["area"] for obj in anno if obj["iscrowd"] == 0]) if len(gt_boxes) == 0: continue valid_gt_inds = (gt_areas >= area_range[0]) & (gt_areas <= area_range[1]) gt_boxes = gt_boxes[valid_gt_inds] num_pos += len(gt_boxes) if len(gt_boxes) == 0: continue if len(prediction) == 0: continue if limit is not None and len(prediction) > limit: prediction = prediction[:limit] overlaps = boxlist_iou(prediction, gt_boxes) _gt_overlaps = torch.zeros(len(gt_boxes)) for j in range(min(len(prediction), len(gt_boxes))): # find which proposal box maximally covers each gt box # and get the iou amount of coverage for each gt box max_overlaps, argmax_overlaps = overlaps.max(dim=0) # find which gt box is 'best' covered (i.e. 'best' = most iou) gt_ovr, gt_ind = max_overlaps.max(dim=0) assert gt_ovr >= 0 # find the proposal box that covers the best covered gt box box_ind = argmax_overlaps[gt_ind] # record the iou coverage of this gt box _gt_overlaps[j] = overlaps[box_ind, gt_ind] assert _gt_overlaps[j] == gt_ovr # mark the proposal box and the gt box as used overlaps[box_ind, :] = -1 overlaps[:, gt_ind] = -1 # append recorded iou coverage level gt_overlaps.append(_gt_overlaps) gt_overlaps = torch.cat(gt_overlaps, dim=0) gt_overlaps, _ = torch.sort(gt_overlaps) if thresholds is None: step = 0.05 thresholds = torch.arange(0.5, 0.95 + 1e-5, step, dtype=torch.float32) recalls = torch.zeros_like(thresholds) # compute recall for each iou threshold for i, t in enumerate(thresholds): recalls[i] = (gt_overlaps >= t).float().sum() / float(num_pos) # ar = 2 * np.trapz(recalls, thresholds) ar = recalls.mean() return { "ar": ar, "recalls": recalls, "thresholds": thresholds, "gt_overlaps": gt_overlaps, "num_pos": num_pos, }
def forward(self, box_cls_all, box_reg_all, centerness_all, boxes_all): device = box_cls_all.device boxes_per_image = [len(box) for box in boxes_all] cls = box_cls_all.split(boxes_per_image, dim=0) reg = box_reg_all.split(boxes_per_image, dim=0) center = centerness_all.split(boxes_per_image, dim=0) results = [] for box_cls, box_regression, centerness, boxes in zip(cls, reg, center, boxes_all): N, C, H, W = box_cls.shape # put in the same format as locations box_cls = box_cls.permute(0, 2, 3, 1).reshape(N, -1, self.num_classes).sigmoid() box_regression = box_regression.permute(0, 2, 3, 1).reshape(N, -1, 4) centerness = centerness.permute(0, 2, 3, 1).reshape(N, -1).sigmoid() # multiply the classification scores with centerness scores box_cls = box_cls * centerness[:, :, None] _boxes = boxes.bbox size = boxes.size boxes_scores = boxes.get_field("scores") results_per_image = [boxes] for i in range(N): box = _boxes[i] boxes_score = boxes_scores[i] per_box_cls = box_cls[i] per_box_cls_max, per_box_cls_inds = per_box_cls.max(dim=0) per_class = torch.range(2, 1 + self.num_classes, dtype=torch.long, device=device) per_box_regression = box_regression[i] per_box_regression = per_box_regression[per_box_cls_inds] x_step = 1.0 y_step = 1.0 shifts_x = torch.arange( 0, self.m, step=x_step, dtype=torch.float32, device=device ) + x_step / 2 shifts_y = torch.arange( 0, self.m, step=y_step, dtype=torch.float32, device=device ) + y_step / 2 shift_y, shift_x = torch.meshgrid(shifts_y, shifts_x) shift_x = shift_x.reshape(-1) shift_y = shift_y.reshape(-1) locations = torch.stack((shift_x, shift_y), dim=1) per_locations = locations[per_box_cls_inds] _x1 = per_locations[:, 0] - per_box_regression[:, 0] _y1 = per_locations[:, 1] - per_box_regression[:, 1] _x2 = per_locations[:, 0] + per_box_regression[:, 2] _y2 = per_locations[:, 1] + per_box_regression[:, 3] _x1 = _x1 / self.m * (box[2] - box[0]) + box[0] _y1 = _y1 / self.m * (box[3] - box[1]) + box[1] _x2 = _x2 / self.m * (box[2] - box[0]) + box[0] _y2 = _y2 / self.m * (box[3] - box[1]) + box[1] detections = torch.stack([_x1, _y1, _x2, _y2], dim=-1) boxlist = BoxList(detections, size, mode="xyxy") boxlist.add_field("labels", per_class) boxlist.add_field("scores", torch.sqrt(torch.sqrt(per_box_cls_max) * boxes_score)) boxlist = boxlist.clip_to_image(remove_empty=False) boxlist = remove_small_boxes(boxlist, 0) results_per_image.append(boxlist) results_per_image = cat_boxlist(results_per_image) results.append(results_per_image) return results
def filter_results(boxlist): num_classes = cfg.MODEL.NUM_CLASSES if not cfg.TEST.SOFT_NMS.ENABLED and not cfg.TEST.BBOX_VOTE.ENABLED: # multiclass nms scores = boxlist.get_field("scores") device = scores.device num_repeat = int(boxlist.bbox.shape[0] / num_classes) labels = np.tile(np.arange(num_classes), num_repeat) boxlist.add_field( "labels", torch.from_numpy(labels).to(dtype=torch.int64, device=device)) fg_labels = torch.from_numpy( (np.arange(boxlist.bbox.shape[0]) % num_classes != 0).astype(int)).to(dtype=torch.bool, device=device) _scores = scores > cfg.FAST_RCNN.SCORE_THRESH inds_all = _scores & fg_labels result = boxlist_ml_nms(boxlist[inds_all], cfg.FAST_RCNN.NMS) else: # boxes = boxlist.bbox.reshape(-1, num_classes * 4) boxes = boxlist.bbox.reshape(-1, 4) labels = boxlist.get_field('labels') scores = boxlist.get_field("scores") # scores = boxlist.get_field("scores").reshape(-1, num_classes) device = scores.device result = [] # Apply threshold on detection probabilities and apply NMS # Skip j = 0, because it's the background class inds_all = scores > cfg.FAST_RCNN.SCORE_THRESH for j in range(1, num_classes): # inds = inds_all[:, j].nonzero().squeeze(1) class_inds = labels == j inds = (inds_all + class_inds == 2) scores_j = scores[inds] boxes_j = boxes[inds] # scores_j = scores[inds, j] # boxes_j = boxes[inds, j * 4 : (j + 1) * 4] boxlist_for_class = BoxList(boxes_j, boxlist.size, mode="xyxy") boxlist_for_class.add_field("scores", scores_j) boxlist_for_class_old = boxlist_for_class if cfg.TEST.SOFT_NMS.ENABLED: boxlist_for_class = boxlist_soft_nms( boxlist_for_class, sigma=cfg.TEST.SOFT_NMS.SIGMA, overlap_thresh=cfg.FAST_RCNN.NMS, score_thresh=0.0001, method=cfg.TEST.SOFT_NMS.METHOD) else: boxlist_for_class = boxlist_nms(boxlist_for_class, cfg.FAST_RCNN.NMS) # Refine the post-NMS boxes using bounding-box voting if cfg.TEST.BBOX_VOTE.ENABLED and boxes_j.shape[0] > 0: boxlist_for_class = boxlist_box_voting( boxlist_for_class, boxlist_for_class_old, cfg.TEST.BBOX_VOTE.VOTE_TH, scoring_method=cfg.TEST.BBOX_VOTE.SCORING_METHOD) num_labels = len(boxlist_for_class) boxlist_for_class.add_field( "labels", torch.full((num_labels, ), j, dtype=torch.int64, device=device)) result.append(boxlist_for_class) result = cat_boxlist(result) number_of_detections = len(result) # Limit to max_per_image detections **over all classes** if number_of_detections > cfg.FAST_RCNN.DETECTIONS_PER_IMG > 0: cls_scores = result.get_field("scores") image_thresh, _ = torch.kthvalue( cls_scores.cpu(), number_of_detections - cfg.FAST_RCNN.DETECTIONS_PER_IMG + 1) keep = cls_scores >= image_thresh.item() keep = torch.nonzero(keep).squeeze(1) result = result[keep] return result
def prepare_boxlist(self, boxes, scores, image_shape): boxes = boxes.reshape(-1, 4) scores = scores.reshape(-1) boxlist = BoxList(boxes, image_shape, mode="xyxy") boxlist.add_field("scores", scores) return boxlist