Salta para o conteúdo

Referência para ultralytics/utils/patches.py

Nota

Este ficheiro está disponível em https://github.com/ultralytics/ ultralytics/blob/main/ ultralytics/utils/patches .py. Se encontrares um problema, por favor ajuda a corrigi-lo contribuindo com um Pull Request 🛠️. Obrigado 🙏!



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

Lê uma imagem de um ficheiro.

Parâmetros:

Nome Tipo Descrição Predefinição
filename str

Caminho para o ficheiro a ler.

necessário
flags int

Sinalizador que pode assumir valores de cv2.IMREAD_*. Usa por defeito cv2.IMREAD_COLOR.

IMREAD_COLOR

Devolve:

Tipo Descrição
ndarray

A imagem lida.

Código fonte em 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)

Escreve uma imagem num ficheiro.

Parâmetros:

Nome Tipo Descrição Predefinição
filename str

Caminho para o ficheiro a escrever.

necessário
img ndarray

Imagem para escrever.

necessário
params list of ints

Parâmetros adicionais. Vê a documentação do OpenCV.

None

Devolve:

Tipo Descrição
bool

Verdadeiro se o ficheiro foi escrito, Falso caso contrário.

Código fonte em 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)

Exibe uma imagem na janela especificada.

Parâmetros:

Nome Tipo Descrição Predefinição
winname str

Nome da janela.

necessário
mat ndarray

Imagem a ser mostrada.

necessário
Código fonte em 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 usa dill para serializar funções lambda onde pickle não o faz, adicionando robustez com 3 tentativas e afastamento exponencial em caso de falha no salvamento.

Parâmetros:

Nome Tipo Descrição Predefinição
*args tuple

Argumentos posicionais para passar para torch.save.

()
use_dill bool

Tenta usar o dill para serialização, se disponível. Usa o valor padrão True.

True
**kwargs any

Argumentos de palavras-chave para passar para torch.save.

{}
Código fonte em 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





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