samgeo3-lab 사용법

segment-geospatial의 SamGeo3 백엔드로 SAM 3 / SAM 3.1 텍스트 프롬프트 세그멘테이션을 실험하는 독립 프로젝트 가이드입니다.

Python 3.12 CUDA / RTX GPU backend=meta facebook/sam3.1 Windows

1. 개요 · 범위

프로젝트 경로: D:\MYCLAUDE_PROJECT\samgeo3-lab

항목내용
패키지 segment-geospatial (PyPI) — 클래스 SamGeo3
하는 일 설치 검증, 단일 이미지 텍스트 세그멘테이션, 마스크/시각화 저장
하지 않는 일 railway-client / sam31server 통합, 철도 후처리, REST API, AnyLabeling/YOLO 파이프라인
환경 원칙 이 폴더의 .venv만 사용. 다른 SAM 서버 env와 섞지 않음
이미 구성된 경우 설치 단계는 건너뛰고 §5 실행 커맨드부터 진행하면 됩니다.

2. 폴더 구조

samgeo3-lab/
  README.md
  docs/usage.html          ← 이 문서
  requirements.txt
  pyproject.toml
  scripts/
    check_install.py       # GPU / import / (옵션) 모델 로드 확인
    text_segment.py        # 단일 이미지 텍스트 세그멘테이션
  data/                    # 입력 이미지
  output/                  # 마스크 · 점수 · 오버레이 결과
  .venv/                   # 독립 가상환경

3. 설치 (Windows + GPU)

PowerShell에서 프로젝트 루트로 이동한 뒤 순서대로 실행합니다.

cd D:\MYCLAUDE_PROJECT\samgeo3-lab

# 1) 독립 venv (Python 3.12)
uv venv --python 3.12 .venv
.\.venv\Scripts\Activate.ps1

# 2) CUDA PyTorch 먼저 (CPU wheel 덮어쓰기 방지)
uv pip install torch torchvision --index-url https://download.pytorch.org/whl/cu121

# 3) SamGeo3 extras only (api / all 설치 금지)
uv pip install "segment-geospatial[samgeo3]>=1.4.1" matplotlib

# 4) Windows: sam3 import에 필요
uv pip install "triton-windows>=3.3.0.post19"

# 5) (선택) 노트북
uv pip install ipykernel jupyterlab
주의 triton-windows가 없으면 import sam3 가 실패합니다. segment-geospatial[samgeo3] 설치 후에도 반드시 확인하세요.

대안: pixi (공식 권장)

conda/pixi 환경이 가능하면 PyTorch·CUDA·SAM3 의존성 해결에 유리합니다.
samgeo.gishub.org — Install with pixi

4. Hugging Face · 체크포인트

  1. 모델 접근 승인
    facebook/sam3.1 (및 필요 시 sam3) 폼 제출 후 승인
  2. 인증
    hf auth login 또는 기존 토큰 파일 ~/.cache/huggingface/token 유지
  3. (선택) 로컬 체크포인트
    $env:SAM3_CHECKPOINT_PATH = "C:\path\to\sam3.1_multiplex.pt"
    스크립트에서는 --checkpoint 로도 지정 가능합니다.
백엔드 제약
  • backend="meta"facebook/sam3, facebook/sam3.1 (배치·인터랙티브 풍부)
  • backend="transformers"facebook/sam3 만. sam3.1은 meta 전용

5. 실행 커맨드

매번 가상환경을 활성화한 뒤 실행합니다.

cd D:\MYCLAUDE_PROJECT\samgeo3-lab
.\.venv\Scripts\Activate.ps1

# A) 패키지 / GPU / import 확인
python scripts\check_install.py

# B) 모델 로드까지 확인 (HF 캐시 또는 다운로드)
python scripts\check_install.py --load-model

# C) 샘플 이미지 텍스트 세그멘테이션 (기본 prompt=person, confidence=0.3)
python scripts\text_segment.py
python scripts\text_segment.py --prompt person --confidence 0.3

# D) 자체 이미지
python scripts\text_segment.py --image data\my.jpg --prompt building --min-size 100

권장 검증 순서

  1. check_install.py — CUDA + imports
  2. check_install.py --load-model — 가중치 로드
  3. text_segment.py — 마스크 저장 확인
  4. --confidence / --min-size 튜닝 후 실데이터 실험

6. text_segment.py 옵션

옵션기본값설명
--image data/test_image.jpg 입력 이미지 경로 (없으면 샘플 자동 다운로드)
--prompt person 텍스트 프롬프트 (예: building, tree, car)
--model-id facebook/sam3.1 HF 모델 ID
--backend meta meta | transformers
--confidence 0.3 confidence threshold. 0.5면 마스크 0개일 수 있음
--mask-threshold 0.5 transformers 후처리용 마스크 threshold
--resolution 1008 meta 입력 해상도
--min-size / --max-size 0 / 없음 마스크 픽셀 면적 필터
--device 자동 cuda | cpu
--checkpoint 환경변수 또는 없음 로컬 .pt 경로
--output-dir output/ 결과 저장 디렉터리
--no-viz off 오버레이 PNG 생략 (마스크는 저장)

check_install.py 옵션

python scripts\check_install.py
python scripts\check_install.py --load-model
python scripts\check_install.py --load-model --model-id facebook/sam3.1 --device cuda

6b. 멀티 프롬프트 (Grok + Gemini 병합)

드론 정사 장면 분석 결과를 합친 프롬프트 JSON과 일괄 실행 스크립트입니다. 모델·이미지를 1회만 로드한 뒤 프롬프트를 순차 generate_masks 합니다.

경로설명
prompts/dji_20260306_0016.json tier A~D + compact, 장면 노트(KO), 권장 confidence
scripts/multi_prompt_segment.py 멀티 프롬프트 러너 + summary.json
data/DJI_20260306100802_0016.JPG 기본 입력 (없으면 sample 경로 fallback)
python scripts\multi_prompt_segment.py --list-only --tier compact
python scripts\multi_prompt_segment.py --tier compact --confidence 0.3
python scripts\multi_prompt_segment.py --tier A_high
python scripts\multi_prompt_segment.py --tier all --confidence 0.25
python scripts\multi_prompt_segment.py --prompts "railway track,building,solar panel"

tier: compact | gap | gap2 | gap2_core | improved | all | A_high | B_facility | C_detail | D_rail_domain

결과 디렉터리: output/<이미지stem>_<tier>/ — 프롬프트별 mask/ann + summary.json

DJI 정사 — 단일 프롬프트 예시 (실제 경로)

cd D:\MYCLAUDE_PROJECT\samgeo3-lab
.\.venv\Scripts\Activate.ps1

$img = "data\DJI_20260306100802_0016.JPG"
$out = "output\dji_0016_analysis"

python scripts\text_segment.py --image $img --prompt "solar panel" --confidence 0.3 --output-dir $out
python scripts\text_segment.py --image $img --prompt "building" --confidence 0.3 --output-dir $out
python scripts\text_segment.py --image $img --prompt "railway track" --confidence 0.3 --output-dir $out

기대 난이도 (정사 드론)

프롬프트기대튜닝 팁
building, solar panel, tree, car, truck 높음 기본 객체. 낮은 confidence에서도 비교적 잘 잡힘
railway track, fence, parking lot, blue tarp 중~높음 선형·구획. context에 따라 변동
utility pole, container, material pile 작거나 밀집. --min-size 권장
rail, ballast, railroad sleeper, catenary 낮~중 도메인·가는 객체. confidence 튜닝 필수
권장 confidence 0.25~0.35 에서 시작. 작은 폴·미세 자재는 --min-size로 노이즈 필터.

결과 합치기 (merge)

멀티 프롬프트 실행 후 클래스별 마스크를 한 장 오버레이 + 격자 + HTML로 합칩니다.

python scripts\merge_multi_results.py `
  --result-dir "output\dji_0016_compact" `
  --image "data\DJI_20260306100802_0016.JPG" `
  --max-side 2560

출력: output\dji_0016_compact\merged\

6c. 예시: DJI_0100 전체 파이프라인

0044 프롬프트 JSON(0016 상속 + 도로/열차 delta)을 DJI_…_0100.JPG에 적용하는 end-to-end 예입니다. 권장 순서: compact → (선택) gap → (선택) gap2_core → merge → HTML.

confidence: compact 0.3 · gap 0.25 · gap2_core 0.22. 같은 출력 폴더에 단계별로 마스크를 쌓은 뒤 merge하면 한 HTML에서 전부 볼 수 있습니다.

cd D:\MYCLAUDE_PROJECT\samgeo3-lab
.\.venv\Scripts\Activate.ps1

$img = "data\DJI_20260306101434_0100.JPG"
$out = "output\dji_0100_compact"
$json = "prompts\dji_20260306_0044.json"

# (선택) 프롬프트 목록 확인
python scripts\multi_prompt_segment.py --prompts-json $json --list-only --tier compact

# 1) 세그 — compact (0016 상속 + 도로/열차 delta)
python scripts\multi_prompt_segment.py `
  --prompts-json $json `
  --image $img `
  --tier compact `
  --confidence 0.3 `
  --output-dir $out

# 2) (선택) gap 보강
python scripts\multi_prompt_segment.py `
  --prompts-json $json `
  --image $img `
  --tier gap `
  --confidence 0.25 `
  --output-dir $out

# 3) (선택) gap2_core 보강
python scripts\multi_prompt_segment.py `
  --prompts-json $json `
  --image $img `
  --tier gap2_core `
  --confidence 0.22 `
  --output-dir $out

# 4) 합치기 + interactive index.html
python scripts\merge_multi_results.py `
  --result-dir $out `
  --image $img `
  --max-side 2048

# 5) 결과 열기
start "$out\merged\index.html"
결과 브라우저에서 output\dji_0100_compact\merged\index.html 을 열면 오버레이·클래스별 격자·범례를 한눈에 볼 수 있습니다.

7. 출력 파일

결과는 output/ 아래에 저장됩니다. 파일명 패턴: {이미지stem}_{prompt}_*

파일내용
*_mask.png 인스턴스별 unique mask (객체마다 다른 픽셀 값)
*_scores.npy 객체별 confidence 점수 (NumPy 배열). float PNG는 저장 불가
*_ann.png 원본 + 마스크/박스/점수 오버레이 시각화

예: test_image_person_mask.png, test_image_person_ann.png

8. Python API 빠른 참고

from samgeo import SamGeo3

sam = SamGeo3(
    backend="meta",                 # sam3.1 은 meta 전용
    model_id="facebook/sam3.1",
    confidence_threshold=0.3,       # 환경에 맞게 튜닝
    resolution=1008,
    enable_segmentation=True,
    enable_inst_interactivity=False,
)
sam.set_image("data/test_image.jpg")
sam.generate_masks("person")        # 텍스트 프롬프트
sam.save_masks("output/mask.png")
sam.show_anns(output="output/ann.png")

포인트 / 박스 인터랙티브 (참고)

import numpy as np
from samgeo import SamGeo3

sam = SamGeo3(backend="meta", enable_inst_interactivity=True)
sam.set_image("image.jpg")
masks, scores, logits = sam.predict_inst(
    point_coords=np.array([[520, 375]]),
    point_labels=np.array([1]),   # 1=foreground, 0=background
)

배치 (meta만)

sam = SamGeo3(backend="meta")
sam.set_image_batch(["a.jpg", "b.jpg"])
sam.generate_masks_batch("tree")
sam.save_masks_batch("output/", prefix="tree_mask")

9. 튜닝 · 트러블슈팅

증상원인 / 대응
No module named 'triton' uv pip install "triton-windows>=3.3.0.post19"
No objects found --confidence 낮추기 (예: 0.3 → 0.2), 프롬프트 변경, 명확한 객체가 보이는 이미지 사용
로드 시 missing_keys 경고 sam3 패키지와 sam3.1 체크포인트 일부 키 불일치. 추론은 동작할 수 있으나 score가 낮을 수 있음 → confidence 튜닝
CUDA not available CUDA torch 재설치, nvidia-smi 확인. SAM3 meta는 GPU 권장 (CPU만으로는 제한)
HF 접근 거부 / 다운로드 실패 모델 게이트 승인 + hf auth login
작은 객체 과다 검출 --min-size 로 픽셀 면적 필터
GeoTIFF 멀티밴드 API: set_image(path, bands=[4,3,2]) (1-based band index)
confidence 기본값 0.3 이유 이 환경에서 sam3.1 meta score가 대략 0.33–0.35 부근으로 나오는 경우가 있어, 기본 0.5를 쓰면 마스크가 0개일 수 있습니다. 실데이터에서 점수 분포를 보고 조정하세요.