Skip to content

Reference for ultralytics/utils/patches.py

Note

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


ultralytics.utils.patches.imread

imread(filename: str, flags: int = cv2.IMREAD_COLOR)

Read an image from a file.

Parameters:

Name Type Description Default
filename str

Path to the file to read.

required
flags int

Flag that can take values of cv2.IMREAD_*.

IMREAD_COLOR

Returns:

Type Description
ndarray

The read image.

Source code in ultralytics/utils/patches.py
def imread(filename: str, flags: int = cv2.IMREAD_COLOR):
    """
    Read an image from a file.

    Args:
        filename (str): Path to the file to read.
        flags (int, optional): Flag that can take values of cv2.IMREAD_*.

    Returns:
        (np.ndarray): The read image.
    """
    return cv2.imdecode(np.fromfile(filename, np.uint8), flags)





ultralytics.utils.patches.imwrite

imwrite(filename: str, img: ndarray, params=None)

Write an image to a file.

Parameters:

Name Type Description Default
filename str

Path to the file to write.

required
img ndarray

Image to write.

required
params List[int]

Additional parameters for image encoding.

None

Returns:

Type Description
bool

True if the file was written, False otherwise.

Source code in ultralytics/utils/patches.py
def imwrite(filename: str, img: np.ndarray, params=None):
    """
    Write an image to a file.

    Args:
        filename (str): Path to the file to write.
        img (np.ndarray): Image to write.
        params (List[int], optional): Additional parameters for image encoding.

    Returns:
        (bool): True if the file was written, False otherwise.
    """
    try:
        cv2.imencode(Path(filename).suffix, img, params)[1].tofile(filename)
        return True
    except Exception:
        return False





ultralytics.utils.patches.imshow

imshow(winname: str, mat: ndarray)

Display an image in the specified window.

Parameters:

Name Type Description Default
winname str

Name of the window.

required
mat ndarray

Image to be shown.

required
Source code in ultralytics/utils/patches.py
def imshow(winname: str, mat: np.ndarray):
    """
    Display an image in the specified window.

    Args:
        winname (str): Name of the window.
        mat (np.ndarray): Image to be shown.
    """
    _imshow(winname.encode("unicode_escape").decode(), mat)





ultralytics.utils.patches.torch_load

torch_load(*args, **kwargs)

Load a PyTorch model with updated arguments to avoid warnings.

This function wraps torch.load and adds the 'weights_only' argument for PyTorch 1.13.0+ to prevent warnings.

Parameters:

Name Type Description Default
*args Any

Variable length argument list to pass to torch.load.

()
**kwargs Any

Arbitrary keyword arguments to pass to torch.load.

{}

Returns:

Type Description
Any

The loaded PyTorch object.

Note

For PyTorch versions 2.0 and above, this function automatically sets 'weights_only=False' if the argument is not provided, to avoid deprecation warnings.

Source code in ultralytics/utils/patches.py
def torch_load(*args, **kwargs):
    """
    Load a PyTorch model with updated arguments to avoid warnings.

    This function wraps torch.load and adds the 'weights_only' argument for PyTorch 1.13.0+ to prevent warnings.

    Args:
        *args (Any): Variable length argument list to pass to torch.load.
        **kwargs (Any): Arbitrary keyword arguments to pass to torch.load.

    Returns:
        (Any): The loaded PyTorch object.

    Note:
        For PyTorch versions 2.0 and above, this function automatically sets 'weights_only=False'
        if the argument is not provided, to avoid deprecation warnings.
    """
    from ultralytics.utils.torch_utils import TORCH_1_13

    if TORCH_1_13 and "weights_only" not in kwargs:
        kwargs["weights_only"] = False

    return _torch_load(*args, **kwargs)





ultralytics.utils.patches.torch_save

torch_save(*args, **kwargs)

Save PyTorch objects with retry mechanism for robustness.

This function wraps torch.save with 3 retries and exponential backoff in case of save failures, which can occur due to device flushing delays or antivirus scanning.

Parameters:

Name Type Description Default
*args Any

Positional arguments to pass to torch.save.

()
**kwargs Any

Keyword arguments to pass to torch.save.

{}
Source code in ultralytics/utils/patches.py
def torch_save(*args, **kwargs):
    """
    Save PyTorch objects with retry mechanism for robustness.

    This function wraps torch.save with 3 retries and exponential backoff in case of save failures, which can occur
    due to device flushing delays or antivirus scanning.

    Args:
        *args (Any): Positional arguments to pass to torch.save.
        **kwargs (Any): Keyword arguments to pass to torch.save.
    """
    for i in range(4):  # 3 retries
        try:
            return _torch_save(*args, **kwargs)
        except RuntimeError as e:  # unable to save, possibly waiting for device to flush or antivirus scan
            if i == 3:
                raise e
            time.sleep((2**i) / 2)  # exponential standoff: 0.5s, 1.0s, 2.0s



📅 Created 1 year ago ✏️ Updated 6 months ago