diff --git a/docs/utils/image.md b/docs/utils/image.md index 99b8b9b0..c712c8f9 100644 --- a/docs/utils/image.md +++ b/docs/utils/image.md @@ -1,3 +1,7 @@ ## ImageSink -:::supervision.utils.image.ImageSink \ No newline at end of file +:::supervision.utils.image.ImageSink + +## crop + +:::supervision.utils.image.crop \ No newline at end of file diff --git a/supervision/__init__.py b/supervision/__init__.py index f0e7cca8..31a3ad0f 100644 --- a/supervision/__init__.py +++ b/supervision/__init__.py @@ -19,7 +19,7 @@ from supervision.draw.utils import draw_filled_rectangle, draw_polygon, draw_tex from supervision.geometry.core import Point, Position, Rect from supervision.geometry.utils import get_polygon_center from supervision.utils.file import list_files_with_extensions -from supervision.utils.image import ImageSink +from supervision.utils.image import ImageSink, crop from supervision.utils.notebook import plot_image, plot_images_grid from supervision.utils.video import ( VideoInfo, diff --git a/supervision/utils/image.py b/supervision/utils/image.py index 90de4677..a0843854 100644 --- a/supervision/utils/image.py +++ b/supervision/utils/image.py @@ -6,6 +6,35 @@ import cv2 import numpy as np +def crop(image: np.ndarray, xyxy: np.ndarray) -> np.ndarray: + """ + Crops the given image based on the given bounding box. + + Args: + image (np.ndarray): The image to be cropped, represented as a numpy array. + xyxy (np.ndarray): A numpy array containing the bounding box coordinates in the format (x1, y1, x2, y2). + + Returns: + (np.ndarray): The cropped image as a numpy array. + + Examples: + ```python + >>> import supervision as sv + + >>> detection = sv.Detections(...) + >>> with sv.ImageSink(target_dir_path='target/directory/path') as sink: + ... for xyxy in detection.xyxy: + ... cropped_image = sv.crop(image=image, xyxy=xyxy) + ... sink.save_image(image=image) + ``` + """ + + xyxy = np.round(xyxy).astype(int) + x1, y1, x2, y2 = xyxy + cropped_img = image[y1:y2, x1:x2] + return cropped_img + + class ImageSink: def __init__( self, @@ -21,7 +50,7 @@ class ImageSink: overwrite (bool, optional): Whether to overwrite the existing directory. Defaults to False. image_name_pattern (str, optional): The image file name pattern. Defaults to "image_{:05d}.png". - Example: + Examples: ```python >>> import supervision as sv