📖 前置知識

Fish Fry Counter 是一個使用電腦視覺技術自動計算圖片中魚苗數量的個人練習專案。

魚苗範例


功能特色

  • 雙重偵測方法
    • 傳統 CV:閾值分割 + 輪廓檢測 + 分水嶺算法
    • YOLO 深度學習:YOLOv8 物件偵測模型
  • 自動偵測容器區域 (ROI)
  • 分水嶺算法分離重疊魚苗
  • Web 介面上傳圖片並顯示結果
  • RESTful API 支援程式化呼叫
  • 支援 JPEG、PNG 圖片格式

技術棧

技術 用途
Python 3.10+ 程式語言
FastAPI Web 框架
OpenCV 影像處理
Ultralytics YOLOv8 深度學習偵測
uv 套件管理

偵測流程

傳統 CV 方法

  1. 圖片轉灰階
  2. 高斯模糊降噪
  3. 自適應閾值分割
  4. 形態學操作(開閉運算)
  5. 分水嶺算法分離重疊物體
  6. 輪廓檢測與過濾
  7. 標記並計數

YOLO 方法

  1. 載入 YOLOv8 模型
  2. 執行物件偵測推論
  3. 依信心度與 IOU 閾值過濾
  4. 標記並計數

API 端點

端點 方法 說明
/ GET 首頁 - 圖片上傳介面
/api/methods GET 取得可用偵測方法列表
/api/count POST 上傳圖片並計算魚苗數量
/api/result/{id} GET 取得標記過的結果圖片
/docs GET Swagger API 文件

API 回應範例

{
  "count": 42,
  "annotated_image_url": "/api/result/uuid-here",
  "method": "cv"
}

專案結構

fish-cv/
├── app/
│   ├── main.py                  # FastAPI 應用程式進入點
│   ├── routers/
│   │   └── counting.py          # 計數 API 路由
│   ├── services/
│   │   ├── fish_detector.py     # 傳統 CV 偵測器
│   │   ├── yolo_detector.py     # YOLO 偵測器
│   │   └── detector_factory.py  # 偵測器工廠
│   ├── templates/
│   │   └── index.html           # 首頁模板
│   └── static/
│       └── style.css            # 樣式表
├── models/                       # YOLO 模型檔案
├── tests/                        # 測試程式
└── pyproject.toml                # 專案設定

參數調整

傳統 CV 偵測器參數

detector = FishDetector(
    min_area=100,           # 最小輪廓面積
    max_area=8000,          # 最大輪廓面積
    min_aspect_ratio=1.5,   # 最小長寬比
    max_aspect_ratio=8.0,   # 最大長寬比
    blur_kernel=5,          # 高斯模糊核大小
    block_size=21,          # 自適應閾值區塊大小
    use_watershed=True,     # 啟用分水嶺算法
)

YOLO 偵測器參數

detector = YoloDetector(
    confidence=0.2,         # 信心度閾值
    iou_threshold=0.3,      # NMS IOU 閾值
    device="auto",          # 運算裝置
)

快速開始

# 安裝相依套件
uv sync

# 啟動伺服器
uv run uvicorn app.main:app --reload

# 開啟瀏覽器
# http://localhost:8000

GitHub

https://github.com/yazelin/fish-cv