メインコンテンツへスキップ
見出し画像

なんでもセグメンテーション:SAM3

    SAM3について

    2025年11月19日、MetaがリリースしたSegment Anything Model 3(SAM 3)
    確か、SAM2は対象(オブジェクト)をクリックするとそれをセグメンテーションしてくれるモデルでした。
    今回は、テキスト(プロンプト)で対象を指定できるようです。
    自動検出の他、動画での追跡(トラッキング)もできるみたいです。

    SAM3 は、画像とテキストを同時に扱い、テキストで指定された対象を検出・識別し、その領域を高精度にセグメンテーションすることを目的としたモデルである。

    ChatGPT解説

    MetaのSAM3ホームページ

    オープンソースではあるのですが、なかなか動かすのが大変そうです。

    私もなるべく簡単な方法で試してみたのですが、それなりに面倒でした。
    環境:Mac(M2Max 96GB)、Anaconda + Jupyter lab
    ってのもよくなかったかも。

    まあ、でも無事になんとか動かせましたので、試したい方は参考にしてくださいませ。

    Ultralyticsから使う

    1.ultralyticsのインストール

    !pip install -U ultralytics

    2.モデルをダウンロード

    モデルをダウンロードする必要があります。
    SAM2までは、自動ダウンロードができました。
    これを実行するだけです。

    from ultralytics import SAM
    
    # Load a model
    model = SAM("sam2.1_b.pt")
    
    # Display model information (optional)
    model.info()

    こちらが参考です。

    SAM3は手動でモデルをダウンロードしなければなりません。
    以下に書いてあるのですが、分かりにくかったので補足します。

    上の記事に以下の記載があります。

    他のUltralytics 異なり、SAM は重み付けを行う(sam3.pt) は 自動的にダウンロードされないまず、モデル重みへのアクセスを Hugging Face3モデルページ そして、承認されたら、ダウンロードしてください sam3.pt ファイルダウンロードしたファイルを配置してください sam3.pt 作業ディレクトリ内のファイルを指定するか、モデルを読み込む際に完全なパスを指定してください。

    Hugging Faceモデルページにリンクからアクセスし、必要事項を記入しsubmitします。承認されると以下のようなメールが届きます。
    (もしかしたらHuggingFaceへのアカウントの作成が必要かもしれません。)

    画像

    上記引用の「 sam3.pt ファイル」の部分をクリックするとダウンロードできるのですが、分かりにくかったら、こちらからダウンロードできます。(コピペして使ってください。)
    https://huggingface.co/facebook/sam3/resolve/main/sam3.pt

    3.SAM3を動かす

    ダウンロードしたsam3.ptファイルを実行ファイルと同じディレクトリにおいて以下のコードを実行します。Jupyter labのipynbファイルを想定しています。

    from ultralytics.models.sam import SAM3SemanticPredictor
    
    # Initialize predictor with configuration
    overrides = dict(
        conf=0.25,
        task="segment",
        mode="predict",
        model="sam3.pt",
        half=True,  # Use FP16 for faster inference
        save=True,
    )
    predictor = SAM3SemanticPredictor(overrides=overrides)
    
    # Set image once for multiple queries
    predictor.set_image("images/bus.jpg")

    bus.jpgはultralyticsの毎度のサンプル画像です。imagesというフォルダーに置いています。コードでフォルダーを指定して読み込めるようにしてください。

    画像
    bus.jpg

    プロンプトで対象を指定すれば、セグメンテーション結果を確認できます。
    結果は/runs/segment/predict??などというディレクトリに保存されます。保存先は実行時に表示されますので安心してください。

    結果① 「人(person)」、「バス(bus)」、「メガネ(glasses)」を指定

    results = predictor(text=["person", "bus", "glasses"])
    画像
    bus.jpg

    結果② 「赤い服を着ている人(person with red cloth)」、「青い服を着ている人(person with blue cloth)」を指定

    results = predictor(text=["person with red cloth", "person with blue cloth"])
    画像
    bus.jpg

    HuggingFaceからモデルダウンロードして使う

    1.HuggingFaceの準備

    こちらは、ちょっとした準備が必要です。結構めんどう。
    モデルダウンロードのため、まずHuggingFaceのアカウントを作成する必要があります。

    次にトークンを取得します。
    トークンの取得方法は以下です。

    1. https://huggingface.co/settings/tokens

    2. New token

    3. Role: read(通常はこれで十分)

    4. 生成された hf_xxxxxxxxx をコピー

    トークンの渡し方は以下の通り

    !hf auth login --token hf_xxxxxxxxx

    ログインの確認方法

    !hf auth whoami

    トークンの保存場所

    ~/.cache/huggingface/token

    通常は、上記は不要でJupyter labで実行する際にトークンを貼り付けるのですが、今回はそれができませんでした。
    以下に対応方法を記します。

    2.モデルをダウンロード

    transformersのインストール

    !pip install -U transformers

    場合によっては以下が必要かもしれません。この場合は仮想環境で実行することをお勧めします。(確認中)

    !pip install git+https://github.com/huggingface/transformers.git

    Jupyter labのセル上で以下を実行すると本来はコレでモデルがダウンロードされるはずなのですが、

    # Load model directly
    from transformers import AutoTokenizer, AutoModel
    
    tokenizer = AutoTokenizer.from_pretrained("facebook/sam3")
    model = AutoModel.from_pretrained("facebook/sam3")

    以下のメッセージが出ます。
    ”IOPub message rate exceeded. The Jupyter server will temporarily stop sending output to the client in order to avoid crashing it. To change this limit, set the config variable `--ServerApp.iopub_msg_rate_limit`. Current values: ServerApp.iopub_msg_rate_limit=1000.0 (msgs/sec) ServerApp.rate_limit_window=3.0 (secs)”

    なんやねん、コレ?とChatGPTさんにお尋ねすると、
    『これは Jupyter が「出力が多すぎて危険」と判断して遮断した状態です。
    エラーではなく 安全装置です。』
    とのこと。

    解決策は色々あるようなのですが、ターミナルで実行するのがいいみたいです。
    まずは、Hugging Faceトークンの入力の必要がありますね。
    前述した 1.HuggingFaceの準備 を参考にしてください。

    notebook ではなくターミナルで先にDL

    python - << 'EOF'
    from transformers import AutoTokenizer, AutoModel
    AutoTokenizer.from_pretrained("facebook/sam3")
    AutoModel.from_pretrained("facebook/sam3")
    EOF

    👉 一度DLされれば notebook では再発しません

    ここで気をつけなければならないのは、モデルのダウンロード先ですが、Mac(またはLinux)ですと以下になるとのこと。

    ~/.cache/huggingface/

    ここにsnapshotsなるものが保存されます。
    これはモデルを読み込む時に必要です。
    読み込み方は後ほど。

    3.SAM3を動かす

    以上で準備ができました。
    では、ダウンロードしたモデルを読み込み、入力画像を指定して結果を出力させてみます。
    https://huggingface.co/facebook/sam3 のコードを少し改良します。

    from transformers import Sam3Processor, Sam3Model
    import torch
    from PIL import Image
    import requests
    
    device = "cuda" if torch.cuda.is_available() else "cpu"
    
    #model = Sam3Model.from_pretrained("facebook/sam3").to(device)
    #processor = Sam3Processor.from_pretrained("facebook/sam3")
    
    model = Sam3Model.from_pretrained(
        "facebook/sam3",
        cache_dir="/Users/username/.cache/huggingface/models--facebook--sam3/sanpshots/<hash>"
    )
    processor = Sam3Processor.from_pretrained(
        "facebook/sam3",
        cache_dir="/Users/username/.cache/huggingface/models--facebook--sam3/snapshots/<hash>"
    )
    
    
    # Load image
    image_url = "http://images.cocodataset.org/val2017/000000077595.jpg"
    image = Image.open(requests.get(image_url, stream=True).raw).convert("RGB")
    
    # Segment using text prompt
    inputs = processor(images=image, text="ear", return_tensors="pt").to(device)
    
    with torch.no_grad():
        outputs = model(**inputs)
    
    # Post-process results
    results = processor.post_process_instance_segmentation(
        outputs,
        threshold=0.5,
        mask_threshold=0.5,
        target_sizes=inputs.get("original_sizes").tolist()
    )[0]
    
    print(f"Found {len(results['masks'])} objects")
    # Results contain:
    # - masks: Binary masks resized to original image size
    # - boxes: Bounding boxes in absolute pixel coordinates (xyxy format)
    # - scores: Confidence scores

    注意点:

    device = "cuda" if torch.cuda.is_available() else "cpu"

    Mac(Apple Silicon)のGPUは"mps"ですが、これはダメでした。なのでこのままで"cpu"で実行します。

    cache_dir="/Users/username/.cache/huggingface/models--facebook--sam3/snapshots/<hash>"

    これはモデルの保存先です。Macの場合はこんな感じかと。絶対パスの方が確実です。usernameはご自身のものを、<hash>はsnapshotsの下を確認してください。

    image_url = "http://images.cocodataset.org/val2017/000000077595.jpg"

    サンプル画像は猫でした。

    画像
    http://images.cocodataset.org/val2017/000000077595.jpg

    結果のresultsの中身は"masks"(セグメンテーション)、"boxes"(バウンディングボックス)、"scores"(確信度)ですので、

    # Results contain:
    # - masks: Binary masks resized to original image size
    # - boxes: Bounding boxes in absolute pixel coordinates (xyxy format)
    # - scores: Confidence scores

    これを確認してみます。

    import torch
    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.patches as patches
    
    #画像データ変換
    if hasattr(image, "numpy"):
        img = image.numpy()
    elif hasattr(image, "size"):  # PIL
        img = np.array(image)
    else:
        img = image
    
    #resultsの中身
    scores = results["scores"].cpu().numpy()
    boxes  = results["boxes"].cpu().numpy()
    masks  = results["masks"].cpu().numpy()  # (N, H, W)
    
    #描画と保存
    fig, ax = plt.subplots(1, figsize=(8, 8))
    ax.imshow(img)
    
    for i, (score, box, mask) in enumerate(zip(scores, boxes, masks)):
        # --- Bounding Box ---
        x1, y1, x2, y2 = box
        rect = patches.Rectangle(
            (x1, y1),
            x2 - x1,
            y2 - y1,
            linewidth=2,
            edgecolor='red',
            facecolor='none'
        )
        ax.add_patch(rect)
    
        # score 表示
        ax.text(
            x1, y1 - 5,
            f"{score:.2f}",
            color="red",
            fontsize=10,
            backgroundcolor="white"
        )
    
        # --- Mask ---
        colored_mask = np.zeros((*mask.shape, 4))
        colored_mask[..., 0] = 1.0        # 赤
        colored_mask[..., 3] = mask * 0.4 # 透明度
        ax.imshow(colored_mask)
    
    ax.axis("off")
    plt.savefig("images/cat.jpg")
    plt.show()
    画像

    https://huggingface.co/facebook/sam3 のコードを試してみます。

    import numpy as np
    import matplotlib
    
    def overlay_masks(image, masks):
        image = image.convert("RGBA")
        masks = 255 * masks.cpu().numpy().astype(np.uint8)
        
        n_masks = masks.shape[0]
        cmap = matplotlib.colormaps.get_cmap("rainbow").resampled(n_masks)
        colors = [
            tuple(int(c * 255) for c in cmap(i)[:3])
            for i in range(n_masks)
        ]
    
        for mask, color in zip(masks, colors):
            mask = Image.fromarray(mask)
            overlay = Image.new("RGBA", image.size, color + (0,))
            alpha = mask.point(lambda v: int(v * 0.5))
            overlay.putalpha(alpha)
            image = Image.alpha_composite(image, overlay)
        return image
    
    overlay_masks(image, results["masks"])
    画像

    今回のプロンプトは、"ear"(耳)だけ。

    # Segment using text prompt
    inputs = processor(images=image, text="ear", return_tensors="pt").to(device)

    じゃあ、猫だけでなく人間いたらどうなるのか?
    試したのがこちら!

    画像

    猫、人間の耳を同時に認識!
    ゾウの耳、とかでもできるのかな???

    おまけ!

    結構めんどくさいじゃないか、ばかやろう!
    と言うわけで、最近流行りのMEMEで遊んでみました。

    ① prompt : sunglasses(グラサン🕶️)

    画像

    右の人(誰でしたっけ?)がサングラスしているの、私分かりませんでしたよ!

    ② pronput : gun(銃🔫)

    画像

    ③ prompt : person with white cloth(白い服を着ている人)

    画像

    ④ prompt : person with gun(銃を持ってる人)

    画像

    これはうまくいってませんね。
    ちなみに③、④はultralyticsの出力になります。

    参考

    ドキュメント

    モデル構造

    print(model)で、モデル構造が出力されますが、

    # huggingface transformersの場合
    print(model)

    ChatGPTにお願いして図にしてもらいました。

    ┌─────────────────────────────────────────────┐
    │                  Input                      │
    │  ┌──────────────┐   ┌──────────────┐        │
    │  │   Image      │   │   Text       │        │
    │  └──────┬───────┘   └──────┬───────┘        │
    └─────────┼──────────────────┼────────────────┘
              │                  │
              ▼                  ▼
    ┌────────────────┐   ┌────────────────────────┐
    │ Vision Encoder │   │     Text Encoder       │
    │  (ViT + FPN)   │   │  (CLIP Transformer)    │
    │                │   │                        │
    │ ViT (32 layers)│   │ 24-layer Transformer   │
    │ + RoPE Attn    │   │ → 512-d projection     │
    │ + FPN multi    │   └──────────┬─────────────┘
    │   scale feats  │              │
    └───────┬────────┘              │
            │                       │
            ▼                       ▼
    ┌──────────────────────────────────────────────┐
    │              Geometry Encoder                │
    │  (Boxes / Points / Prompts Encoding)         │
    │                                              │
    │  - Box embedding                             │
    │  - Positional encoding                       │
    │  - Self + Cross Attention (3 layers)         │
    └───────────────┬──────────────────────────────┘
                    │
                    ▼
    ┌──────────────────────────────────────────────┐
    │               DETR Encoder                   │
    │         (Vision Feature Encoding)            │
    │  - 6-layer Transformer                       │
    │  - Self + Cross Attention                    │
    └───────────────┬──────────────────────────────┘
                    │
                    ▼
    ┌──────────────────────────────────────────────┐
    │               DETR Decoder                   │
    │        (Query-based Object Reasoning)        │
    │                                              │
    │  Queries (200)                               │
    │  ├─ Self Attention                           │
    │  ├─ Text Cross Attention                     │
    │  ├─ Vision Cross Attention                   │
    │  ├─ Box Head → Bounding Boxes                │
    │  ├─ Presence Head → Objectness               │
    │  └─ Ref Point Head                           │
    └───────────────┬──────────────────────────────┘
                    │
                    ▼
    ┌──────────────────────────────────────────────┐
    │                Mask Decoder                  │
    │         (Segmentation Head)                  │
    │                                              │
    │  - Pixel Decoder (Conv + GN)                 │
    │  - Prompt Cross Attention                    │
    │  - Instance Projection                       │
    │  - Semantic Projection                       │
    │                                              │
    │  → Segmentation Masks                        │
    └───────────────┬──────────────────────────────┘
                    │
                    ▼
    ┌──────────────────────────────────────────────┐
    │         Dot Product Scoring                  │
    │  (Text ↔ Query Matching)                     │
    │                                              │
    │  - Text MLP                                  │
    │  - Query Projection                          │
    │  → Scores                                    │
    └──────────────────────────────────────────────┘
    
    Outputs:
    - Bounding Boxes
    - Masks
    - Scores
    画像
    各モジュールの説明

    SAM3モデルとは、Sam3Model = SAM + DETR + CLIP の融合です。

    SAM3 は、ViT ベースの視覚エンコーディング、CLIP によるテキスト埋め込み、DETR 形式のオブジェクトクエリ、そして SAM 風のマスクデコーダを統合した、テキスト指示型インスタンスセグメンテーションのためのマルチモーダルアーキテクチャである。

    ChatGPT解説

    SAM2との比較

    SAM2
    ─────────────────────────────────────────────
    Input
     ┌──────────────┐
     │ Image        │
     └──────┬───────┘
            ▼
    ┌────────────────────────────┐
    │ Vision Encoder (ViT)       │
    │  - Image Embedding         │
    │  - High-res features       │
    └──────────────┬─────────────┘
                   ▼
    ┌────────────────────────────┐
    │ Prompt Encoder             │
    │  - Points / Boxes / Mask   │
    │  - Positional Encoding     │
    └──────────────┬─────────────┘
                   ▼
    ┌────────────────────────────┐
    │ Mask Decoder               │
    │  - Cross Attention         │
    │  - MLP + Conv              │
    └──────────────┬─────────────┘
                   ▼
    Output
      → Segmentation Mask
    SAM3
    ────────────────────────────────────────────────────────────────────
    Input
     ┌──────────────┐    ┌──────────────┐
     │ Image        │    │ Text         │
     └──────┬───────┘    └──────┬───────┘
            │                   │
            ▼                   ▼
    ┌──────────────────┐  ┌────────────────────────┐
    │ Vision Encoder   │  │ Text Encoder (CLIP)    │
    │  ViT + FPN       │  │ 24-layer Transformer   │
    │  Multi-scale     │  │ Semantic Embedding     │
    └────────┬─────────┘  └──────────┬─────────────┘
             │                       │
             ▼                       ▼
    ┌────────────────────────────────────────────────┐
    │ Geometry Encoder                               │
    │  - Boxes / Prompts / Position Encoding         │
    │  - Self + Cross Attention                      │
    └────────────────────┬───────────────────────────┘
                         ▼
    ┌────────────────────────────────────────────────┐
    │ DETR Encoder                                   │
    │  - Vision feature reasoning                    │
    └────────────────────┬───────────────────────────┘
                         ▼
    ┌────────────────────────────────────────────────┐
    │ DETR Decoder                                   │
    │  - Object Queries (200)                        │
    │  - Vision × Text Cross Attention               │
    │  - Box / Presence Prediction                   │
    └────────────────────┬───────────────────────────┘
                         ▼
    ┌────────────────────────────────────────────────┐
    │ Mask Decoder                                   │
    │  - Pixel Decoder                               │
    │  - Prompt Cross Attention                      │
    │  - Instance / Semantic Masks                   │
    └────────────────────┬───────────────────────────┘
                         ▼
    ┌────────────────────────────────────────────────┐
    │ Dot Product Scoring                            │
    │  - Text ↔ Query Matching                       │
    └────────────────────────────────────────────────┘
    
    Outputs
     → Boxes + Masks + Scores
    画像
    SAM2 vs SAM3 比較
     
     
    医療AI/モビリティAI/AI・Python教材制作/元コンサル 日本メディカルAI学会公認資格 大規模言語モデル2024(東大),AI-Quest2020修了 国内AIデータ分析コンペに参加:Nishika Aランク(金1銀1銅2)SIGNATE Master称号(金1銅3)

    あなたへのおすすめ