> ## Documentation Index
> Fetch the complete documentation index at: https://docs.baeum.ai.kr/llms.txt
> Use this file to discover all available pages before exploring further.

# cv-research

> detection, segmentation, classification 실험용 컴퓨터 비전 환경입니다.

## 문서 기준

* 기준일: `2026-02-23`
* Python: `3.12`
* 운영체제: macOS, Ubuntu, Windows
* 동기화 명령: `uv sync`

## 호환성 메모

| 환경                    | PyTorch 백엔드 | YOLO 학습 | 설명            |
| --------------------- | ----------- | ------- | ------------- |
| Ubuntu x86\_64 (CUDA) | `cu130`     | GPU 가속  | 전체 학습/추론 지원   |
| macOS Apple Silicon   | `mps`       | MPS 가속  | 대부분의 모델 학습 가능 |
| macOS Intel / Windows | `cpu`       | CPU 전용  | 추론/프로토타이핑 용도  |

<Note>
  `ultralytics`는 내부적으로 PyTorch 백엔드를 자동 감지합니다. GPU 사용 시 별도 device 설정 없이 자동으로 CUDA/MPS를 활용합니다.
</Note>

## CV 연구에서 패키지 역할

| 패키지                           | 역할                       | 비고                                  |
| ----------------------------- | ------------------------ | ----------------------------------- |
| `torch` / `torchvision`       | CV 기본 프레임워크              | 모델, 데이터셋, 변환(transforms)            |
| `ultralytics`                 | YOLO 시리즈 (v5\~v11)       | Detection, Segmentation, Pose, OBB  |
| `timm`                        | 사전학습 이미지 모델 허브           | ResNet, EfficientNet, ViT 등 700+ 모델 |
| `albumentations`              | 이미지 증강 파이프라인             | 고속 augmentation, 바운딩 박스 동기화         |
| `segmentation-models-pytorch` | Semantic Segmentation 모델 | UNet, FPN, DeepLabV3+ 등             |
| `supervision`                 | 비전 결과 시각화 및 후처리          | Annotation, Tracking, Zone counting |
| `opencv-python`               | 이미지/영상 I/O 및 처리          | 읽기, 쓰기, 색상 변환, 필터링                  |

## pyproject.toml

```toml theme={null}
[project]
name = "cv-research"
version = "0.1.0"
description = "Computer vision research environment"
requires-python = "==3.12.*"
dependencies = [
  "torch==2.10.0",
  "torchvision==0.25.0",
  "torchaudio==2.10.0",
  "ultralytics==8.4.14",
  "timm==1.0.24",
  "albumentations==2.0.8",
  "segmentation-models-pytorch==0.5.0",
  "supervision==0.27.0.post1",
  "opencv-python==4.13.0.92",
  "ipykernel==7.2.0",
  "pytest==9.0.2",
  "ruff==0.15.2",
]

[tool.uv]
package = false
```

## 설치

<Steps>
  <Step title="프로젝트 생성">
    ```bash theme={null}
    uv init cv-research
    cd cv-research
    ```
  </Step>

  <Step title="의존성 락 및 동기화">
    ```bash theme={null}
    uv lock
    uv sync
    ```
  </Step>

  <Step title="Jupyter 커널 등록">
    ```bash theme={null}
    uv run python -m ipykernel install --user --name cv-research --display-name "UV cv-research"
    ```
  </Step>
</Steps>

## 설치 확인

```bash theme={null}
uv run python -c "import torch, ultralytics, timm, albumentations, cv2; print('torch', torch.__version__); print('ultralytics', ultralytics.__version__); print('opencv', cv2.__version__)"
```

## 기본 사용 예시

### 이미지 분류 (timm)

```python theme={null}
import timm
import torch
from torchvision import transforms
from PIL import Image

model = timm.create_model("efficientnet_b0", pretrained=True, num_classes=10)
model.eval()

transform = transforms.Compose([
    transforms.Resize((224, 224)),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])

img = transform(Image.open("sample.jpg")).unsqueeze(0)
with torch.no_grad():
    output = model(img)
    pred = output.argmax(dim=1).item()
    print(f"Predicted class: {pred}")
```

### 객체 탐지 (YOLO)

```python theme={null}
from ultralytics import YOLO

# 사전학습 모델로 추론
model = YOLO("yolo11n.pt")
results = model("image.jpg")
results[0].show()

# 커스텀 데이터셋으로 학습
model = YOLO("yolo11n.pt")
model.train(data="dataset.yaml", epochs=50, imgsz=640, batch=16)
```

### Augmentation 파이프라인

```python theme={null}
import albumentations as A
from albumentations.pytorch import ToTensorV2

transform = A.Compose([
    A.RandomResizedCrop(height=224, width=224, scale=(0.8, 1.0)),
    A.HorizontalFlip(p=0.5),
    A.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2, hue=0.1),
    A.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
    ToTensorV2(),
], bbox_params=A.BboxParams(format="pascal_voc", label_fields=["labels"]))  # Detection용
```

## 트러블슈팅

| 증상                       | 원인                                     | 해결                                               |
| ------------------------ | -------------------------------------- | ------------------------------------------------ |
| `cv2` import 실패          | `opencv-python` 의존성 꼬임                 | `uv lock --refresh` 후 `uv sync`                  |
| 학습 속도 저하                 | GPU 미인식 또는 DataLoader `num_workers` 부족 | `torch.cuda.is_available()` 확인, `num_workers` 증가 |
| YOLO 학습 중 OOM            | 이미지 크기 또는 배치 크기 초과                     | `imgsz` 줄이기 (640 → 480), `batch` 줄이기             |
| `timm` 모델 다운로드 실패        | 네트워크 문제 또는 HuggingFace 접근 제한           | `HF_TOKEN` 설정 또는 수동 다운로드                         |
| albumentations 바운딩 박스 오류 | `bbox_params` 포맷 불일치                   | `pascal_voc`, `coco`, `yolo` 중 데이터에 맞는 포맷 지정     |
| `uv sync` 의존성 충돌         | 기존 락 파일과 버전 불일치                        | `uv lock --refresh` 후 `uv sync`                  |

## 설치 점검 목록

* 관리자 권한/필수 도구 등 사전 요구사항을 먼저 확인했습니다.
* 설치 후 버전 확인 명령어(`--version`)를 실행해 정상 설치를 검증했습니다.
* PATH/환경변수 변경이 필요한 경우 터미널을 다시 열어 적용 여부를 확인했습니다.
* 문제가 생겼을 때를 대비해 설치 로그 또는 스크린샷을 남겼습니다.

## 관련 문서

<CardGroup cols={2}>
  <Card title="Setup 홈" icon="house" href="/setup/index">
    운영체제별 설치 흐름을 다시 확인합니다.
  </Card>

  <Card title="다음: automl" icon="arrow-right" href="/setup/uv-env/automl">
    다음 설치 단계를 이어서 진행합니다.
  </Card>
</CardGroup>
