Saltar al contenido

Referencia para ultralytics/utils/patches.py

Nota

Este archivo está disponible en https://github.com/ultralytics/ ultralytics/blob/main/ ultralytics/utils/patches .py. Si detectas algún problema, por favor, ayuda a solucionarlo contribuyendo con una Pull Request 🛠️. ¡Gracias 🙏!



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

Lee una imagen de un archivo.

Parámetros:

Nombre Tipo Descripción Por defecto
filename str

Ruta del archivo a leer.

necesario
flags int

Bandera que puede tomar valores de cv2.IMREAD_*. Por defecto es cv2.IMREAD_COLOR.

IMREAD_COLOR

Devuelve:

Tipo Descripción
ndarray

La imagen leída.

Código fuente en 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)

Escribe una imagen en un archivo.

Parámetros:

Nombre Tipo Descripción Por defecto
filename str

Ruta del archivo a escribir.

necesario
img ndarray

Imagen para escribir.

necesario
params list of ints

Parámetros adicionales. Consulta la documentación de OpenCV.

None

Devuelve:

Tipo Descripción
bool

Verdadero si se ha escrito el archivo, Falso en caso contrario.

Código fuente en 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)

Muestra una imagen en la ventana especificada.

Parámetros:

Nombre Tipo Descripción Por defecto
winname str

Nombre de la ventana.

necesario
mat ndarray

Imagen a mostrar.

necesario
Código fuente en 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)

Opcionalmente utiliza dill para serializar funciones lambda donde pickle no lo hace, añadiendo robustez con 3 reintentos y separación exponencial en caso de fallo de guardado.

Parámetros:

Nombre Tipo Descripción Por defecto
*args tuple

Argumentos posicionales para pasar a torch.save.

()
use_dill bool

Si se intenta utilizar dill para la serialización si está disponible. Por defecto es True.

True
**kwargs any

Argumentos de palabra clave para pasar a torch.save.

{}
Código fuente en 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





Creado 2023-11-12, Actualizado 2024-05-08
Autores: Burhan-Q (1), glenn-jocher (3), Laughing-q (1)