Vai al contenuto

Riferimento per ultralytics/models/sam/model.py

Nota

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



ultralytics.models.sam.model.SAM

Basi: Model

SAM (Segment Anything Model) classe di interfaccia.

SAM è stato progettato per la segmentazione di immagini in tempo reale. Può essere utilizzato con una varietà di suggerimenti, come ad esempio bounding box, punti o etichette. Il modello è in grado di garantire prestazioni a zero scatti ed è stato addestrato sul dataset SA-1B. e viene addestrato sul set di dati SA-1B.

Codice sorgente in ultralytics/models/sam/model.py
class SAM(Model):
    """
    SAM (Segment Anything Model) interface class.

    SAM is designed for promptable real-time image segmentation. It can be used with a variety of prompts such as
    bounding boxes, points, or labels. The model has capabilities for zero-shot performance and is trained on the SA-1B
    dataset.
    """

    def __init__(self, model="sam_b.pt") -> None:
        """
        Initializes the SAM model with a pre-trained model file.

        Args:
            model (str): Path to the pre-trained SAM model file. File should have a .pt or .pth extension.

        Raises:
            NotImplementedError: If the model file extension is not .pt or .pth.
        """
        if model and Path(model).suffix not in {".pt", ".pth"}:
            raise NotImplementedError("SAM prediction requires pre-trained *.pt or *.pth model.")
        super().__init__(model=model, task="segment")

    def _load(self, weights: str, task=None):
        """
        Loads the specified weights into the SAM model.

        Args:
            weights (str): Path to the weights file.
            task (str, optional): Task name. Defaults to None.
        """
        self.model = build_sam(weights)

    def predict(self, source, stream=False, bboxes=None, points=None, labels=None, **kwargs):
        """
        Performs segmentation prediction on the given image or video source.

        Args:
            source (str): Path to the image or video file, or a PIL.Image object, or a numpy.ndarray object.
            stream (bool, optional): If True, enables real-time streaming. Defaults to False.
            bboxes (list, optional): List of bounding box coordinates for prompted segmentation. Defaults to None.
            points (list, optional): List of points for prompted segmentation. Defaults to None.
            labels (list, optional): List of labels for prompted segmentation. Defaults to None.

        Returns:
            (list): The model predictions.
        """
        overrides = dict(conf=0.25, task="segment", mode="predict", imgsz=1024)
        kwargs.update(overrides)
        prompts = dict(bboxes=bboxes, points=points, labels=labels)
        return super().predict(source, stream, prompts=prompts, **kwargs)

    def __call__(self, source=None, stream=False, bboxes=None, points=None, labels=None, **kwargs):
        """
        Alias for the 'predict' method.

        Args:
            source (str): Path to the image or video file, or a PIL.Image object, or a numpy.ndarray object.
            stream (bool, optional): If True, enables real-time streaming. Defaults to False.
            bboxes (list, optional): List of bounding box coordinates for prompted segmentation. Defaults to None.
            points (list, optional): List of points for prompted segmentation. Defaults to None.
            labels (list, optional): List of labels for prompted segmentation. Defaults to None.

        Returns:
            (list): The model predictions.
        """
        return self.predict(source, stream, bboxes, points, labels, **kwargs)

    def info(self, detailed=False, verbose=True):
        """
        Logs information about the SAM model.

        Args:
            detailed (bool, optional): If True, displays detailed information about the model. Defaults to False.
            verbose (bool, optional): If True, displays information on the console. Defaults to True.

        Returns:
            (tuple): A tuple containing the model's information.
        """
        return model_info(self.model, detailed=detailed, verbose=verbose)

    @property
    def task_map(self):
        """
        Provides a mapping from the 'segment' task to its corresponding 'Predictor'.

        Returns:
            (dict): A dictionary mapping the 'segment' task to its corresponding 'Predictor'.
        """
        return {"segment": {"predictor": Predictor}}

task_map property

Fornisce una mappatura dal compito "segmento" al corrispondente "predittore".

Restituzione:

Tipo Descrizione
dict

Un dizionario che mappa il compito "segmento" con il corrispondente "Predittore".

__call__(source=None, stream=False, bboxes=None, points=None, labels=None, **kwargs)

Alias per il metodo 'predict'.

Parametri:

Nome Tipo Descrizione Predefinito
source str

Percorso del file immagine o video, o un oggetto PIL.Image, o un oggetto numpy.ndarray.

None
stream bool

Se Vero, attiva lo streaming in tempo reale. L'impostazione predefinita è Falso.

False
bboxes list

Elenco delle coordinate del rettangolo di selezione per la segmentazione richiesta. Il valore predefinito è Nessuno.

None
points list

Elenco di punti per la segmentazione richiesta. Il valore predefinito è Nessuno.

None
labels list

Elenco di etichette per la segmentazione richiesta. Il valore predefinito è Nessuno.

None

Restituzione:

Tipo Descrizione
list

Le previsioni del modello.

Codice sorgente in ultralytics/models/sam/model.py
def __call__(self, source=None, stream=False, bboxes=None, points=None, labels=None, **kwargs):
    """
    Alias for the 'predict' method.

    Args:
        source (str): Path to the image or video file, or a PIL.Image object, or a numpy.ndarray object.
        stream (bool, optional): If True, enables real-time streaming. Defaults to False.
        bboxes (list, optional): List of bounding box coordinates for prompted segmentation. Defaults to None.
        points (list, optional): List of points for prompted segmentation. Defaults to None.
        labels (list, optional): List of labels for prompted segmentation. Defaults to None.

    Returns:
        (list): The model predictions.
    """
    return self.predict(source, stream, bboxes, points, labels, **kwargs)

__init__(model='sam_b.pt')

Inizializza il modello SAM con un file di modello pre-addestrato.

Parametri:

Nome Tipo Descrizione Predefinito
model str

Percorso del file del modello pre-addestrato SAM . Il file deve avere un'estensione .pt o .pth.

'sam_b.pt'

Aumenta:

Tipo Descrizione
NotImplementedError

Se l'estensione del file del modello non è .pt o .pth.

Codice sorgente in ultralytics/models/sam/model.py
def __init__(self, model="sam_b.pt") -> None:
    """
    Initializes the SAM model with a pre-trained model file.

    Args:
        model (str): Path to the pre-trained SAM model file. File should have a .pt or .pth extension.

    Raises:
        NotImplementedError: If the model file extension is not .pt or .pth.
    """
    if model and Path(model).suffix not in {".pt", ".pth"}:
        raise NotImplementedError("SAM prediction requires pre-trained *.pt or *.pth model.")
    super().__init__(model=model, task="segment")

info(detailed=False, verbose=True)

Registra le informazioni sul modello SAM .

Parametri:

Nome Tipo Descrizione Predefinito
detailed bool

Se Vero, visualizza informazioni dettagliate sul modello. L'impostazione predefinita è False.

False
verbose bool

Se Vero, visualizza le informazioni sulla console. Il valore predefinito è Vero.

True

Restituzione:

Tipo Descrizione
tuple

Una tupla contenente le informazioni del modello.

Codice sorgente in ultralytics/models/sam/model.py
def info(self, detailed=False, verbose=True):
    """
    Logs information about the SAM model.

    Args:
        detailed (bool, optional): If True, displays detailed information about the model. Defaults to False.
        verbose (bool, optional): If True, displays information on the console. Defaults to True.

    Returns:
        (tuple): A tuple containing the model's information.
    """
    return model_info(self.model, detailed=detailed, verbose=verbose)

predict(source, stream=False, bboxes=None, points=None, labels=None, **kwargs)

Esegue la previsione della segmentazione sull'immagine o sulla sorgente video data.

Parametri:

Nome Tipo Descrizione Predefinito
source str

Percorso del file immagine o video, o un oggetto PIL.Image, o un oggetto numpy.ndarray.

richiesto
stream bool

Se Vero, attiva lo streaming in tempo reale. L'impostazione predefinita è Falso.

False
bboxes list

Elenco delle coordinate del rettangolo di selezione per la segmentazione richiesta. Il valore predefinito è Nessuno.

None
points list

Elenco di punti per la segmentazione richiesta. Il valore predefinito è Nessuno.

None
labels list

Elenco di etichette per la segmentazione richiesta. Il valore predefinito è Nessuno.

None

Restituzione:

Tipo Descrizione
list

Le previsioni del modello.

Codice sorgente in ultralytics/models/sam/model.py
def predict(self, source, stream=False, bboxes=None, points=None, labels=None, **kwargs):
    """
    Performs segmentation prediction on the given image or video source.

    Args:
        source (str): Path to the image or video file, or a PIL.Image object, or a numpy.ndarray object.
        stream (bool, optional): If True, enables real-time streaming. Defaults to False.
        bboxes (list, optional): List of bounding box coordinates for prompted segmentation. Defaults to None.
        points (list, optional): List of points for prompted segmentation. Defaults to None.
        labels (list, optional): List of labels for prompted segmentation. Defaults to None.

    Returns:
        (list): The model predictions.
    """
    overrides = dict(conf=0.25, task="segment", mode="predict", imgsz=1024)
    kwargs.update(overrides)
    prompts = dict(bboxes=bboxes, points=points, labels=labels)
    return super().predict(source, stream, prompts=prompts, **kwargs)





Creato 2023-11-12, Aggiornato 2024-05-18
Autori: glenn-jocher (4), Burhan-Q (1)