Skip to content

Register now for

# Reference for `ultralytics/solutions/object_cropper.py`

Note

This file is available at https://github.com/ultralytics/ultralytics/blob/main/ultralytics/solutions/object_cropper.py. If you spot a problem please help fix it by contributing a Pull Request 🛠️. Thank you 🙏!

## `` ultralytics.solutions.object_cropper.ObjectCropper

    ObjectCropper(**kwargs: Any)

Bases: `BaseSolution`

A class to manage the cropping of detected objects in a real-time video stream or images.

This class extends the BaseSolution class and provides functionality for cropping objects based on detected bounding boxes. The cropped images are saved to a specified directory for further analysis or usage.

Attributes:

Name | Type | Description
--- | --- | ---
`crop_dir` | `str` | Directory where cropped object images are stored.
`crop_idx` | `int` | Counter for the total number of cropped objects.
`iou` | `float` | IoU (Intersection over Union) threshold for non-maximum suppression.
`conf` | `float` | Confidence threshold for filtering detections.

Methods:

Name | Description
--- | ---
`process` | Crop detected objects from the input image and save them to the output directory.

Examples:

    >>> cropper = ObjectCropper()
    >>> frame = cv2.imread("frame.jpg")
    >>> processed_results = cropper.process(frame)
    >>> print(f"Total cropped objects: {cropper.crop_idx}")

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`**kwargs` | `Any` | Keyword arguments passed to the parent class and used for configuration. crop_dir (str): Path to the directory for saving cropped object images. | `{}`

Source code in `ultralytics/solutions/object_cropper.py`

    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    def __init__(self, **kwargs: Any) -> None:
        """
        Initialize the ObjectCropper class for cropping objects from detected bounding boxes.

        Args:
            **kwargs (Any): Keyword arguments passed to the parent class and used for configuration.
                crop_dir (str): Path to the directory for saving cropped object images.
        """
        super().__init__(**kwargs)

        self.crop_dir = self.CFG["crop_dir"]  # Directory for storing cropped detections
        if not os.path.exists(self.crop_dir):
            os.mkdir(self.crop_dir)  # Create directory if it does not exist
        if self.CFG["show"]:
            self.LOGGER.warning(
                f"show=True disabled for crop solution, results will be saved in the directory named: {self.crop_dir}"
            )
        self.crop_idx = 0  # Initialize counter for total cropped objects
        self.iou = self.CFG["iou"]
        self.conf = self.CFG["conf"]

### `` process

    process(im0) -> SolutionResults

Crop detected objects from the input image and save them as separate images.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`im0` | `ndarray` | The input image containing detected objects. | required

Returns:

Type | Description
--- | ---
`SolutionResults` | A SolutionResults object containing the total number of cropped objects and processed image.

Examples:

    >>> cropper = ObjectCropper()
    >>> frame = cv2.imread("image.jpg")
    >>> results = cropper.process(frame)
    >>> print(f"Total cropped objects: {results.total_crop_objects}")

Source code in `ultralytics/solutions/object_cropper.py`

    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
    def process(self, im0) -> SolutionResults:
        """
        Crop detected objects from the input image and save them as separate images.

        Args:
            im0 (np.ndarray): The input image containing detected objects.

        Returns:
            (SolutionResults): A SolutionResults object containing the total number of cropped objects and processed
                image.

        Examples:
            >>> cropper = ObjectCropper()
            >>> frame = cv2.imread("image.jpg")
            >>> results = cropper.process(frame)
            >>> print(f"Total cropped objects: {results.total_crop_objects}")
        """
        with self.profilers[0]:
            results = self.model.predict(
                im0,
                classes=self.classes,
                conf=self.conf,
                iou=self.iou,
                device=self.CFG["device"],
                verbose=False,
            )[0]
            self.clss = results.boxes.cls.tolist()  # required for logging only.

        for box in results.boxes:
            self.crop_idx += 1
            save_one_box(
                box.xyxy,
                im0,
                file=Path(self.crop_dir) / f"crop_{self.crop_idx}.jpg",
                BGR=True,
            )

        # Return SolutionResults
        return SolutionResults(plot_im=im0, total_crop_objects=self.crop_idx)

📅 Created 6 months ago ✏️ Updated 6 months ago