Vai al contenuto

Riferimento per ultralytics/utils/patches.py

Nota

Questo file è disponibile su https://github.com/ultralytics/ ultralytics/blob/main/ ultralytics/utils/patches .py. Se riscontri un problema, contribuisci a risolverlo inviando una Pull Request 🛠️. Grazie 🙏!



ultralytics.utils.patches.imread(filename, flags=cv2.IMREAD_COLOR)

Legge un'immagine da un file.

Parametri:

Nome Tipo Descrizione Predefinito
filename str

Percorso del file da leggere.

richiesto
flags int

Flag che può assumere valori di cv2.IMREAD_*. Il valore predefinito è cv2.IMREAD_COLOR.

IMREAD_COLOR

Restituzione:

Tipo Descrizione
ndarray

L'immagine letta.

Codice sorgente 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_*. Defaults to cv2.IMREAD_COLOR.

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



ultralytics.utils.patches.imwrite(filename, img, params=None)

Scrive un'immagine in un file.

Parametri:

Nome Tipo Descrizione Predefinito
filename str

Percorso del file da scrivere.

richiesto
img ndarray

Immagine da scrivere.

richiesto
params list of ints

Parametri aggiuntivi. Vedi la documentazione di OpenCV.

None

Restituzione:

Tipo Descrizione
bool

Vero se il file è stato scritto, Falso altrimenti.

Codice sorgente 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 of ints, optional): Additional parameters. See OpenCV documentation.

    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(winname, mat)

Visualizza un'immagine nella finestra specificata.

Parametri:

Nome Tipo Descrizione Predefinito
winname str

Nome della finestra.

richiesto
mat ndarray

Immagine da mostrare.

richiesto
Codice sorgente in ultralytics/utils/patches.py
def imshow(winname: str, mat: np.ndarray):
    """
    Displays 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_save(*args, use_dill=True, **kwargs)

Utilizza facoltativamente dill per serializzare le funzioni lambda laddove pickle non lo fa, aggiungendo robustezza con 3 tentativi e uno stallo esponenziale in caso di fallimento del salvataggio.

Parametri:

Nome Tipo Descrizione Predefinito
*args tuple

Argomenti posizionali da passare a torch.save.

()
use_dill bool

Se provare a utilizzare dill per la serializzazione, se disponibile. L'impostazione predefinita è True.

True
**kwargs any

Argomenti delle parole chiave da passare a torch.save.

{}
Codice sorgente in ultralytics/utils/patches.py
def torch_save(*args, use_dill=True, **kwargs):
    """
    Optionally use dill to serialize lambda functions where pickle does not, adding robustness with 3 retries and
    exponential standoff in case of save failure.

    Args:
        *args (tuple): Positional arguments to pass to torch.save.
        use_dill (bool): Whether to try using dill for serialization if available. Defaults to True.
        **kwargs (any): Keyword arguments to pass to torch.save.
    """
    try:
        assert use_dill
        import dill as pickle
    except (AssertionError, ImportError):
        import pickle

    if "pickle_module" not in kwargs:
        kwargs["pickle_module"] = pickle

    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





Creato 2023-11-12, Aggiornato 2024-05-08
Autori: Burhan-Q (1), glenn-jocher (3), Laughing-q (1)