diff --git a/src/supervision/annotators/core.py b/src/supervision/annotators/core.py index 38c2957e..af844099 100644 --- a/src/supervision/annotators/core.py +++ b/src/supervision/annotators/core.py @@ -201,6 +201,7 @@ class BoxAnnotator(BaseAnnotator): or `PIL.Image.Image`) Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> image = np.zeros((100, 100, 3), dtype=np.uint8) @@ -214,6 +215,8 @@ class BoxAnnotator(BaseAnnotator): ... detections=detections ... ) + ``` + ![bounding-box-annotator-example](https://media.roboflow.com/ supervision-annotator-examples/bounding-box-annotator-example-purple.png) """ @@ -376,6 +379,7 @@ class MaskAnnotator(BaseAnnotator): or `PIL.Image.Image`) Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> image = np.zeros((100, 100, 3), dtype=np.uint8) @@ -390,6 +394,8 @@ class MaskAnnotator(BaseAnnotator): ... detections=detections ... ) + ``` + ![mask-annotator-example](https://media.roboflow.com/ supervision-annotator-examples/mask-annotator-example-purple.png) """ @@ -468,6 +474,7 @@ class PolygonAnnotator(BaseAnnotator): or `PIL.Image.Image`) Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> image = np.zeros((100, 100, 3), dtype=np.uint8) @@ -481,6 +488,8 @@ class PolygonAnnotator(BaseAnnotator): ... detections=detections ... ) + ``` + ![polygon-annotator-example](https://media.roboflow.com/ supervision-annotator-examples/polygon-annotator-example-purple.png) """ @@ -556,6 +565,7 @@ class ColorAnnotator(BaseAnnotator): or `PIL.Image.Image`) Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> image = np.zeros((100, 100, 3), dtype=np.uint8) @@ -569,6 +579,8 @@ class ColorAnnotator(BaseAnnotator): ... detections=detections ... ) + ``` + ![box-mask-annotator-example](https://media.roboflow.com/ supervision-annotator-examples/box-mask-annotator-example-purple.png) """ @@ -653,6 +665,7 @@ class HaloAnnotator(BaseAnnotator): or `PIL.Image.Image`) Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> image = np.zeros((100, 100, 3), dtype=np.uint8) @@ -666,6 +679,8 @@ class HaloAnnotator(BaseAnnotator): ... detections=detections ... ) + ``` + ![halo-annotator-example](https://media.roboflow.com/ supervision-annotator-examples/halo-annotator-example-purple.png) """ @@ -754,6 +769,7 @@ class EllipseAnnotator(BaseAnnotator): or `PIL.Image.Image`) Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> image = np.zeros((100, 100, 3), dtype=np.uint8) @@ -767,6 +783,8 @@ class EllipseAnnotator(BaseAnnotator): ... detections=detections ... ) + ``` + ![ellipse-annotator-example](https://media.roboflow.com/ supervision-annotator-examples/ellipse-annotator-example-purple.png) """ @@ -847,6 +865,7 @@ class BoxCornerAnnotator(BaseAnnotator): or `PIL.Image.Image`) Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> image = np.zeros((100, 100, 3), dtype=np.uint8) @@ -860,6 +879,8 @@ class BoxCornerAnnotator(BaseAnnotator): ... detections=detections ... ) + ``` + ![box-corner-annotator-example](https://media.roboflow.com/ supervision-annotator-examples/box-corner-annotator-example-purple.png) """ @@ -937,6 +958,7 @@ class CircleAnnotator(BaseAnnotator): or `PIL.Image.Image`) Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> image = np.zeros((100, 100, 3), dtype=np.uint8) @@ -950,6 +972,8 @@ class CircleAnnotator(BaseAnnotator): ... detections=detections ... ) + ``` + ![circle-annotator-example](https://media.roboflow.com/ supervision-annotator-examples/circle-annotator-example-purple.png) @@ -1037,6 +1061,7 @@ class DotAnnotator(BaseAnnotator): or `PIL.Image.Image`) Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> image = np.zeros((100, 100, 3), dtype=np.uint8) @@ -1050,6 +1075,8 @@ class DotAnnotator(BaseAnnotator): ... detections=detections ... ) + ``` + ![dot-annotator-example](https://media.roboflow.com/ supervision-annotator-examples/dot-annotator-example-purple.png) """ @@ -1166,6 +1193,7 @@ class LabelAnnotator(_BaseLabelAnnotator): or `PIL.Image.Image`) Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> image = np.zeros((100, 100, 3), dtype=np.uint8) @@ -1187,6 +1215,8 @@ class LabelAnnotator(_BaseLabelAnnotator): ... labels=labels ... ) + ``` + ![label-annotator-example](https://media.roboflow.com/ supervision-annotator-examples/label-annotator-example-purple.png) """ @@ -1481,6 +1511,7 @@ class RichLabelAnnotator(_BaseLabelAnnotator): or `PIL.Image.Image`) Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> from PIL import Image @@ -1502,6 +1533,8 @@ class RichLabelAnnotator(_BaseLabelAnnotator): ... detections=detections, ... labels=labels ... ) + + ``` """ assert isinstance(scene, Image.Image) validate_labels(labels, detections) @@ -1805,6 +1838,7 @@ class BlurAnnotator(BaseAnnotator): or `PIL.Image.Image`) Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> image = np.zeros((100, 100, 3), dtype=np.uint8) @@ -1818,6 +1852,8 @@ class BlurAnnotator(BaseAnnotator): ... detections=detections ... ) + ``` + ![blur-annotator-example](https://media.roboflow.com/ supervision-annotator-examples/blur-annotator-example-purple.png) """ @@ -2207,6 +2243,7 @@ class TriangleAnnotator(BaseAnnotator): or `PIL.Image.Image`) Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> image = np.zeros((100, 100, 3), dtype=np.uint8) @@ -2220,6 +2257,8 @@ class TriangleAnnotator(BaseAnnotator): ... detections=detections ... ) + ``` + ![triangle-annotator-example](https://media.roboflow.com/ supervision-annotator-examples/triangle-annotator-example.png) """ @@ -2321,6 +2360,7 @@ class RoundBoxAnnotator(BaseAnnotator): or `PIL.Image.Image`) Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> image = np.zeros((100, 100, 3), dtype=np.uint8) @@ -2334,6 +2374,8 @@ class RoundBoxAnnotator(BaseAnnotator): ... detections=detections ... ) + ``` + ![round-box-annotator-example](https://media.roboflow.com/ supervision-annotator-examples/round-box-annotator-example-purple.png) """ @@ -2469,6 +2511,7 @@ class PercentageBarAnnotator(BaseAnnotator): or `PIL.Image.Image`) Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> image = np.zeros((100, 100, 3), dtype=np.uint8) @@ -2483,6 +2526,8 @@ class PercentageBarAnnotator(BaseAnnotator): ... detections=detections ... ) + ``` + ![percentage-bar-example](https://media.roboflow.com/ supervision-annotator-examples/percentage-bar-annotator-example-purple.png) """ @@ -2648,6 +2693,7 @@ class CropAnnotator(BaseAnnotator): The annotated image. Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> image = np.zeros((100, 100, 3), dtype=np.uint8) @@ -2661,6 +2707,8 @@ class CropAnnotator(BaseAnnotator): ... detections=detections ... ) + ``` + ![crop-annotator-example](https://media.roboflow.com/ supervision-annotator-examples/crop-annotator-example.png) """ @@ -2790,6 +2838,7 @@ class BackgroundOverlayAnnotator(BaseAnnotator): or `PIL.Image.Image`) Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> image = np.zeros((100, 100, 3), dtype=np.uint8) @@ -2803,6 +2852,8 @@ class BackgroundOverlayAnnotator(BaseAnnotator): ... detections=detections ... ) + ``` + ![background-overlay-annotator-example](https://media.roboflow.com/ supervision-annotator-examples/background-color-annotator-example-purple.png) """ diff --git a/src/supervision/annotators/utils.py b/src/supervision/annotators/utils.py index 7fc5bfad..6bb6417b 100644 --- a/src/supervision/annotators/utils.py +++ b/src/supervision/annotators/utils.py @@ -273,10 +273,9 @@ def snap_boxes( A numpy array of shape `(N, 4)` with boxes shifted into frame. Examples: + ```pycon >>> import numpy as np >>> from supervision.annotators.utils import snap_boxes - - Example boxes: >>> xyxy = np.array([ ... [-10, 10, 30, 50], # Off left edge ... [310, 200, 350, 250], # Off right edge @@ -294,6 +293,8 @@ def snap_boxes( [200., 190., 250., 240.], [ 0., 10., 370., 50.], [ 10., 0., 30., 280.]], dtype=float32) + + ``` """ result = np.copy(xyxy) width, height = resolution_wh diff --git a/src/supervision/assets/downloader.py b/src/supervision/assets/downloader.py index d507b643..e535a95a 100644 --- a/src/supervision/assets/downloader.py +++ b/src/supervision/assets/downloader.py @@ -46,9 +46,12 @@ def download_assets(asset_name: VideoAssets | str) -> str: The filename of the downloaded asset. Example: + ```pycon >>> from supervision.assets import download_assets, VideoAssets >>> download_assets(VideoAssets.VEHICLES) # doctest: +SKIP 'vehicles.mp4' + + ``` """ filename = asset_name.value if isinstance(asset_name, VideoAssets) else asset_name diff --git a/src/supervision/classification/core.py b/src/supervision/classification/core.py index 86703b2f..32f38722 100644 --- a/src/supervision/classification/core.py +++ b/src/supervision/classification/core.py @@ -167,6 +167,7 @@ class Classifications: the top k class IDs and confidences. Example: + ```pycon >>> import numpy as np >>> import supervision as sv >>> classifications = sv.Classifications( @@ -175,6 +176,8 @@ class 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") diff --git a/src/supervision/dataset/core.py b/src/supervision/dataset/core.py index d901195a..f0b3d339 100644 --- a/src/supervision/dataset/core.py +++ b/src/supervision/dataset/core.py @@ -165,6 +165,7 @@ class DetectionDataset(BaseDataset): the training and testing datasets. Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> ds = sv.DetectionDataset( @@ -181,6 +182,8 @@ class DetectionDataset(BaseDataset): >>> train_ds, test_ds = ds.split(split_ratio=0.5, random_state=42) >>> len(train_ds), len(test_ds) (1, 1) + + ``` """ train_paths, test_paths = train_test_split( @@ -232,6 +235,7 @@ class DetectionDataset(BaseDataset): the merged data from the input list. Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> ds_1 = sv.DetectionDataset( @@ -257,6 +261,8 @@ class DetectionDataset(BaseDataset): 2 >>> ds_merged.classes ['cat', 'dog', 'person'] + + ``` """ def is_in_memory(dataset: DetectionDataset) -> bool: @@ -760,6 +766,7 @@ class ClassificationDataset(BaseDataset): the training and testing datasets. Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> cd = sv.ClassificationDataset( @@ -776,6 +783,8 @@ class ClassificationDataset(BaseDataset): >>> train_cd, test_cd = cd.split(split_ratio=0.5, random_state=42) >>> len(train_cd), len(test_cd) (1, 1) + + ``` """ train_paths, test_paths = train_test_split( data=self.image_paths, diff --git a/src/supervision/dataset/utils.py b/src/supervision/dataset/utils.py index 8cf4682f..37d9bf91 100644 --- a/src/supervision/dataset/utils.py +++ b/src/supervision/dataset/utils.py @@ -163,6 +163,7 @@ def rle_to_mask( number of pixels in the expected mask (computed based on resolution_wh). Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> mask = sv.rle_to_mask([5, 2, 2, 2, 5], (4, 4)) @@ -171,6 +172,8 @@ def rle_to_mask( [0, 1, 1, 0], [0, 1, 1, 0], [0, 0, 0, 0]], dtype=uint8) + + ``` """ if isinstance(rle, list): rle = np.array(rle, dtype=int) @@ -210,6 +213,7 @@ def mask_to_rle(mask: npt.NDArray[np.bool_]) -> list[int]: AssertionError: If input mask is not 2D or is empty. Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> mask = np.array([ @@ -222,6 +226,9 @@ def mask_to_rle(mask: npt.NDArray[np.bool_]) -> list[int]: >>> [int(x) for x in rle] [0, 16] + ``` + + ```pycon >>> import numpy as np >>> import supervision as sv >>> mask = np.array([ @@ -234,6 +241,8 @@ def mask_to_rle(mask: npt.NDArray[np.bool_]) -> list[int]: >>> [int(x) for x in rle] [5, 2, 2, 2, 5] + ``` + ![mask_to_rle](https://media.roboflow.com/supervision-docs/ mask-to-rle.png){ align=center width="800" } """ diff --git a/src/supervision/detection/tools/csv_sink.py b/src/supervision/detection/tools/csv_sink.py index a81899f5..d8be7d73 100644 --- a/src/supervision/detection/tools/csv_sink.py +++ b/src/supervision/detection/tools/csv_sink.py @@ -34,6 +34,7 @@ class CSVSink: Defaults to 'output.csv'. Example: + ```pycon >>> import supervision as sv >>> import numpy as np >>> import tempfile @@ -53,6 +54,8 @@ class CSVSink: >>> with csv_sink as sink: ... sink.append(detections, custom_data={'frame': 0}) >>> os.unlink(temp_file.name) # Clean up + + ``` """ def __init__(self, file_name: str = "output.csv") -> None: diff --git a/src/supervision/detection/tools/smoother.py b/src/supervision/detection/tools/smoother.py index bab98305..32d80e59 100644 --- a/src/supervision/detection/tools/smoother.py +++ b/src/supervision/detection/tools/smoother.py @@ -30,6 +30,7 @@ class DetectionsSmoother: - This class is not compatible with segmentation models. Example: + ```pycon >>> import numpy as np >>> import supervision as sv >>> smoother = sv.DetectionsSmoother(length=3) @@ -52,6 +53,8 @@ class DetectionsSmoother: >>> smoothed.confidence array([0.6]) + ``` + ```python import supervision as sv diff --git a/src/supervision/detection/utils/boxes.py b/src/supervision/detection/utils/boxes.py index af0bccf5..c736adbb 100644 --- a/src/supervision/detection/utils/boxes.py +++ b/src/supervision/detection/utils/boxes.py @@ -23,6 +23,7 @@ def clip_boxes(xyxy: np.ndarray, resolution_wh: tuple[int, int]) -> np.ndarray: within the frame resolution. Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> xyxy = np.array([ @@ -34,6 +35,8 @@ def clip_boxes(xyxy: np.ndarray, resolution_wh: tuple[int, int]) -> np.ndarray: array([[ 10, 20, 300, 200], [ 15, 25, 320, 240], [ 0, 0, 30, 40]]) + + ``` """ result = np.copy(xyxy) width, height = resolution_wh @@ -62,6 +65,7 @@ def pad_boxes(xyxy: np.ndarray, px: int, py: int | None = None) -> np.ndarray: values. Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> xyxy = np.array([ @@ -71,6 +75,8 @@ def pad_boxes(xyxy: np.ndarray, px: int, py: int | None = None) -> np.ndarray: >>> sv.pad_boxes(xyxy=xyxy, px=5, py=10) array([[ 5, 10, 35, 50], [10, 15, 40, 55]]) + + ``` """ if py is None: py = px @@ -107,6 +113,7 @@ def denormalize_boxes( `(x_min, y_min, x_max, y_max)` format. Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> xyxy = np.array([ @@ -119,11 +126,16 @@ def denormalize_boxes( [384., 288., 896., 576.], [256., 72., 768., 360.]]) + ``` + + ```pycon >>> xyxy = np.array([ ... [256., 128., 768., 640.] ... ]) >>> sv.denormalize_boxes(xyxy, (1280, 720), normalization_factor=1024.0) array([[320., 90., 960., 450.]]) + + ``` """ width, height = resolution_wh result = xyxy.copy() @@ -148,6 +160,7 @@ def move_boxes( Repositioned bounding boxes. Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> xyxy = np.array([ @@ -158,6 +171,8 @@ def move_boxes( >>> sv.move_boxes(xyxy=xyxy, offset=offset) array([[15, 15, 25, 25], [35, 35, 45, 45]]) + + ``` """ return xyxy + np.hstack([offset, offset]) @@ -177,6 +192,7 @@ def move_oriented_boxes( Repositioned bounding boxes. Examples: + ```pycon >>> import numpy as np >>> from supervision.detection.utils.boxes import move_oriented_boxes >>> xyxyxyxy = np.array([ @@ -204,6 +220,8 @@ def move_oriented_boxes( [25, 45], [35, 55], [45, 45]]]) + + ``` """ return xyxyxyxy + offset @@ -225,6 +243,7 @@ def scale_boxes( Scaled bounding boxes. Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> xyxy = np.array([ @@ -234,6 +253,8 @@ def scale_boxes( >>> sv.scale_boxes(xyxy=xyxy, factor=1.5) array([[ 7.5, 7.5, 22.5, 22.5], [27.5, 27.5, 42.5, 42.5]]) + + ``` """ centers = (xyxy[:, :2] + xyxy[:, 2:]) / 2 new_sizes = (xyxy[:, 2:] - xyxy[:, :2]) * factor @@ -252,6 +273,7 @@ def spread_out_boxes( max_iterations: Maximum number of iterations to run the algorithm for. Example: + ```pycon >>> import numpy as np >>> from supervision.detection.utils.boxes import spread_out_boxes >>> xyxy = np.array([ @@ -264,6 +286,8 @@ def spread_out_boxes( True >>> bool(spread_out[1, 0] > 12 and spread_out[1, 1] > 12) True + + ``` """ if len(xyxy) == 0: return xyxy diff --git a/src/supervision/detection/utils/converters.py b/src/supervision/detection/utils/converters.py index ad051293..cc886cff 100644 --- a/src/supervision/detection/utils/converters.py +++ b/src/supervision/detection/utils/converters.py @@ -55,6 +55,7 @@ def xywh_to_xyxy(xywh: np.ndarray) -> np.ndarray: to a bounding box in the format `(x_min, y_min, x_max, y_max)`. Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> xywh = np.array([ @@ -64,6 +65,8 @@ def xywh_to_xyxy(xywh: np.ndarray) -> np.ndarray: >>> sv.xywh_to_xyxy(xywh=xywh) array([[10, 20, 40, 60], [15, 25, 50, 70]]) + + ``` """ xyxy = xywh.copy() xyxy[:, 2] = xywh[:, 0] + xywh[:, 2] @@ -86,6 +89,7 @@ def xyxy_to_xywh(xyxy: np.ndarray) -> np.ndarray: to a bounding box in the format `(x, y, width, height)`. Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> xyxy = np.array([ @@ -95,6 +99,8 @@ def xyxy_to_xywh(xyxy: np.ndarray) -> np.ndarray: >>> sv.xyxy_to_xywh(xyxy=xyxy) array([[10, 20, 30, 40], [15, 25, 35, 45]]) + + ``` """ xywh = xyxy.copy() xywh[:, 2] = xyxy[:, 2] - xyxy[:, 0] @@ -117,6 +123,7 @@ def xcycwh_to_xyxy(xcycwh: np.ndarray) -> np.ndarray: to a bounding box in the format `(x_min, y_min, x_max, y_max)`. Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> xcycwh = np.array([ @@ -126,6 +133,8 @@ def xcycwh_to_xyxy(xcycwh: np.ndarray) -> np.ndarray: >>> sv.xcycwh_to_xyxy(xcycwh=xcycwh) array([[40. , 35. , 60. , 65. ], [25. , 32.5, 35. , 47.5]]) + + ``` """ xyxy = xcycwh.copy() xyxy[:, 0] = xcycwh[:, 0] - xcycwh[:, 2] / 2 @@ -149,6 +158,7 @@ def xyxy_to_xcycarh(xyxy: np.ndarray) -> np.ndarray: `(center x, center y, aspect ratio, height)`. Shape `(N, 4)`. Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> xyxy = np.array([ @@ -159,6 +169,8 @@ def xyxy_to_xcycarh(xyxy: np.ndarray) -> np.ndarray: array([[25. , 40. , 0.75 , 40. ], [32.5 , 47.5 , 0.77..., 45. ]]) + ``` + """ if xyxy.size == 0: return np.empty((0, 4), dtype=float) @@ -219,6 +231,7 @@ def xyxy_to_mask(boxes: np.ndarray, resolution_wh: tuple[int, int]) -> np.ndarra for each bounding box. Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> boxes = np.array([[0, 0, 2, 2]]) @@ -241,6 +254,8 @@ def xyxy_to_mask(boxes: np.ndarray, resolution_wh: tuple[int, int]) -> np.ndarra [False, False, False, False, False], [False, False, False, True, True], [False, False, False, True, True]]]) + + ``` """ width, height = resolution_wh n = boxes.shape[0] diff --git a/src/supervision/detection/utils/iou_and_nms.py b/src/supervision/detection/utils/iou_and_nms.py index 6e1b4ded..36ef0e35 100644 --- a/src/supervision/detection/utils/iou_and_nms.py +++ b/src/supervision/detection/utils/iou_and_nms.py @@ -111,6 +111,7 @@ def box_iou( ValueError: If `overlap_metric` is not IOU or IOS. Examples: + ```pycon >>> import supervision as sv >>> box_true = [100, 100, 200, 200] >>> box_detection = [150, 150, 250, 250] @@ -118,6 +119,8 @@ def box_iou( 0.142857... >>> sv.box_iou(box_true, box_detection, overlap_metric=sv.OverlapMetric.IOS) 0.25 + + ``` """ overlap_metric = OverlapMetric.from_value(overlap_metric) x_min_true, y_min_true, x_max_true, y_max_true = np.array(box_true) @@ -184,6 +187,7 @@ def box_iou_batch( ValueError: If `overlap_metric` is not IOU or IOS. Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> boxes_true = np.array([ @@ -204,6 +208,8 @@ def box_iou_batch( ... ) array([[0.25, 0. ], [0. , 0.64]], dtype=float32) + + ``` """ overlap_metric = OverlapMetric.from_value(overlap_metric) x_min_true, y_min_true, x_max_true, y_max_true = boxes_true.T @@ -311,6 +317,7 @@ def box_iou_batch_with_jaccard( np.ndarray: Array of IoU values of shape (len(dt), len(gt)). Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> boxes_true = [ @@ -330,6 +337,8 @@ def box_iou_batch_with_jaccard( >>> ious # doctest: +ELLIPSIS array([[0.886..., 0.496...], [0.4 ..., 0.862...]]) + + ``` """ assert len(is_crowd) == len(boxes_true), ( "`is_crowd` must have the same length as `boxes_true`" diff --git a/src/supervision/detection/utils/masks.py b/src/supervision/detection/utils/masks.py index 9b4193ed..a03bb2bf 100644 --- a/src/supervision/detection/utils/masks.py +++ b/src/supervision/detection/utils/masks.py @@ -30,6 +30,7 @@ def move_masks( shape. Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> mask = np.array([[[False, False, False, False], @@ -48,6 +49,8 @@ def move_masks( [False, False, False, False], [False, False, False, False], [ True, False, False, False]]]) + + ``` """ mask_array = np.full((masks.shape[0], resolution_wh[1], resolution_wh[0]), False) @@ -126,6 +129,7 @@ def contains_holes(mask: npt.NDArray[np.bool_]) -> bool: True if holes are detected, False otherwise. Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> mask = np.array([ @@ -147,6 +151,8 @@ def contains_holes(mask: npt.NDArray[np.bool_]) -> bool: >>> sv.contains_holes(mask=mask) False + ``` + ![contains_holes](https://media.roboflow.com/supervision-docs/contains-holes.png){ align=center width="800" } """ # noqa E501 // docs mask_uint8 = mask.astype(np.uint8) @@ -182,6 +188,7 @@ def contains_multiple_segments( ValueError: If connectivity(int) parameter value is not 4 or 8. Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> mask = np.array([ @@ -205,6 +212,8 @@ def contains_multiple_segments( >>> sv.contains_multiple_segments(mask=mask, connectivity=4) False + ``` + ![contains_multiple_segments](https://media.roboflow.com/supervision-docs/contains-multiple-segments.png){ align=center width="800" } """ # noqa E501 // docs if connectivity != 4 and connectivity != 8: @@ -287,6 +296,7 @@ def filter_segments_by_distance( Boolean mask after filtering. Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> mask = np.array([ @@ -322,6 +332,8 @@ def filter_segments_by_distance( [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]) + ``` + The nearby 2×2 block at columns 6–7 is kept because its edge distance is within 3 pixels. The distant block at columns 9-10 is removed. """ # noqa E501 // docs diff --git a/src/supervision/detection/utils/vlms.py b/src/supervision/detection/utils/vlms.py index d48a360e..ccc32205 100644 --- a/src/supervision/detection/utils/vlms.py +++ b/src/supervision/detection/utils/vlms.py @@ -18,6 +18,7 @@ def edit_distance(string_1: str, string_2: str, case_sensitive: bool = True) -> into `string_2`. Examples: + ```pycon >>> import supervision as sv >>> sv.edit_distance("hello", "hello") 0 @@ -31,6 +32,8 @@ def edit_distance(string_1: str, string_2: str, case_sensitive: bool = True) -> 0 >>> sv.edit_distance("hello world", "helloworld") 1 + + ``` """ if not case_sensitive: string_1 = string_1.lower() @@ -80,6 +83,7 @@ def fuzzy_match_index( or None if no match is found. Examples: + ```pycon >>> from supervision.detection.utils.vlms import fuzzy_match_index >>> fuzzy_match_index(["cat", "dog", "rat"], "dat", threshold=1) 0 @@ -87,6 +91,8 @@ def fuzzy_match_index( 1 >>> fuzzy_match_index(["one", "two", "three"], "xyz", threshold=2) is None True + + ``` """ for idx, candidate in enumerate(candidates): if edit_distance(candidate, query, case_sensitive=case_sensitive) <= threshold: diff --git a/src/supervision/draw/color.py b/src/supervision/draw/color.py index 008a3839..9ed448e3 100644 --- a/src/supervision/draw/color.py +++ b/src/supervision/draw/color.py @@ -76,10 +76,13 @@ class Color: b (int): Blue channel value (0-255). Example: + ```pycon >>> import supervision as sv >>> sv.Color.WHITE Color(r=255, g=255, b=255) + ``` + | Constant | Hex Code | RGB | |------------|------------|-------------------| | `WHITE` | `#FFFFFF` | `(255, 255, 255)` | @@ -111,11 +114,14 @@ class Color: Color: An instance representing the color. Example: + ```pycon >>> import supervision as sv >>> sv.Color.from_hex('#ff00ff') Color(r=255, g=0, b=255) >>> sv.Color.from_hex('#f0f') Color(r=255, g=0, b=255) + + ``` """ _validate_color_hex(color_hex) color_hex = color_hex.lstrip("#") @@ -137,9 +143,12 @@ class Color: Color: An instance representing the color. Example: + ```pycon >>> import supervision as sv >>> sv.Color.from_rgb_tuple((255, 255, 0)) Color(r=255, g=255, b=0) + + ``` """ r, g, b = color_tuple return cls(r=r, g=g, b=b) @@ -157,9 +166,12 @@ class Color: Color: An instance representing the color. Example: + ```pycon >>> import supervision as sv >>> sv.Color.from_bgr_tuple((0, 255, 255)) Color(r=255, g=255, b=0) + + ``` """ b, g, r = color_tuple return cls(r=r, g=g, b=b) @@ -172,9 +184,12 @@ class Color: str: The hexadecimal color string. Example: + ```pycon >>> import supervision as sv >>> sv.Color(r=255, g=255, b=0).as_hex() '#ffff00' + + ``` """ return f"#{self.r:02x}{self.g:02x}{self.b:02x}" @@ -186,9 +201,12 @@ class Color: Tuple[int, int, int]: RGB tuple. Example: + ```pycon >>> import supervision as sv >>> sv.Color(r=255, g=255, b=0).as_rgb() (255, 255, 0) + + ``` """ return self.r, self.g, self.b @@ -200,9 +218,12 @@ class Color: Tuple[int, int, int]: BGR tuple. Example: + ```pycon >>> import supervision as sv >>> sv.Color(r=255, g=255, b=0).as_bgr() (0, 255, 255) + + ``` """ return self.b, self.g, self.r @@ -263,10 +284,13 @@ class ColorPalette: ColorPalette: A ColorPalette instance with default colors. Example: + ```pycon >>> import supervision as sv >>> sv.ColorPalette.DEFAULT # doctest: +ELLIPSIS ColorPalette(colors=[Color(r=163, g=81, b=251), Color(r=255, g=64, b=64), ...]) + ``` + ![default-color-palette](https://media.roboflow.com/ supervision-annotator-examples/default-color-palette.png) """ # noqa: E501 // docs @@ -281,10 +305,13 @@ class ColorPalette: ColorPalette: A ColorPalette instance with Roboflow colors. Example: + ```pycon >>> import supervision as sv >>> sv.ColorPalette.ROBOFLOW # doctest: +ELLIPSIS ColorPalette(colors=[Color(r=194, g=141, b=252), Color(r=163, g=81, b=251), ...]) + ``` + ![roboflow-color-palette](https://media.roboflow.com/ supervision-annotator-examples/roboflow-color-palette.png) """ # noqa: E501 // docs @@ -306,10 +333,13 @@ class ColorPalette: ColorPalette: A ColorPalette instance. Example: + ```pycon >>> import supervision as sv >>> colors = ['#ff0000', '#00ff00', '#0000ff'] >>> sv.ColorPalette.from_hex(colors) # doctest: +ELLIPSIS ColorPalette(colors=[Color(r=255, g=0, b=0), Color(r=0, g=255, b=0), ...]) + + ``` """ colors = [Color.from_hex(color_hex) for color_hex in color_hex_list] return cls(colors) @@ -327,10 +357,13 @@ class ColorPalette: ColorPalette: A ColorPalette instance. Example: + ```pycon >>> import supervision as sv >>> sv.ColorPalette.from_matplotlib('viridis', 5) # doctest: +ELLIPSIS ColorPalette(colors=[Color(r=68, g=1, b=84), Color(r=58, g=82, b=139), ...]) + ``` + ![visualized_color_palette](https://media.roboflow.com/ supervision-annotator-examples/visualized_color_palette.png) """ @@ -356,11 +389,14 @@ class ColorPalette: Color: Color at the given index. Example: + ```pycon >>> import supervision as sv >>> colors = ['#ff0000', '#00ff00', '#0000ff'] >>> color_palette = sv.ColorPalette.from_hex(colors) >>> color_palette.by_idx(1) Color(r=0, g=255, b=0) + + ``` """ if idx < 0: raise ValueError("idx argument should not be negative") @@ -389,11 +425,14 @@ def unify_to_bgr(color: tuple[int, int, int] | Color) -> tuple[int, int, int]: The color in BGR format as a tuple of three integers. Example: + ```pycon >>> from supervision.draw.color import unify_to_bgr, Color >>> unify_to_bgr(Color.WHITE) (255, 255, 255) >>> unify_to_bgr((0, 255, 255)) (0, 255, 255) + + ``` """ if issubclass(type(color), Color): color = cast(Color, color) diff --git a/src/supervision/draw/utils.py b/src/supervision/draw/utils.py index a6dca7b7..3109d579 100644 --- a/src/supervision/draw/utils.py +++ b/src/supervision/draw/utils.py @@ -248,6 +248,7 @@ def draw_text( np.ndarray: The input scene with the text drawn on it. Examples: + ```pycon >>> import numpy as np >>> from supervision.geometry.core import Point >>> from supervision.draw.utils import draw_text @@ -258,6 +259,8 @@ def draw_text( ... ) >>> scene.shape (100, 100, 3) + + ``` """ text_width, text_height = cv2.getTextSize( text=text, @@ -376,11 +379,14 @@ def calculate_optimal_text_scale(resolution_wh: tuple[int, int]) -> float: float: recommended font scale factor Examples: + ```pycon >>> import supervision as sv >>> sv.calculate_optimal_text_scale((1920, 1080)) 1.08 >>> sv.calculate_optimal_text_scale((640, 480)) 0.48 + + ``` """ return min(resolution_wh) * 1e-3 @@ -398,11 +404,14 @@ def calculate_optimal_line_thickness(resolution_wh: tuple[int, int]) -> int: int: recommended line thickness in pixels Examples: + ```pycon >>> import supervision as sv >>> sv.calculate_optimal_line_thickness((1920, 1080)) 4 >>> sv.calculate_optimal_line_thickness((640, 480)) 2 + + ``` """ if min(resolution_wh) < 1080: return 2 diff --git a/src/supervision/geometry/core.py b/src/supervision/geometry/core.py index fc8fb63d..cc9b647a 100644 --- a/src/supervision/geometry/core.py +++ b/src/supervision/geometry/core.py @@ -36,12 +36,15 @@ class Point: y: The y-coordinate of the point. Example: + ```pycon >>> from supervision.geometry.core import Point >>> point = Point(x=10.0, y=20.0) >>> point.as_xy_int_tuple() (10, 20) >>> point.as_xy_float_tuple() (10.0, 20.0) + + ``` """ x: float @@ -76,6 +79,7 @@ class Vector: end: The end point of the vector. Example: + ```pycon >>> from supervision.geometry.core import Point, Vector >>> start_point = Point(x=0.0, y=0.0) >>> end_point = Point(x=3.0, y=4.0) @@ -84,6 +88,8 @@ class Vector: 5.0 >>> vector.center Point(x=1.5, y=2.0) + + ``` """ start: Point @@ -148,6 +154,7 @@ class Rect: height: The height of the rectangle. Example: + ```pycon >>> from supervision.geometry.core import Rect >>> rect = Rect(x=10.0, y=20.0, width=30.0, height=40.0) >>> rect.top_left @@ -156,6 +163,8 @@ class Rect: Point(x=40.0, y=60.0) >>> rect.as_xyxy_int_tuple() (10, 20, 40, 60) + + ``` """ x: float diff --git a/src/supervision/geometry/utils.py b/src/supervision/geometry/utils.py index f51e4577..e9a95a31 100644 --- a/src/supervision/geometry/utils.py +++ b/src/supervision/geometry/utils.py @@ -21,6 +21,7 @@ def get_polygon_center(polygon: npt.NDArray[np.float64]) -> Point: ValueError: If the polygon has no vertices. Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> polygon = np.array([[0, 0], [0, 2], [2, 2], [2, 0]]) @@ -29,6 +30,8 @@ def get_polygon_center(polygon: npt.NDArray[np.float64]) -> Point: 1.0 >>> float(center.y) 1.0 + + ``` """ # This is one of the 3 candidate algorithms considered for centroid calculation. diff --git a/src/supervision/key_points/annotators.py b/src/supervision/key_points/annotators.py index dc004abb..a13115b1 100644 --- a/src/supervision/key_points/annotators.py +++ b/src/supervision/key_points/annotators.py @@ -61,6 +61,7 @@ class VertexAnnotator(BaseKeyPointAnnotator): or `PIL.Image.Image`) Example: + ```pycon >>> import numpy as np >>> import supervision as sv >>> image = np.zeros((100, 100, 3), dtype=np.uint8) @@ -77,6 +78,8 @@ class VertexAnnotator(BaseKeyPointAnnotator): ... ) >>> annotated_frame.shape (100, 100, 3) + + ``` """ assert isinstance(scene, np.ndarray) if len(key_points) == 0: @@ -137,6 +140,7 @@ class EdgeAnnotator(BaseKeyPointAnnotator): or `PIL.Image.Image`) Example: + ```pycon >>> import numpy as np >>> import supervision as sv >>> image = np.zeros((100, 100, 3), dtype=np.uint8) @@ -153,6 +157,8 @@ class EdgeAnnotator(BaseKeyPointAnnotator): ... ) >>> annotated_frame.shape (100, 100, 3) + + ``` """ assert isinstance(scene, np.ndarray) if len(key_points) == 0: @@ -248,6 +254,7 @@ class VertexLabelAnnotator: or `PIL.Image.Image`) Example: + ```pycon >>> import numpy as np >>> import supervision as sv >>> image = np.zeros((100, 100, 3), dtype=np.uint8) @@ -266,6 +273,8 @@ class VertexLabelAnnotator: >>> annotated_frame.shape (100, 100, 3) + ``` + ![vertex-label-annotator-example](https://media.roboflow.com/supervision-annotator-examples/vertex-label-annotator-example.png) !!! tip @@ -274,6 +283,7 @@ class VertexLabelAnnotator: values. Example: + ```pycon >>> import numpy as np >>> import supervision as sv >>> image = np.zeros((100, 100, 3), dtype=np.uint8) @@ -312,6 +322,8 @@ class VertexLabelAnnotator: >>> annotated_frame.shape (100, 100, 3) + ``` + ![vertex-label-annotator-custom-example](https://media.roboflow.com/supervision-annotator-examples/vertex-label-annotator-custom-example.png) """ assert isinstance(scene, np.ndarray) diff --git a/src/supervision/key_points/core.py b/src/supervision/key_points/core.py index 417b03c1..4099d0dd 100644 --- a/src/supervision/key_points/core.py +++ b/src/supervision/key_points/core.py @@ -175,12 +175,15 @@ class KeyPoints: int: The number of objects. Example: + ```pycon >>> import numpy as np >>> import supervision as sv >>> xy = np.array([[[10, 20], [30, 40]]], dtype=np.float32) >>> key_points = sv.KeyPoints(xy=xy) >>> len(key_points) 1 + + ``` """ return len(self.xy) @@ -769,10 +772,13 @@ class KeyPoints: An empty `sv.KeyPoints` object. Examples: + ```pycon >>> import supervision as sv >>> key_points = sv.KeyPoints.empty() >>> len(key_points) 0 + + ``` """ return cls(xy=np.empty((0, 0, 2), dtype=np.float32)) @@ -784,10 +790,13 @@ class KeyPoints: bool: `True` if the object is empty, `False` otherwise. Example: + ```pycon >>> import supervision as sv >>> key_points = sv.KeyPoints.empty() >>> key_points.is_empty() True + + ``` """ empty_key_points = KeyPoints.empty() empty_key_points.data = self.data @@ -811,6 +820,7 @@ class KeyPoints: detections: The converted detections object. Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> key_points = sv.KeyPoints( @@ -819,6 +829,8 @@ class KeyPoints: >>> detections = key_points.as_detections() >>> detections.xyxy array([[10., 20., 30., 40.]], dtype=float32) + + ``` """ if self.is_empty(): return Detections.empty() diff --git a/src/supervision/metrics/detection.py b/src/supervision/metrics/detection.py index 7074474e..b057d7f5 100644 --- a/src/supervision/metrics/detection.py +++ b/src/supervision/metrics/detection.py @@ -121,6 +121,7 @@ class ConfusionMatrix: New instance of ConfusionMatrix. Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> targets = [ @@ -144,6 +145,8 @@ class ConfusionMatrix: >>> confusion_matrix.matrix array([[1., 0.], [0., 0.]]) + + ``` """ prediction_tensors = [] @@ -192,6 +195,7 @@ class ConfusionMatrix: New instance of ConfusionMatrix. Examples: + ```pycon >>> import supervision as sv >>> import numpy as np >>> targets = [ @@ -217,6 +221,8 @@ class ConfusionMatrix: array([[1., 0., 1.], [0., 1., 0.], [1., 0., 0.]]) + + ``` """ validate_input_tensors(predictions, targets) @@ -533,6 +539,7 @@ class MeanAveragePrecision: New instance of ConfusionMatrix. Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> targets = [ @@ -554,6 +561,8 @@ class MeanAveragePrecision: ... ) >>> round(float(mAP.map50), 2) 0.99 + + ``` """ prediction_tensors = [] target_tensors = [] @@ -637,6 +646,7 @@ class MeanAveragePrecision: New instance of MeanAveragePrecision. Examples: + ```pycon >>> import supervision as sv >>> import numpy as np >>> targets = [ @@ -659,6 +669,8 @@ class MeanAveragePrecision: ... ) >>> round(float(mAP.map50), 2) 0.81 + + ``` """ validate_input_tensors(predictions, targets) iou_thresholds = np.linspace(0.5, 0.95, 10) diff --git a/src/supervision/metrics/f1_score.py b/src/supervision/metrics/f1_score.py index e34a614e..ecfe701c 100644 --- a/src/supervision/metrics/f1_score.py +++ b/src/supervision/metrics/f1_score.py @@ -38,6 +38,7 @@ class F1Score(Metric): `F1 = 2 * (precision * recall) / (precision + recall)` Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> from supervision.metrics import F1Score @@ -55,6 +56,8 @@ class F1Score(Metric): >>> round(float(f1_result.f1_50), 2) 1.0 + ``` + ![example_plot]( https://media.roboflow.com/supervision-docs/metrics/f1_plot_example.png ){ align=center width="800" } diff --git a/src/supervision/metrics/mean_average_precision.py b/src/supervision/metrics/mean_average_precision.py index 69ab21fc..24c4cc49 100644 --- a/src/supervision/metrics/mean_average_precision.py +++ b/src/supervision/metrics/mean_average_precision.py @@ -1188,6 +1188,7 @@ class MeanAveragePrecision(Metric): It is the average of the precision-recall curves at different IoU thresholds. Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> from supervision.metrics import MeanAveragePrecision @@ -1212,6 +1213,8 @@ class MeanAveragePrecision(Metric): Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = -1.000 Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = -1.000 + ``` + ![example_plot]( https://media.roboflow.com/supervision-docs/metrics/mAP_plot_example.png ){ align=center width="800" } diff --git a/src/supervision/metrics/mean_average_recall.py b/src/supervision/metrics/mean_average_recall.py index 670b07a7..3d937178 100644 --- a/src/supervision/metrics/mean_average_recall.py +++ b/src/supervision/metrics/mean_average_recall.py @@ -252,6 +252,7 @@ class MeanAverageRecall(Metric): confidence detection for each class. Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> from supervision.metrics import MeanAverageRecall @@ -269,6 +270,8 @@ class MeanAverageRecall(Metric): >>> round(float(mar_result.mAR_at_100), 2) 1.0 + ``` + ![example_plot]( https://media.roboflow.com/supervision-docs/metrics/mAR_plot_example.png ){ align=center width="800" } diff --git a/src/supervision/metrics/precision.py b/src/supervision/metrics/precision.py index 596a6f74..c0c9c1e1 100644 --- a/src/supervision/metrics/precision.py +++ b/src/supervision/metrics/precision.py @@ -41,6 +41,7 @@ class Precision(Metric): number of false positive detections (detected, but incorrectly). Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> from supervision.metrics import Precision @@ -58,6 +59,8 @@ class Precision(Metric): >>> round(float(precision_result.precision_at_50), 2) 1.0 + ``` + ![example_plot]( https://media.roboflow.com/supervision-docs/metrics/precision_plot_example.png ){ align=center width="800" } diff --git a/src/supervision/metrics/recall.py b/src/supervision/metrics/recall.py index d16791ab..ef7b7c97 100644 --- a/src/supervision/metrics/recall.py +++ b/src/supervision/metrics/recall.py @@ -41,6 +41,7 @@ class Recall(Metric): number of false negatives (missed detections). Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> from supervision.metrics import Recall @@ -58,6 +59,8 @@ class Recall(Metric): >>> round(float(recall_result.recall_at_50), 2) 1.0 + ``` + ![example_plot]( https://media.roboflow.com/supervision-docs/metrics/recall_plot_example.png ){ align=center width="800" } diff --git a/src/supervision/metrics/utils/object_size.py b/src/supervision/metrics/utils/object_size.py index 8e9457c4..ad9f37b5 100644 --- a/src/supervision/metrics/utils/object_size.py +++ b/src/supervision/metrics/utils/object_size.py @@ -24,6 +24,7 @@ class ObjectSizeCategory(Enum): Large: area >= 96^2 Example: + ```pycon >>> from supervision.metrics.utils.object_size import ObjectSizeCategory >>> ObjectSizeCategory.SMALL.value 1 @@ -31,6 +32,8 @@ class ObjectSizeCategory(Enum): 2 >>> ObjectSizeCategory.LARGE.value 3 + + ``` """ ANY = -1 @@ -55,6 +58,7 @@ def get_object_size_category( the enum values of ObjectSizeCategory. Shaped (N,). Example: + ```pycon >>> import numpy as np >>> from supervision.metrics.core import MetricTarget >>> from supervision.metrics.utils.object_size import get_object_size_category @@ -65,6 +69,8 @@ def get_object_size_category( ... ]) >>> get_object_size_category(xyxy, MetricTarget.BOXES) array([1, 2, 3]) + + ``` """ if metric_target == MetricTarget.BOXES: return get_bbox_size_category(data) @@ -87,6 +93,7 @@ def get_bbox_size_category(xyxy: npt.NDArray[np.float32]) -> npt.NDArray[np.int_ the enum values of ObjectSizeCategory. Shaped (N,). Example: + ```pycon >>> import numpy as np >>> from supervision.metrics.utils.object_size import get_bbox_size_category >>> xyxy = np.array([ @@ -97,6 +104,8 @@ def get_bbox_size_category(xyxy: npt.NDArray[np.float32]) -> npt.NDArray[np.int_ ... ]) >>> get_bbox_size_category(xyxy) array([1, 2, 2, 3]) + + ``` """ if len(xyxy.shape) != 2 or xyxy.shape[1] != 4: raise ValueError("Bounding boxes must be shaped (N, 4)") @@ -125,6 +134,7 @@ def get_mask_size_category(mask: npt.NDArray[np.bool_]) -> npt.NDArray[np.int_]: the enum values of ObjectSizeCategory. Shaped (N,). Example: + ```pycon >>> import numpy as np >>> from supervision.metrics.utils.object_size import get_mask_size_category >>> mask = np.zeros((3, 100, 100), dtype=bool) @@ -133,6 +143,8 @@ def get_mask_size_category(mask: npt.NDArray[np.bool_]) -> npt.NDArray[np.int_]: >>> mask[2, 0:100, 0:100] = True # 10000 (Large) >>> get_mask_size_category(mask) array([1, 2, 3]) + + ``` """ if len(mask.shape) != 3: raise ValueError("Masks must be shaped (N, H, W)") @@ -159,6 +171,7 @@ def get_obb_size_category(xyxyxyxy: npt.NDArray[np.float32]) -> npt.NDArray[np.i the enum values of ObjectSizeCategory. Shaped (N,). Example: + ```pycon >>> import numpy as np >>> from supervision.metrics.utils.object_size import get_obb_size_category >>> obb = np.array([ @@ -168,6 +181,8 @@ def get_obb_size_category(xyxyxyxy: npt.NDArray[np.float32]) -> npt.NDArray[np.i ... ]) >>> get_obb_size_category(obb) array([1, 2, 3]) + + ``` """ if len(xyxyxyxy.shape) != 3 or xyxyxyxy.shape[1] != 4 or xyxyxyxy.shape[2] != 2: raise ValueError("Oriented bounding boxes must be shaped (N, 4, 2)") diff --git a/src/supervision/utils/file.py b/src/supervision/utils/file.py index 4849ae20..764ee5f3 100644 --- a/src/supervision/utils/file.py +++ b/src/supervision/utils/file.py @@ -35,6 +35,7 @@ def list_files_with_extensions( A list of Path objects for the matching files. Examples: + ```pycon >>> import supervision as sv >>> from pathlib import Path >>> import tempfile @@ -54,6 +55,8 @@ def list_files_with_extensions( ... directory=tmpdir, extensions=['txt', 'md']) >>> len(files) 2 + + ``` """ directory = Path(directory) @@ -82,6 +85,7 @@ def read_txt_file(file_path: str | Path, skip_empty: bool = False) -> list[str]: A list of strings representing the lines in the text file. Examples: + ```pycon >>> import tempfile >>> from pathlib import Path >>> from supervision.utils.file import read_txt_file, save_text_file @@ -92,6 +96,8 @@ def read_txt_file(file_path: str | Path, skip_empty: bool = False) -> list[str]: ... print(read_txt_file(file_path, skip_empty=True)) ['line1', ' ', 'line3'] ['line1', 'line3'] + + ``` """ with open(str(file_path)) as file: if skip_empty: @@ -126,6 +132,7 @@ def read_json_file(file_path: str | Path) -> dict[str, Any]: A dict of annotations information Examples: + ```pycon >>> import tempfile >>> from pathlib import Path >>> from supervision.utils.file import read_json_file, save_json_file @@ -135,6 +142,8 @@ def read_json_file(file_path: str | Path) -> dict[str, Any]: ... save_json_file(data, file_path) ... print(read_json_file(file_path)) {'key': 'value', 'list': [1, 2, 3]} + + ``` """ with open(str(file_path)) as file: data = json.load(file) diff --git a/src/supervision/utils/image.py b/src/supervision/utils/image.py index d8417225..717cd5a1 100644 --- a/src/supervision/utils/image.py +++ b/src/supervision/utils/image.py @@ -35,6 +35,7 @@ def crop_image( type. Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> image = np.zeros((1080, 1920, 3), dtype=np.uint8) @@ -45,6 +46,9 @@ def crop_image( >>> cropped_image.shape (400, 400, 3) + ``` + + ```pycon >>> image = np.zeros((1920, 1080), dtype=np.uint8) >>> image.shape (1920, 1080) @@ -53,6 +57,8 @@ def crop_image( >>> cropped_image.shape (400, 400) + ``` + ![crop-image](https://media.roboflow.com/supervision-docs/supervision-docs-crop-image-2.png){ align=center width="1000" } """ # noqa E501 // docs if isinstance(xyxy, (list, tuple)): @@ -89,6 +95,7 @@ def scale_image(image: ImageType, scale_factor: float) -> ImageType: ValueError: If scale factor is non-positive. Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> image = np.zeros((1080, 1920, 3), dtype=np.uint8) @@ -98,6 +105,9 @@ def scale_image(image: ImageType, scale_factor: float) -> ImageType: >>> scaled_image.shape (540, 960, 3) + ``` + + ```pycon >>> image = np.zeros((1920, 1080), dtype=np.uint8) >>> image.shape (1920, 1080) @@ -105,6 +115,8 @@ def scale_image(image: ImageType, scale_factor: float) -> ImageType: >>> scaled_image.shape (960, 540) + ``` + ![scale-image](https://media.roboflow.com/supervision-docs/supervision-docs-scale-image-2.png){ align=center width="1000" } """ # noqa E501 // docs if scale_factor <= 0: @@ -136,6 +148,7 @@ def resize_image( type. Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> image = np.zeros((1080, 1920, 3), dtype=np.uint8) @@ -147,6 +160,9 @@ def resize_image( >>> resized_image.shape (562, 1000, 3) + ``` + + ```pycon >>> image = np.zeros((1920, 1080), dtype=np.uint8) >>> image.shape (1920, 1080) @@ -156,6 +172,8 @@ def resize_image( >>> resized_image.shape (1000, 562) + ``` + ![resize-image](https://media.roboflow.com/supervision-docs/supervision-docs-resize-image-2.png){ align=center width="1000" } """ # noqa E501 // docs if keep_aspect_ratio: @@ -194,6 +212,7 @@ def letterbox_image( type. Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> image = np.zeros((1080, 1920, 3), dtype=np.uint8) @@ -205,6 +224,8 @@ def letterbox_image( >>> letterboxed_image.shape (1000, 1000, 3) + ``` + ![letterbox-image](https://media.roboflow.com/supervision-docs/supervision-docs-letterbox-image-2.png){ align=center width="1000" } """ # noqa E501 // docs assert isinstance(image, np.ndarray) @@ -260,6 +281,7 @@ def overlay_image( Scene with overlay applied, shape `(height, width, 3)`. Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> image = np.zeros((1000, 1000, 3), dtype=np.uint8) @@ -270,6 +292,8 @@ def overlay_image( ... ) >>> result_image.shape (1000, 1000, 3) + + ``` """ scene_height, scene_width = image.shape[:2] image_height, image_width = overlay.shape[:2] @@ -332,6 +356,7 @@ def tint_image( ValueError: If opacity is outside range [0.0, 1.0]. Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> image = np.zeros((100, 100, 3), dtype=np.uint8) @@ -341,6 +366,8 @@ def tint_image( >>> tinted_image.shape (100, 100, 3) + ``` + ![tint-image](https://media.roboflow.com/supervision-docs/supervision-docs-tint-image-2.png){ align=center width="1000" } """ # noqa E501 // docs if not 0.0 <= opacity <= 1.0: @@ -368,6 +395,7 @@ def grayscale_image(image: ImageType) -> ImageType: matching input type. Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> image = np.ones((100, 100, 3), dtype=np.uint8) * 128 @@ -375,6 +403,8 @@ def grayscale_image(image: ImageType) -> ImageType: >>> grayscale_image.shape (100, 100, 3) + ``` + ![grayscale-image](https://media.roboflow.com/supervision-docs/supervision-docs-grayscale-image-2.png){ align=center width="1000" } """ # noqa E501 // docs grayscaled = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) @@ -400,11 +430,14 @@ def get_image_resolution_wh(image: ImageType) -> tuple[int, int]: `PIL.Image.Image`). Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> image = np.zeros((1080, 1920, 3), dtype=np.uint8) >>> sv.get_image_resolution_wh(image) (1920, 1080) + + ``` """ if isinstance(image, np.ndarray): if image.ndim < 2: @@ -444,6 +477,7 @@ class ImageSink: Defaults to `"image_{:05d}.png"`. Examples: + ```pycon >>> import numpy as np >>> import supervision as sv >>> import tempfile @@ -456,6 +490,8 @@ class ImageSink: ... files = sorted(os.listdir(tmpdir)) ... len(files) 2 + + ``` """ self.target_dir_path = target_dir_path self.overwrite = overwrite diff --git a/src/supervision/utils/internal.py b/src/supervision/utils/internal.py index c93cc07e..4b92c43b 100644 --- a/src/supervision/utils/internal.py +++ b/src/supervision/utils/internal.py @@ -78,6 +78,7 @@ def deprecated_parameter( parameter as deprecated. Examples: + ```pycon >>> from supervision.utils.internal import deprecated_parameter >>> import warnings >>> @deprecated_parameter( @@ -94,6 +95,8 @@ def deprecated_parameter( ... result = example_function(old_name='deprecated_value') ... print(result) deprecated_value + + ``` """ def decorator(func: Callable[..., Any]) -> Callable[..., Any]: @@ -196,6 +199,7 @@ def get_instance_variables(instance: Any, include_properties: bool = False) -> s include_properties: Whether to include properties in the result Usage: + ```pycon >>> from supervision.utils.internal import get_instance_variables >>> import numpy as np >>> from supervision import Detections @@ -205,6 +209,8 @@ def get_instance_variables(instance: Any, include_properties: bool = False) -> s True >>> 'data' in variables True + + ``` """ if isinstance(instance, type): raise ValueError("Only class instances are supported, not classes.") diff --git a/src/supervision/utils/iterables.py b/src/supervision/utils/iterables.py index 268887b7..9b30e6bb 100644 --- a/src/supervision/utils/iterables.py +++ b/src/supervision/utils/iterables.py @@ -22,11 +22,14 @@ def create_batches( the input `sequence`. Examples: + ```pycon >>> from supervision.utils.iterables import create_batches >>> list(create_batches([1, 2, 3, 4, 5], 2)) [[1, 2], [3, 4], [5]] >>> list(create_batches("abcde", 3)) [['a', 'b', 'c'], ['d', 'e']] + + ``` """ batch_size = max(batch_size, 1) current_batch: list[V] = [] @@ -56,11 +59,14 @@ def fill(sequence: list[V], desired_size: int, content: V) -> list[V]: A padded version of the input `sequence` (if needed). Examples: + ```pycon >>> from supervision.utils.iterables import fill >>> fill([1, 2], 4, 0) [1, 2, 0, 0] >>> fill(['a', 'b'], 3, 'c') ['a', 'b', 'c'] + + ``` """ missing_size = max(0, desired_size - len(sequence)) sequence.extend([content] * missing_size) @@ -78,11 +84,14 @@ def find_duplicates(sequence: list[V]) -> list[V]: A list of duplicate elements found in the sequence. Examples: + ```pycon >>> from supervision.utils.iterables import find_duplicates >>> sorted(find_duplicates([1, 2, 3, 2, 4, 5, 1])) [1, 2] >>> find_duplicates(['a', 'b', 'c']) [] + + ``` """ seen = set() duplicates = set() diff --git a/src/supervision/utils/notebook.py b/src/supervision/utils/notebook.py index a0f61513..ed8f4f68 100644 --- a/src/supervision/utils/notebook.py +++ b/src/supervision/utils/notebook.py @@ -21,6 +21,7 @@ def plot_image( cmap: the colormap to use for single channel images. Examples: + ```pycon >>> import cv2 >>> import numpy as np >>> import matplotlib @@ -29,6 +30,8 @@ def plot_image( >>> image = np.zeros((100, 100, 3), dtype=np.uint8) >>> sv.plot_image(image=image, size=(16, 16)) ... + + ``` """ if isinstance(image, Image.Image): image = pillow_to_cv2(image) @@ -69,6 +72,7 @@ def plot_images_grid( ValueError: If the number of images exceeds the grid size. Examples: + ```pycon >>> import cv2 >>> import numpy as np >>> import matplotlib @@ -82,6 +86,8 @@ def plot_images_grid( >>> titles = ["Image 1", "Image 2", "Image 3"] >>> sv.plot_images_grid(images, grid_size=(2, 2), titles=titles, size=(16, 16)) ... + + ``` """ nrows, ncols = grid_size diff --git a/src/supervision/validators/__init__.py b/src/supervision/validators/__init__.py index 2ece1db4..bb31816d 100644 --- a/src/supervision/validators/__init__.py +++ b/src/supervision/validators/__init__.py @@ -6,7 +6,10 @@ import numpy as np def validate_xyxy(xyxy: Any) -> None: """Validate that xyxy is a 2D np.ndarray with shape (N, 4). + ```pycon >>> validate_xyxy(np.array([[0, 0, 1, 1], [1, 1, 2, 2]])) + + ``` """ expected_shape = "(_, 4)" actual_shape = str(getattr(xyxy, "shape", None))