o
    Wh@                     @   s   d Z ddlZddlmZ ddlZddlZddlZejZ	ej
fdedefddZddedejfd	d
ZdedejfddZejZejZdd Zdd ZdS )zDMonkey patches to update/extend functionality of existing functions.    N)Pathfilenameflagsc                 C   sn   t | t j}| dr1t|tj\}}|r/t|dkr(|d jdkr(|d S t j	|ddS dS t
||S )av  
    Read an image from a file.

    Args:
        filename (str): Path to the file to read.
        flags (int): Flag that can take values of cv2.IMREAD_*. Controls how the image is read.

    Returns:
        (np.ndarray): The read image.

    Examples:
        >>> img = imread("path/to/image.jpg")
        >>> img = imread("path/to/image.jpg", cv2.IMREAD_GRAYSCALE)
    )z.tiffz.tif   r         )axisN)npfromfileuint8endswithcv2imdecodemultiIMREAD_UNCHANGEDlenndimstackimdecode)r   r   
file_bytessuccessframes r   M/var/www/vscode/kcb/lib/python3.10/site-packages/ultralytics/utils/patches.pyimread   s   
0r   imgc                 C   s:   zt t| j||d |  W dS  ty   Y dS w )a%  
    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 successfully, False otherwise.

    Examples:
        >>> import numpy as np
        >>> img = np.zeros((100, 100, 3), dtype=np.uint8)  # Create a black image
        >>> success = imwrite("output.jpg", img)  # Write image to file
        >>> print(success)
        True
    r   TF)r   imencoder   suffixtofile	Exception)r   r   paramsr   r   r   imwrite)   s   r    winnamematc                 C   s   t | d | dS )a  
    Display an image in the specified window.

    This function is a wrapper around OpenCV's imshow function that displays an image in a named window. It is
    particularly useful for visualizing images during development and debugging.

    Args:
        winname (str): Name of the window where the image will be displayed. If a window with this name already
            exists, the image will be displayed in that window.
        mat (np.ndarray): Image to be shown. Should be a valid numpy array representing an image.

    Examples:
        >>> import numpy as np
        >>> img = np.zeros((300, 300, 3), dtype=np.uint8)  # Create a black image
        >>> img[:100, :100] = [255, 0, 0]  # Add a blue square
        >>> imshow("Example Window", img)  # Display the image
    unicode_escapeN)_imshowencodedecode)r!   r"   r   r   r   imshowC   s   r'   c                  O   s.   ddl m} |rd|vrd|d< t| i |S )aH  
    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.

    Notes:
        For PyTorch versions 2.0 and above, this function automatically sets 'weights_only=False'
        if the argument is not provided, to avoid deprecation warnings.
    r   )
TORCH_1_13weights_onlyF)ultralytics.utils.torch_utilsr(   _torch_load)argskwargsr(   r   r   r   
torch_load]   s   r.   c                  O   sh   t dD ]-}z
t| i |W   S  ty1 } z|dkr|td| d  W Y d}~qd}~ww dS )aJ  
    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.

    Returns:
        (Any): Result of torch.save operation if successful, None otherwise.

    Examples:
        >>> model = torch.nn.Linear(10, 1)
        >>> torch_save(model.state_dict(), "model.pt")
       r   r   N)range_torch_saveRuntimeErrortimesleep)r,   r-   ier   r   r   
torch_savev   s   r7   )N)__doc__r3   pathlibr   r   numpyr	   torchr'   r$   IMREAD_COLORstrintr   ndarrayr    loadr+   saver1   r.   r7   r   r   r   r   <module>   s   