"""Interface for Vis4D bounding box samplers."""from__future__importannotationsimportabcfromtypingimportNamedTupleimporttorchfromtorchimportTensor,nnfrom..matchersimportMatcher,MatchResult
[docs]classSamplingResult(NamedTuple):"""Sampling result class. Stores expected result tensors. sampled_box_indices (Tensor): Index of sampled boxes from input. sampled_target_indices (Tensor): Index of assigned target for each positive sampled box. sampled_labels (Tensor): {0, -1, 1} = {neg, ignore, pos}. """sampled_box_indices:Tensorsampled_target_indices:Tensorsampled_labels:Tensor
[docs]classSampler(nn.Module):"""Sampler base class."""def__init__(self,batch_size:int,positive_fraction:float)->None:"""Creates an instance of the class."""super().__init__()self.batch_size=batch_sizeself.positive_fraction=positive_fraction
[docs]@abc.abstractmethoddefforward(self,matching:MatchResult)->SamplingResult:"""Sample bounding boxes according to their struct."""raiseNotImplementedError
[docs]defmatch_and_sample_proposals(matcher:Matcher,sampler:Sampler,proposal_boxes:list[Tensor],target_boxes:list[Tensor],)->tuple[list[Tensor],list[Tensor],list[Tensor]]:"""Match proposals to targets and subsample. First, match the proposals to targets (ground truth labels) using the matcher. It is usually IoU matcher. The matching labels the proposals with positive or negative to show whether they are matched to an object. Second, the sampler will choose proposals based on certain criteria such as total proposal number and ratio of postives and negatives. """withtorch.no_grad():matchings=tuple(matcher(prop_box,tgt_box)forprop_box,tgt_boxinzip(proposal_boxes,target_boxes))sampling_results=tuple(sampler(matchs)formatchsinmatchings)return([s.sampled_box_indicesforsinsampling_results],[s.sampled_target_indicesforsinsampling_results],[s.sampled_labelsforsinsampling_results],)