Skip to content

Core

Classifications

Source code in supervision/classification/core.py
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
@dataclass
class Classifications:
    class_id: np.ndarray
    confidence: Optional[np.ndarray] = None

    def __post_init__(self) -> None:
        """
        Validate the classification inputs.
        """
        n = len(self.class_id)

        _validate_class_ids(self.class_id, n)
        _validate_confidence(self.confidence, n)

    def __len__(self) -> int:
        """
        Returns the number of classifications.
        """
        return len(self.class_id)

    @classmethod
    def from_clip(cls, clip_results) -> Classifications:
        """
        Creates a Classifications instance from a
        [clip](https://github.com/openai/clip) inference result.

        Args:
            clip_results (np.ndarray): The inference result from clip model.

        Returns:
            Classifications: A new Classifications object.

        Example:
            ```python
            from PIL import Image
            import clip
            import supervision as sv

            model, preprocess = clip.load('ViT-B/32')

            image = cv2.imread(SOURCE_IMAGE_PATH)
            image = preprocess(image).unsqueeze(0)

            text = clip.tokenize(["a diagram", "a dog", "a cat"])
            output, _ = model(image, text)
            classifications = sv.Classifications.from_clip(output)
            ```
        """

        confidence = clip_results.softmax(dim=-1).cpu().detach().numpy()[0]

        if len(confidence) == 0:
            return cls(class_id=np.array([]), confidence=np.array([]))

        class_ids = np.arange(len(confidence))
        return cls(class_id=class_ids, confidence=confidence)

    @classmethod
    def from_ultralytics(cls, ultralytics_results) -> Classifications:
        """
        Creates a Classifications instance from a
        [ultralytics](https://github.com/ultralytics/ultralytics) inference result.

        Args:
            ultralytics_results (ultralytics.engine.results.Results):
                The inference result from ultralytics model.

        Returns:
            Classifications: A new Classifications object.

        Example:
            ```python
            import cv2
            from ultralytics import YOLO
            import supervision as sv

            image = cv2.imread(SOURCE_IMAGE_PATH)
            model = YOLO('yolov8n-cls.pt')

            output = model(image)[0]
            classifications = sv.Classifications.from_ultralytics(output)
            ```
        """
        confidence = ultralytics_results.probs.data.cpu().numpy()
        return cls(class_id=np.arange(confidence.shape[0]), confidence=confidence)

    @classmethod
    def from_timm(cls, timm_results) -> Classifications:
        """
        Creates a Classifications instance from a
        [timm](https://huggingface.co/docs/hub/timm) inference result.

        Args:
            timm_results: The inference result from timm model.

        Returns:
            Classifications: A new Classifications object.

        Example:
            ```python
            from PIL import Image
            import timm
            from timm.data import resolve_data_config, create_transform
            import supervision as sv

            model = timm.create_model(
                model_name='hf-hub:nateraw/resnet50-oxford-iiit-pet',
                pretrained=True
            ).eval()

            config = resolve_data_config({}, model=model)
            transform = create_transform(**config)

            image = Image.open(SOURCE_IMAGE_PATH).convert('RGB')
            x = transform(image).unsqueeze(0)

            output = model(x)

            classifications = sv.Classifications.from_timm(output)
            ```
        """
        confidence = timm_results.cpu().detach().numpy()[0]

        if len(confidence) == 0:
            return cls(class_id=np.array([]), confidence=np.array([]))

        class_id = np.arange(len(confidence))
        return cls(class_id=class_id, confidence=confidence)

    def get_top_k(self, k: int) -> Tuple[np.ndarray, np.ndarray]:
        """
        Retrieve the top k class IDs and confidences,
            ordered in descending order by confidence.

        Args:
            k (int): The number of top class IDs and confidences to retrieve.

        Returns:
            Tuple[np.ndarray, np.ndarray]: A tuple containing
                the top k class IDs and confidences.

        Example:
            ```python
            import supervision as sv

            classifications = sv.Classifications(...)

            classifications.get_top_k(1)

            (array([1]), array([0.9]))
            ```
        """
        if self.confidence is None:
            raise ValueError("top_k could not be calculated, confidence is None")

        order = np.argsort(self.confidence)[::-1]
        top_k_order = order[:k]
        top_k_class_id = self.class_id[top_k_order]
        top_k_confidence = self.confidence[top_k_order]

        return top_k_class_id, top_k_confidence

__len__()

Returns the number of classifications.

Source code in supervision/classification/core.py
42
43
44
45
46
def __len__(self) -> int:
    """
    Returns the number of classifications.
    """
    return len(self.class_id)

__post_init__()

Validate the classification inputs.

Source code in supervision/classification/core.py
33
34
35
36
37
38
39
40
def __post_init__(self) -> None:
    """
    Validate the classification inputs.
    """
    n = len(self.class_id)

    _validate_class_ids(self.class_id, n)
    _validate_confidence(self.confidence, n)

from_clip(clip_results) classmethod

Creates a Classifications instance from a clip inference result.

Parameters:

Name Type Description Default
clip_results ndarray

The inference result from clip model.

required

Returns:

Name Type Description
Classifications Classifications

A new Classifications object.

Example
from PIL import Image
import clip
import supervision as sv

model, preprocess = clip.load('ViT-B/32')

image = cv2.imread(SOURCE_IMAGE_PATH)
image = preprocess(image).unsqueeze(0)

text = clip.tokenize(["a diagram", "a dog", "a cat"])
output, _ = model(image, text)
classifications = sv.Classifications.from_clip(output)
Source code in supervision/classification/core.py
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
@classmethod
def from_clip(cls, clip_results) -> Classifications:
    """
    Creates a Classifications instance from a
    [clip](https://github.com/openai/clip) inference result.

    Args:
        clip_results (np.ndarray): The inference result from clip model.

    Returns:
        Classifications: A new Classifications object.

    Example:
        ```python
        from PIL import Image
        import clip
        import supervision as sv

        model, preprocess = clip.load('ViT-B/32')

        image = cv2.imread(SOURCE_IMAGE_PATH)
        image = preprocess(image).unsqueeze(0)

        text = clip.tokenize(["a diagram", "a dog", "a cat"])
        output, _ = model(image, text)
        classifications = sv.Classifications.from_clip(output)
        ```
    """

    confidence = clip_results.softmax(dim=-1).cpu().detach().numpy()[0]

    if len(confidence) == 0:
        return cls(class_id=np.array([]), confidence=np.array([]))

    class_ids = np.arange(len(confidence))
    return cls(class_id=class_ids, confidence=confidence)

from_timm(timm_results) classmethod

Creates a Classifications instance from a timm inference result.

Parameters:

Name Type Description Default
timm_results

The inference result from timm model.

required

Returns:

Name Type Description
Classifications Classifications

A new Classifications object.

Example
from PIL import Image
import timm
from timm.data import resolve_data_config, create_transform
import supervision as sv

model = timm.create_model(
    model_name='hf-hub:nateraw/resnet50-oxford-iiit-pet',
    pretrained=True
).eval()

config = resolve_data_config({}, model=model)
transform = create_transform(**config)

image = Image.open(SOURCE_IMAGE_PATH).convert('RGB')
x = transform(image).unsqueeze(0)

output = model(x)

classifications = sv.Classifications.from_timm(output)
Source code in supervision/classification/core.py
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
@classmethod
def from_timm(cls, timm_results) -> Classifications:
    """
    Creates a Classifications instance from a
    [timm](https://huggingface.co/docs/hub/timm) inference result.

    Args:
        timm_results: The inference result from timm model.

    Returns:
        Classifications: A new Classifications object.

    Example:
        ```python
        from PIL import Image
        import timm
        from timm.data import resolve_data_config, create_transform
        import supervision as sv

        model = timm.create_model(
            model_name='hf-hub:nateraw/resnet50-oxford-iiit-pet',
            pretrained=True
        ).eval()

        config = resolve_data_config({}, model=model)
        transform = create_transform(**config)

        image = Image.open(SOURCE_IMAGE_PATH).convert('RGB')
        x = transform(image).unsqueeze(0)

        output = model(x)

        classifications = sv.Classifications.from_timm(output)
        ```
    """
    confidence = timm_results.cpu().detach().numpy()[0]

    if len(confidence) == 0:
        return cls(class_id=np.array([]), confidence=np.array([]))

    class_id = np.arange(len(confidence))
    return cls(class_id=class_id, confidence=confidence)

from_ultralytics(ultralytics_results) classmethod

Creates a Classifications instance from a ultralytics inference result.

Parameters:

Name Type Description Default
ultralytics_results Results

The inference result from ultralytics model.

required

Returns:

Name Type Description
Classifications Classifications

A new Classifications object.

Example
import cv2
from ultralytics import YOLO
import supervision as sv

image = cv2.imread(SOURCE_IMAGE_PATH)
model = YOLO('yolov8n-cls.pt')

output = model(image)[0]
classifications = sv.Classifications.from_ultralytics(output)
Source code in supervision/classification/core.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
@classmethod
def from_ultralytics(cls, ultralytics_results) -> Classifications:
    """
    Creates a Classifications instance from a
    [ultralytics](https://github.com/ultralytics/ultralytics) inference result.

    Args:
        ultralytics_results (ultralytics.engine.results.Results):
            The inference result from ultralytics model.

    Returns:
        Classifications: A new Classifications object.

    Example:
        ```python
        import cv2
        from ultralytics import YOLO
        import supervision as sv

        image = cv2.imread(SOURCE_IMAGE_PATH)
        model = YOLO('yolov8n-cls.pt')

        output = model(image)[0]
        classifications = sv.Classifications.from_ultralytics(output)
        ```
    """
    confidence = ultralytics_results.probs.data.cpu().numpy()
    return cls(class_id=np.arange(confidence.shape[0]), confidence=confidence)

get_top_k(k)

Retrieve the top k class IDs and confidences, ordered in descending order by confidence.

Parameters:

Name Type Description Default
k int

The number of top class IDs and confidences to retrieve.

required

Returns:

Type Description
Tuple[ndarray, ndarray]

Tuple[np.ndarray, np.ndarray]: A tuple containing the top k class IDs and confidences.

Example
import supervision as sv

classifications = sv.Classifications(...)

classifications.get_top_k(1)

(array([1]), array([0.9]))
Source code in supervision/classification/core.py
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
def get_top_k(self, k: int) -> Tuple[np.ndarray, np.ndarray]:
    """
    Retrieve the top k class IDs and confidences,
        ordered in descending order by confidence.

    Args:
        k (int): The number of top class IDs and confidences to retrieve.

    Returns:
        Tuple[np.ndarray, np.ndarray]: A tuple containing
            the top k class IDs and confidences.

    Example:
        ```python
        import supervision as sv

        classifications = sv.Classifications(...)

        classifications.get_top_k(1)

        (array([1]), array([0.9]))
        ```
    """
    if self.confidence is None:
        raise ValueError("top_k could not be calculated, confidence is None")

    order = np.argsort(self.confidence)[::-1]
    top_k_order = order[:k]
    top_k_class_id = self.class_id[top_k_order]
    top_k_confidence = self.confidence[top_k_order]

    return top_k_class_id, top_k_confidence

Comments