Skip to content

How to select detections by index? #115

@lomnes-atlast-food

Description

@lomnes-atlast-food

Search before asking

  • I have searched the Supervision issues and found no similar feature requests.

Question

I'd like to get a single detection by index but the way I've found to do it seems a little clunky. Is there a cleaner way to do this?

For example:

detections = sv.Detections.from_sam(sam_annotations)
big_detections = detections[detections.area > 1000] # filters detections by area
gets_single_detection = detections[np.array([0])] # gets the first detection
gives_error = detectons[0] # could return the first detection but throws an error
gives_error = detectons[[0,1,2]] # could return the first detection but throws an error

Question: Is there a different intended way to access detections by index?

If not, you could update the __getitem__ method of the Detections dataclass to allow passing ints, or lists of ints instead of only allowing np.array objects.

Suggested modification:

    def __getitem__(self, index: np.ndarray) -> Detections:
        index = np.asarray(index) # ADDED
        if isinstance(index, np.ndarray) and (
            index.dtype == bool or index.dtype == int
        ):
            return Detections(
                xyxy=self.xyxy[index],
                mask=self.mask[index] if self.mask is not None else None,
                confidence=self.confidence[index]
                if self.confidence is not None
                else None,
                class_id=self.class_id[index] if self.class_id is not None else None,
                tracker_id=self.tracker_id[index]
                if self.tracker_id is not None
                else None,
            )
        raise TypeError(
            f"Detections.__getitem__ not supported for index of type {type(index)}."
        )

Additional

No response

Metadata

Metadata

Assignees

Labels

enhancementNew feature or requestversion: 0.9.0Feature to be added in `0.9.0` release

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions