def get_center_crop_bbox(center_bboxes_in, im_width=None, im_height=None, warning=True, debug=True): ''' obtain a bbox to crop around a center point parameters: center_bboxes_in: a list of 2 or 4 scalar elements, or (N, 2) / (N, 4) numpy array 2 - > [crop_width, crop_height], the center is the image center 4 - > [center_x, center_y, crop_width, crop_height] im_width/im_height: scalar outputs: crop_bboxes: TLHW format, an int64 numpy array with shape of (N, 4) ''' np_center_bboxes = safe_center_bbox(center_bboxes_in, warning=warning, debug=debug) if debug: assert iscenterbbox(np_center_bboxes), 'the center bbox does not have a good shape' if np_center_bboxes.shape[1] == 4: # crop around the given center and width and height center_x = np_center_bboxes[:, 0] center_y = np_center_bboxes[:, 1] crop_width = np_center_bboxes[:, 2] crop_height = np_center_bboxes[:, 3] else: # crop around the center of the image if debug: assert (im_width is not None) and (im_height is not None), 'the image shape should be known when center is not provided' center_x = np.ceil(im_width / 2) center_y = np.ceil(im_height / 2) crop_width = np_center_bboxes[:, 0] crop_height = np_center_bboxes[:, 1] xmin = center_x - np.ceil(crop_width / 2) ymin = center_y - np.ceil(crop_height / 2) crop_bboxes = np.hstack((xmin.reshape((-1, 1)), ymin.reshape((-1, 1)), crop_width.reshape((-1, 1)), crop_height.reshape((-1, 1)))) crop_bboxes = crop_bboxes.astype('int64') return crop_bboxes
def safe_center_bbox(input_bbox, warning=True, debug=True): ''' make sure to copy the center bbox without modifying it and make the dimension to N x 4 or N x 2 parameters: input_bbox: a list of 4 (2) elements, a listoflist of 4 (2) elements: e.g., [[1,2,3,4], [5,6,7,8]], a numpy array with shape or (N, 4) or (4, ) or (N, 2) or (2, ) outputs: np_bboxes: N X 4 (2) numpy array ''' if islist(input_bbox): if islistoflist(input_bbox): if debug: assert all( len(list_tmp) == 4 or len(list_tmp) == 2 for list_tmp in input_bbox), 'all sub-lists should have length of 4' np_bboxes = np.array(input_bbox) else: if debug: assert len(input_bbox) == 4 or len( input_bbox ) == 2, 'the center bboxes list does not have a good shape' if len(input_bbox) == 4: np_bboxes = np.array(input_bbox).reshape((1, 4)) else: np_bboxes = np.array(input_bbox).reshape((1, 2)) elif isnparray(input_bbox): input_bbox = input_bbox.copy() if input_bbox.shape == (4, ): np_bboxes = input_bbox.reshape((1, 4)) elif input_bbox.shape == (2, ): np_bboxes = input_bbox.reshape((1, 2)) else: if debug: assert iscenterbbox( input_bbox ), 'the input center bbox numpy array does not have a good shape' np_bboxes = input_bbox else: assert False, 'only list and numpy array for bbox are supported' return np_bboxes