Zum Inhalt springen

Referenz für ultralytics/models/sam/model.py

Hinweis

Diese Datei ist verfügbar unter https://github.com/ultralytics/ ultralytics/blob/main/ ultralytics/models/ sam/model .py. Wenn du ein Problem entdeckst, hilf bitte mit, es zu beheben, indem du einen Pull Request 🛠️ einreichst. Vielen Dank 🙏!



ultralytics.models.sam.model.SAM

Basen: Model

SAM (Segment Anything Model) Schnittstellenklasse.

SAM wurde für die Echtzeit-Segmentierung von Bildern mit Prompts entwickelt. Sie kann mit einer Vielzahl von Eingabeaufforderungen verwendet werden, wie Bounding Boxes, Punkten oder Labels verwendet werden. Das Modell ist in der Lage, eine Zero-Shot-Leistung zu erbringen und wurde mit dem SA-1B Datensatz trainiert.

Quellcode 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

Stellt eine Zuordnung zwischen der Aufgabe "Segment" und dem entsprechenden "Predictor" her.

Retouren:

Typ Beschreibung
dict

Ein Wörterbuch, das die Aufgabe "Segment" dem entsprechenden "Predictor" zuordnet.

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

Alias für die Methode "predict".

Parameter:

Name Typ Beschreibung Standard
source str

Pfad zur Bild- oder Videodatei, oder ein PIL.Image-Objekt, oder ein numpy.ndarray-Objekt.

None
stream bool

Bei True wird Echtzeit-Streaming aktiviert. Der Standardwert ist False.

False
bboxes list

Liste der Bounding-Box-Koordinaten für die prompte Segmentierung. Der Standardwert ist Keine.

None
points list

Liste der Punkte für die Aufforderung zur Segmentierung. Der Standardwert ist Keine.

None
labels list

Liste der Beschriftungen für die Aufforderung zur Segmentierung. Der Standardwert ist Keine.

None

Retouren:

Typ Beschreibung
list

Die Modellvorhersagen.

Quellcode 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')

Initialisiert das Modell SAM mit einer vortrainierten Modelldatei.

Parameter:

Name Typ Beschreibung Standard
model str

Pfad zu der vortrainierten SAM Modelldatei. Die Datei sollte eine .pt oder .pth Erweiterung haben.

'sam_b.pt'

Erhöht:

Typ Beschreibung
NotImplementedError

Wenn die Dateierweiterung des Modells nicht .pt oder .pth lautet.

Quellcode 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)

Protokolliert Informationen über das Modell SAM .

Parameter:

Name Typ Beschreibung Standard
detailed bool

Bei True werden detaillierte Informationen über das Modell angezeigt. Der Standardwert ist False.

False
verbose bool

Wenn True, werden Informationen auf der Konsole angezeigt. Der Standardwert ist True.

True

Retouren:

Typ Beschreibung
tuple

Ein Tupel mit den Informationen über das Modell.

Quellcode 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)

Führt eine Segmentierungsvorhersage für die angegebene Bild- oder Videoquelle durch.

Parameter:

Name Typ Beschreibung Standard
source str

Pfad zur Bild- oder Videodatei, oder ein PIL.Image-Objekt, oder ein numpy.ndarray-Objekt.

erforderlich
stream bool

Bei True wird Echtzeit-Streaming aktiviert. Der Standardwert ist False.

False
bboxes list

Liste der Bounding-Box-Koordinaten für die prompte Segmentierung. Der Standardwert ist Keine.

None
points list

Liste der Punkte für die Aufforderung zur Segmentierung. Der Standardwert ist Keine.

None
labels list

Liste der Beschriftungen für die Aufforderung zur Segmentierung. Der Standardwert ist Keine.

None

Retouren:

Typ Beschreibung
list

Die Modellvorhersagen.

Quellcode 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)





Erstellt am 2023-11-12, Aktualisiert am 2024-05-18
Autoren: glenn-jocher (4), Burhan-Q (1)