Python numpy.empty() Examples
The following are 30
code examples of numpy.empty().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
numpy
, or try the search function
.

Example #1
Source File: test_masks.py From mmdetection with Apache License 2.0 | 8 votes |
def test_bitmap_mask_pad(): # pad with empty bitmap masks raw_masks = dummy_raw_bitmap_masks((0, 28, 28)) bitmap_masks = BitmapMasks(raw_masks, 28, 28) padded_masks = bitmap_masks.pad((56, 56)) assert len(padded_masks) == 0 assert padded_masks.height == 56 assert padded_masks.width == 56 # pad with bitmap masks contain 3 instances raw_masks = dummy_raw_bitmap_masks((3, 28, 28)) bitmap_masks = BitmapMasks(raw_masks, 28, 28) padded_masks = bitmap_masks.pad((56, 56)) assert len(padded_masks) == 3 assert padded_masks.height == 56 assert padded_masks.width == 56 assert (padded_masks.masks[:, 28:, 28:] == 0).all()
Example #2
Source File: NLP.py From Financial-NLP with Apache License 2.0 | 7 votes |
def wordbag2mat(self, wordbag): #testing if self.model==None: raise Exception("no model") matrix=np.empty((len(wordbag),self.len_vector)) #如果词典中不存在该词,抛出异常,但暂时还没有自定义词典的办法,所以暂时不那么严格 #try: # for i in range(len(wordbag)): # matrix[i,:]=self.model[wordbag[i]] #except: # raise Exception("'%s' can not be found in dictionary." % wordbag[i]) #如果词典中不存在该词,则push进一列零向量 for i in range(len(wordbag)): try: matrix[i,:]=self.model.wv.__getitem__(wordbag[i])#[wordbag[i]] except: matrix[i,:]=np.zeros((1,self.len_vector)) return matrix ################################ problem #####################################
Example #3
Source File: structures.py From mmdetection with Apache License 2.0 | 7 votes |
def __init__(self, masks, height, width): self.height = height self.width = width if len(masks) == 0: self.masks = np.empty((0, self.height, self.width), dtype=np.uint8) else: assert isinstance(masks, (list, np.ndarray)) if isinstance(masks, list): assert isinstance(masks[0], np.ndarray) assert masks[0].ndim == 2 # (H, W) else: assert masks.ndim == 3 # (N, H, W) self.masks = np.stack(masks).reshape(-1, height, width) assert self.masks.shape[1] == self.height assert self.masks.shape[2] == self.width
Example #4
Source File: mean_ap.py From mmdetection with Apache License 2.0 | 7 votes |
def get_cls_results(det_results, annotations, class_id): """Get det results and gt information of a certain class. Args: det_results (list[list]): Same as `eval_map()`. annotations (list[dict]): Same as `eval_map()`. class_id (int): ID of a specific class. Returns: tuple[list[np.ndarray]]: detected bboxes, gt bboxes, ignored gt bboxes """ cls_dets = [img_res[class_id] for img_res in det_results] cls_gts = [] cls_gts_ignore = [] for ann in annotations: gt_inds = ann['labels'] == class_id cls_gts.append(ann['bboxes'][gt_inds, :]) if ann.get('labels_ignore', None) is not None: ignore_inds = ann['labels_ignore'] == class_id cls_gts_ignore.append(ann['bboxes_ignore'][ignore_inds, :]) else: cls_gts_ignore.append(np.empty((0, 4), dtype=np.float32)) return cls_dets, cls_gts, cls_gts_ignore
Example #5
Source File: ndarray.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 7 votes |
def asnumpy(self): """Returns a ``numpy.ndarray`` object with value copied from this array. Examples -------- >>> x = mx.nd.ones((2,3)) >>> y = x.asnumpy() >>> type(y) <type 'numpy.ndarray'> >>> y array([[ 1., 1., 1.], [ 1., 1., 1.]], dtype=float32) >>> z = mx.nd.ones((2,3), dtype='int32') >>> z.asnumpy() array([[1, 1, 1], [1, 1, 1]], dtype=int32) """ data = np.empty(self.shape, dtype=self.dtype) check_call(_LIB.MXNDArraySyncCopyToCPU( self.handle, data.ctypes.data_as(ctypes.c_void_p), ctypes.c_size_t(data.size))) return data
Example #6
Source File: test_masks.py From mmdetection with Apache License 2.0 | 7 votes |
def test_bitmap_mask_resize(): # resize with empty bitmap masks raw_masks = dummy_raw_bitmap_masks((0, 28, 28)) bitmap_masks = BitmapMasks(raw_masks, 28, 28) resized_masks = bitmap_masks.resize((56, 72)) assert len(resized_masks) == 0 assert resized_masks.height == 56 assert resized_masks.width == 72 # resize with bitmap masks contain 1 instances raw_masks = np.diag(np.ones(4, dtype=np.uint8))[np.newaxis, ...] bitmap_masks = BitmapMasks(raw_masks, 4, 4) resized_masks = bitmap_masks.resize((8, 8)) assert len(resized_masks) == 1 assert resized_masks.height == 8 assert resized_masks.width == 8 truth = np.array([[[1, 1, 0, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 0, 0, 0, 0], [0, 0, 1, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 0, 1, 1]]]) assert (resized_masks.masks == truth).all()
Example #7
Source File: test_masks.py From mmdetection with Apache License 2.0 | 7 votes |
def test_bitmap_mask_crop(): # crop with empty bitmap masks dummy_bbox = np.array([0, 10, 10, 27], dtype=np.int) raw_masks = dummy_raw_bitmap_masks((0, 28, 28)) bitmap_masks = BitmapMasks(raw_masks, 28, 28) cropped_masks = bitmap_masks.crop(dummy_bbox) assert len(cropped_masks) == 0 assert cropped_masks.height == 17 assert cropped_masks.width == 10 # crop with bitmap masks contain 3 instances raw_masks = dummy_raw_bitmap_masks((3, 28, 28)) bitmap_masks = BitmapMasks(raw_masks, 28, 28) cropped_masks = bitmap_masks.crop(dummy_bbox) assert len(cropped_masks) == 3 assert cropped_masks.height == 17 assert cropped_masks.width == 10 x1, y1, x2, y2 = dummy_bbox assert (cropped_masks.masks == raw_masks[:, y1:y2, x1:x2]).all() # crop with invalid bbox with pytest.raises(AssertionError): dummy_bbox = dummy_bboxes(2, 28, 28) bitmap_masks.crop(dummy_bbox)
Example #8
Source File: common.py From numpynet with BSD 3-Clause "New" or "Revised" License | 6 votes |
def predict_2d_space(net, delta=0.05): """ Iterate predictions over a 2d space :param net: (object) A NumpyNet model object :param delta: space between predictions :return: prediction_matrix: the actual predictions axis_x and axis_y: the axes (useful for plotting) """ axis_x = np.arange(net.predict_space[0], net.predict_space[1] + delta, delta) axis_y = np.arange(net.predict_space[2], net.predict_space[3] + delta, delta) prediction_matrix = np.empty((len(axis_x), len(axis_y))) for i, x in enumerate(axis_x): for j, y in enumerate(axis_y): test_prediction = np.array([x, y]) test_prediction = net.predict(test_prediction) prediction_matrix[i, j] = test_prediction return prediction_matrix, axis_x, axis_y
Example #9
Source File: utils.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 6 votes |
def sample_categorical(prob, rng): """Sample from independent categorical distributions Each batch is an independent categorical distribution. Parameters ---------- prob : numpy.ndarray Probability of the categorical distribution. Shape --> (batch_num, category_num) rng : numpy.random.RandomState Returns ------- ret : numpy.ndarray Sampling result. Shape --> (batch_num,) """ ret = numpy.empty(prob.shape[0], dtype=numpy.float32) for ind in range(prob.shape[0]): ret[ind] = numpy.searchsorted(numpy.cumsum(prob[ind]), rng.rand()).clip(min=0.0, max=prob.shape[ 1] - 0.5) return ret
Example #10
Source File: Utility.py From fuku-ml with MIT License | 6 votes |
def random_projection(X): data_demension = X.shape[1] new_data_demension = random.randint(2, data_demension) new_X = np.empty((data_demension, new_data_demension)) minus_one = 0.1 positive_one = 0.9 for i in range(len(new_X)): for j in range(len(new_X[i])): rand = random.random() if rand < minus_one: new_X[i][j] = -1.0 elif rand >= positive_one: new_X[i][j] = 1.0 else: new_X[i][j] = 0.0 new_X = np.inner(X, new_X.T) return new_X
Example #11
Source File: ndarray.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 6 votes |
def _new_alloc_handle(shape, ctx, delay_alloc, dtype=mx_real_t): """Return a new handle with specified shape and context. Empty handle is only used to hold results. Returns ------- handle A new empty `NDArray` handle. """ hdl = NDArrayHandle() check_call(_LIB.MXNDArrayCreateEx( c_array_buf(mx_uint, native_array('I', shape)), mx_uint(len(shape)), ctypes.c_int(ctx.device_typeid), ctypes.c_int(ctx.device_id), ctypes.c_int(int(delay_alloc)), ctypes.c_int(int(_DTYPE_NP_TO_MX[np.dtype(dtype).type])), ctypes.byref(hdl))) return hdl
Example #12
Source File: dataloader_m.py From models with MIT License | 6 votes |
def map_values(values, pos, target_pos, dtype=None, nan=dat.CPG_NAN): """Maps `values` array at positions `pos` to `target_pos`. Inserts `nan` for uncovered positions. """ assert len(values) == len(pos) assert np.all(pos == np.sort(pos)) assert np.all(target_pos == np.sort(target_pos)) values = values.ravel() pos = pos.ravel() target_pos = target_pos.ravel() idx = np.in1d(pos, target_pos) pos = pos[idx] values = values[idx] if not dtype: dtype = values.dtype target_values = np.empty(len(target_pos), dtype=dtype) target_values.fill(nan) idx = np.in1d(target_pos, pos).nonzero()[0] assert len(idx) == len(values) assert np.all(target_pos[idx] == pos) target_values[idx] = values return target_values
Example #13
Source File: test_masks.py From mmdetection with Apache License 2.0 | 6 votes |
def test_polygon_mask_pad(): # pad with empty polygon masks raw_masks = dummy_raw_polygon_masks((0, 28, 28)) polygon_masks = PolygonMasks(raw_masks, 28, 28) padded_masks = polygon_masks.pad((56, 56)) assert len(padded_masks) == 0 assert padded_masks.height == 56 assert padded_masks.width == 56 assert padded_masks.to_ndarray().shape == (0, 56, 56) # pad with polygon masks contain 3 instances raw_masks = dummy_raw_polygon_masks((3, 28, 28)) polygon_masks = PolygonMasks(raw_masks, 28, 28) padded_masks = polygon_masks.pad((56, 56)) assert len(padded_masks) == 3 assert padded_masks.height == 56 assert padded_masks.width == 56 assert padded_masks.to_ndarray().shape == (3, 56, 56) assert (padded_masks.to_ndarray()[:, 28:, 28:] == 0).all()
Example #14
Source File: test_masks.py From mmdetection with Apache License 2.0 | 6 votes |
def test_polygon_mask_crop_and_resize(): dummy_bbox = dummy_bboxes(5, 28, 28) inds = np.random.randint(0, 3, (5, )) # crop and resize with empty polygon masks raw_masks = dummy_raw_polygon_masks((0, 28, 28)) polygon_masks = PolygonMasks(raw_masks, 28, 28) cropped_resized_masks = polygon_masks.crop_and_resize( dummy_bbox, (56, 56), inds) assert len(cropped_resized_masks) == 0 assert cropped_resized_masks.height == 56 assert cropped_resized_masks.width == 56 assert cropped_resized_masks.to_ndarray().shape == (0, 56, 56) # crop and resize with polygon masks contain 3 instances raw_masks = dummy_raw_polygon_masks((3, 28, 28)) polygon_masks = PolygonMasks(raw_masks, 28, 28) cropped_resized_masks = polygon_masks.crop_and_resize( dummy_bbox, (56, 56), inds) assert len(cropped_resized_masks) == 5 assert cropped_resized_masks.height == 56 assert cropped_resized_masks.width == 56 assert cropped_resized_masks.to_ndarray().shape == (5, 56, 56)
Example #15
Source File: test_masks.py From mmdetection with Apache License 2.0 | 6 votes |
def test_bitmap_mask_crop_and_resize(): dummy_bbox = dummy_bboxes(5, 28, 28) inds = np.random.randint(0, 3, (5, )) # crop and resize with empty bitmap masks raw_masks = dummy_raw_bitmap_masks((0, 28, 28)) bitmap_masks = BitmapMasks(raw_masks, 28, 28) cropped_resized_masks = bitmap_masks.crop_and_resize( dummy_bbox, (56, 56), inds) assert len(cropped_resized_masks) == 0 assert cropped_resized_masks.height == 56 assert cropped_resized_masks.width == 56 # crop and resize with bitmap masks contain 3 instances raw_masks = dummy_raw_bitmap_masks((3, 28, 28)) bitmap_masks = BitmapMasks(raw_masks, 28, 28) cropped_resized_masks = bitmap_masks.crop_and_resize( dummy_bbox, (56, 56), inds) assert len(cropped_resized_masks) == 5 assert cropped_resized_masks.height == 56 assert cropped_resized_masks.width == 56
Example #16
Source File: object_detection_evaluation.py From DOTA_models with Apache License 2.0 | 6 votes |
def __init__(self, num_groundtruth_classes, matching_iou_threshold=0.5, nms_iou_threshold=1.0, nms_max_output_boxes=10000): self.per_image_eval = per_image_evaluation.PerImageEvaluation( num_groundtruth_classes, matching_iou_threshold, nms_iou_threshold, nms_max_output_boxes) self.num_class = num_groundtruth_classes self.groundtruth_boxes = {} self.groundtruth_class_labels = {} self.groundtruth_is_difficult_list = {} self.num_gt_instances_per_class = np.zeros(self.num_class, dtype=int) self.num_gt_imgs_per_class = np.zeros(self.num_class, dtype=int) self.detection_keys = set() self.scores_per_class = [[] for _ in range(self.num_class)] self.tp_fp_labels_per_class = [[] for _ in range(self.num_class)] self.num_images_correctly_detected_per_class = np.zeros(self.num_class) self.average_precision_per_class = np.empty(self.num_class, dtype=float) self.average_precision_per_class.fill(np.nan) self.precisions_per_class = [] self.recalls_per_class = [] self.corloc_per_class = np.ones(self.num_class, dtype=float)
Example #17
Source File: buffer.py From PyOptiX with MIT License | 5 votes |
def to_array(self): numpy_array = numpy.empty(self._numpy_shape, dtype=self.dtype) self.copy_to_array(numpy_array) return numpy_array
Example #18
Source File: test_masks.py From mmdetection with Apache License 2.0 | 5 votes |
def test_polygon_to_tensor(): # empty polygon masks to tensor raw_masks = dummy_raw_polygon_masks((0, 28, 28)) polygon_masks = PolygonMasks(raw_masks, 28, 28) tensor_masks = polygon_masks.to_tensor(dtype=torch.uint8, device='cpu') assert isinstance(tensor_masks, torch.Tensor) assert tensor_masks.shape == (0, 28, 28) # polygon masks contain 3 instances to tensor raw_masks = dummy_raw_polygon_masks((3, 28, 28)) polygon_masks = PolygonMasks(raw_masks, 28, 28) tensor_masks = polygon_masks.to_tensor(dtype=torch.uint8, device='cpu') assert isinstance(tensor_masks, torch.Tensor) assert tensor_masks.shape == (3, 28, 28) assert (tensor_masks.numpy() == polygon_masks.to_ndarray()).all()
Example #19
Source File: policies.py From soccer-matlab with BSD 2-Clause "Simplified" License | 5 votes |
def __init__(self, policy_params): self.ob_dim = policy_params['ob_dim'] self.ac_dim = policy_params['ac_dim'] self.weights = np.empty(0) # a filter for updating statistics of the observations and normalizing # inputs to the policies self.observation_filter = filter.get_filter( policy_params['ob_filter'], shape=(self.ob_dim,)) self.update_filter = True
Example #20
Source File: mxnet_predict.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 5 votes |
def get_output(self, index): """Get the index-th output. Parameters ---------- index : int The index of output. Returns ------- out : numpy array. The output array. """ pdata = ctypes.POINTER(mx_uint)() ndim = mx_uint() _check_call(_LIB.MXPredGetOutputShape( self.handle, index, ctypes.byref(pdata), ctypes.byref(ndim))) shape = tuple(pdata[:ndim.value]) data = np.empty(shape, dtype=np.float32) _check_call(_LIB.MXPredGetOutput( self.handle, mx_uint(index), data.ctypes.data_as(mx_float_p), mx_uint(data.size))) return data
Example #21
Source File: ndarray.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 5 votes |
def empty(shape, ctx=None, dtype=None): """Returns a new array of given shape and type, without initializing entries. Parameters ---------- shape : int or tuple of int The shape of the empty array. ctx : Context, optional An optional device context (default is the current default context). dtype : str or numpy.dtype, optional An optional value type (default is `float32`). Returns ------- NDArray A created array. """ if isinstance(shape, int): shape = (shape, ) if ctx is None: ctx = current_context() if dtype is None: dtype = mx_real_t return NDArray(handle=_new_alloc_handle(shape, ctx, False, dtype)) # pylint: disable= redefined-builtin
Example #22
Source File: graphTools.py From graph-neural-networks with GNU General Public License v3.0 | 5 votes |
def permCoarsening(x, indices): # Original function written by M. Defferrard, found in # https://github.com/mdeff/cnn_graph/blob/master/lib/coarsening.py#L219 # Function name has been changed, and it has been further adapted to handle # multiple features as # number_data_points x number_features x number_nodes # instead of the original # number_data_points x number_nodes """ Permute data matrix, i.e. exchange node ids, so that binary unions form the clustering tree. """ if indices is None: return x B, F, N = x.shape Nnew = len(indices) assert Nnew >= N xnew = np.empty((B, F, Nnew)) for i,j in enumerate(indices): # Existing vertex, i.e. real data. if j < N: xnew[:,:,i] = x[:,:,j] # Fake vertex because of singeltons. # They will stay 0 so that max pooling chooses the singelton. # Or -infty ? else: xnew[:,:,i] = np.zeros([B, F]) return xnew
Example #23
Source File: Swaps.py From fullrmc with GNU Affero General Public License v3.0 | 5 votes |
def set_swap_length(self, swapLength): """ Set swap length. It will reset swaplist automatically. :Parameters: #. swapLength (Integer): The swap length that defines the length of the group and the length of the every swap sub-list in swapList. """ super(SwapPositionsGenerator, self).set_swap_length(swapLength=swapLength) self.__swapArray = np.empty( (self.swapLength,3), dtype=FLOAT_TYPE )
Example #24
Source File: test_masks.py From mmdetection with Apache License 2.0 | 5 votes |
def test_polygon_mask_flip(): # flip with empty polygon masks raw_masks = dummy_raw_polygon_masks((0, 28, 28)) polygon_masks = PolygonMasks(raw_masks, 28, 28) flipped_masks = polygon_masks.flip(flip_direction='horizontal') assert len(flipped_masks) == 0 assert flipped_masks.height == 28 assert flipped_masks.width == 28 assert flipped_masks.to_ndarray().shape == (0, 28, 28) # TODO: fixed flip correctness checking after v2.0_coord is merged # horizontally flip with polygon masks contain 3 instances raw_masks = dummy_raw_polygon_masks((3, 28, 28)) polygon_masks = PolygonMasks(raw_masks, 28, 28) flipped_masks = polygon_masks.flip(flip_direction='horizontal') flipped_flipped_masks = flipped_masks.flip(flip_direction='horizontal') assert len(flipped_masks) == 3 assert flipped_masks.height == 28 assert flipped_masks.width == 28 assert flipped_masks.to_ndarray().shape == (3, 28, 28) assert (polygon_masks.to_ndarray() == flipped_flipped_masks.to_ndarray() ).all() # vertically flip with polygon masks contain 3 instances raw_masks = dummy_raw_polygon_masks((3, 28, 28)) polygon_masks = PolygonMasks(raw_masks, 28, 28) flipped_masks = polygon_masks.flip(flip_direction='vertical') flipped_flipped_masks = flipped_masks.flip(flip_direction='vertical') assert len(flipped_masks) == 3 assert flipped_masks.height == 28 assert flipped_masks.width == 28 assert flipped_masks.to_ndarray().shape == (3, 28, 28) assert (polygon_masks.to_ndarray() == flipped_flipped_masks.to_ndarray() ).all()
Example #25
Source File: face_recognition_api.py From Face-Recognition with MIT License | 5 votes |
def face_distance(face_encodings, face_to_compare): """ Given a list of face encodings, compare them to a known face encoding and get a euclidean distance for each comparison face. The distance tells you how similar the faces are. :param faces: List of face encodings to compare :param face_to_compare: A face encoding to compare against :return: A numpy ndarray with the distance for each face in the same order as the 'faces' array """ if len(face_encodings) == 0: return np.empty((0)) return np.linalg.norm(face_encodings - face_to_compare, axis=1)
Example #26
Source File: Collection.py From fullrmc with GNU Affero General Public License v3.0 | 5 votes |
def set_data_keys(self, dataKeys): """ Set atoms collector data keys. keys can be set only once. This method will throw an error if used to reset dataKeys. :Parameters: #. dataKeys (list): The data keys list promised to store everytime an atom is removed from the system. """ assert not len(self.__dataKeys), LOGGER.error("resetting dataKeys is not allowed") assert isinstance(dataKeys, (list, set, tuple)), LOGGER.error("dataKeys must be a list") assert len(set(dataKeys))==len(dataKeys), LOGGER.error("Redundant keys in dataKeys list are found") assert len(dataKeys)>0, LOGGER.error("dataKeys must not be empty") self.__dataKeys = tuple(sorted(dataKeys))
Example #27
Source File: Collection.py From fullrmc with GNU Affero General Public License v3.0 | 5 votes |
def find_extrema(x, max = True, min = True, strict = False, withend = False): """ Get a vector extrema indexes and values. :Parameters: #. max (boolean): Whether to index the maxima. #. min (boolean): Whether to index the minima. #. strict (boolean): Whether not to index changes to zero gradient. #. withend (boolean): Whether to always include x[0] and x[-1]. :Returns: #. indexes (numpy.ndarray): Extrema indexes. #. values (numpy.ndarray): Extrema values. """ # This is the gradient dx = np.empty(len(x)) dx[1:] = np.diff(x) dx[0] = dx[1] # Clean up the gradient in order to pick out any change of sign dx = np.sign(dx) # define the threshold for whether to pick out changes to zero gradient threshold = 0 if strict: threshold = 1 # Second order diff to pick out the spikes d2x = np.diff(dx) if max and min: d2x = abs(d2x) elif max: d2x = -d2x # Take care of the two ends if withend: d2x[0] = 2 d2x[-1] = 2 # Sift out the list of extremas ind = np.nonzero(d2x > threshold)[0] return ind, x[ind]
Example #28
Source File: dataloader.py From models with MIT License | 5 votes |
def nans(shape, dtype=float): a = np.empty(shape, dtype) a.fill(np.nan) return a
Example #29
Source File: test_masks.py From mmdetection with Apache License 2.0 | 5 votes |
def test_polygon_mask_area(): # area of empty polygon masks raw_masks = dummy_raw_polygon_masks((0, 28, 28)) polygon_masks = PolygonMasks(raw_masks, 28, 28) assert polygon_masks.areas.sum() == 0 # area of polygon masks contain 1 instance # here we hack a case that the gap between the area of bitmap and polygon # is minor raw_masks = [[np.array([1, 1, 5, 1, 3, 4])]] polygon_masks = PolygonMasks(raw_masks, 6, 6) polygon_area = polygon_masks.areas bitmap_area = polygon_masks.to_bitmap().areas assert len(polygon_area) == 1 assert np.isclose(polygon_area, bitmap_area).all()
Example #30
Source File: test_masks.py From mmdetection with Apache License 2.0 | 5 votes |
def test_polygon_mask_crop(): dummy_bbox = np.array([0, 10, 10, 27], dtype=np.int) # crop with empty polygon masks raw_masks = dummy_raw_polygon_masks((0, 28, 28)) polygon_masks = PolygonMasks(raw_masks, 28, 28) cropped_masks = polygon_masks.crop(dummy_bbox) assert len(cropped_masks) == 0 assert cropped_masks.height == 17 assert cropped_masks.width == 10 assert cropped_masks.to_ndarray().shape == (0, 17, 10) # crop with polygon masks contain 1 instances raw_masks = [[np.array([1., 3., 5., 1., 5., 6., 1, 6])]] polygon_masks = PolygonMasks(raw_masks, 7, 7) bbox = np.array([0, 0, 3, 4]) cropped_masks = polygon_masks.crop(bbox) assert len(cropped_masks) == 1 assert cropped_masks.height == 4 assert cropped_masks.width == 3 assert cropped_masks.to_ndarray().shape == (1, 4, 3) truth = np.array([[0, 0, 0], [0, 0, 0], [0, 0, 1], [0, 1, 1]]) assert (cropped_masks.to_ndarray() == truth).all() # crop with invalid bbox with pytest.raises(AssertionError): dummy_bbox = dummy_bboxes(2, 28, 28) polygon_masks.crop(dummy_bbox)