This class stores the segmentation masks for all objects in one image, in the form of bitmaps. Attributes: tensor: bool Tensor of N,H,W, representing N instances in the image.
| 82 | |
| 83 | |
| 84 | class BitMasks: |
| 85 | """ |
| 86 | This class stores the segmentation masks for all objects in one image, in |
| 87 | the form of bitmaps. |
| 88 | |
| 89 | Attributes: |
| 90 | tensor: bool Tensor of N,H,W, representing N instances in the image. |
| 91 | """ |
| 92 | |
| 93 | def __init__(self, tensor: Union[torch.Tensor, np.ndarray]): |
| 94 | """ |
| 95 | Args: |
| 96 | tensor: bool Tensor of N,H,W, representing N instances in the image. |
| 97 | """ |
| 98 | device = tensor.device if isinstance(tensor, torch.Tensor) else torch.device("cpu") |
| 99 | tensor = torch.as_tensor(tensor, dtype=torch.bool, device=device) |
| 100 | assert tensor.dim() == 3, tensor.size() |
| 101 | self.image_size = tensor.shape[1:] |
| 102 | self.tensor = tensor |
| 103 | |
| 104 | def to(self, *args: Any, **kwargs: Any) -> "BitMasks": |
| 105 | return BitMasks(self.tensor.to(*args, **kwargs)) |
| 106 | |
| 107 | @property |
| 108 | def device(self) -> torch.device: |
| 109 | return self.tensor.device |
| 110 | |
| 111 | def __getitem__(self, item: Union[int, slice, torch.BoolTensor]) -> "BitMasks": |
| 112 | """ |
| 113 | Returns: |
| 114 | BitMasks: Create a new :class:`BitMasks` by indexing. |
| 115 | |
| 116 | The following usage are allowed: |
| 117 | |
| 118 | 1. `new_masks = masks[3]`: return a `BitMasks` which contains only one mask. |
| 119 | 2. `new_masks = masks[2:10]`: return a slice of masks. |
| 120 | 3. `new_masks = masks[vector]`, where vector is a torch.BoolTensor |
| 121 | with `length = len(masks)`. Nonzero elements in the vector will be selected. |
| 122 | |
| 123 | Note that the returned object might share storage with this object, |
| 124 | subject to Pytorch's indexing semantics. |
| 125 | """ |
| 126 | if isinstance(item, int): |
| 127 | return BitMasks(self.tensor[item].view(1, -1)) |
| 128 | m = self.tensor[item] |
| 129 | assert m.dim() == 3, "Indexing on BitMasks with {} returns a tensor with shape {}!".format( |
| 130 | item, m.shape |
| 131 | ) |
| 132 | return BitMasks(m) |
| 133 | |
| 134 | def __iter__(self) -> torch.Tensor: |
| 135 | yield from self.tensor |
| 136 | |
| 137 | def __repr__(self) -> str: |
| 138 | s = self.__class__.__name__ + "(" |
| 139 | s += "num_instances={})".format(len(self.tensor)) |
| 140 | return s |
| 141 |
no outgoing calls