# OpenCV 學習筆記（考試溫習版）

---

## 0. 30 秒總複習（考前最後掃描）

```
OpenCV 流程：讀圖 → 轉色彩空間 → 前處理 → 矩陣運算 / 繪圖
             → 幾何變換 → 濾波 → 邊緣 → 輪廓
             → 特徵擷取 → 特徵匹配 → Homography
```

| 你會用到的函式 | 一句話記法 |
|---|---|
| `cv2.imread()` | 讀圖（預設 **BGR**） |
| `cv2.cvtColor()` | 換色彩空間（BGR→RGB / Gray / HSV / LAB） |
| `cv2.resize()` / `cv2.GaussianBlur()` / `cv2.threshold()` | 前處理三寶 |
| `cv2.addWeighted()` | 兩張圖加權混合（透明疊圖） |
| `cv2.line/rectangle/circle/polylines/putText` | 繪圖五招 |
| `cv2.warpAffine()` / `cv2.warpPerspective()` | 仿射 / 透視變換 |
| `cv2.Canny()` | 邊緣偵測 |
| `cv2.findContours()` / `cv2.boundingRect()` | 輪廓 / 邊界框 |
| `cv2.erode/dilate/morphologyEx` | 形態學 |
| `cv2.ORB_create()` + `BFMatcher` | 特徵擷取 + 匹配 |

---

## 1. What is OpenCV?

### 1.1 定義

**OpenCV = Open Source Computer Vision Library**，一個開源的電腦視覺與機器學習軟體庫。

| 項目 | 內容 |
|------|------|
| 全名 | Open Source Computer Vision Library |
| 起源 | 由 **Intel** 發起（2000 年），現由 **OpenCV 社群 / OpenCV.org** 維護 |
| 授權 | Apache 2.0（開源、可商用） |
| 語言支援 | **C++、Python、Java**、MATLAB、JavaScript 等（本課程用 **Python**） |
| 演算法數量 | **2500+** 已最佳化（optimized）演算法 |
| 應用領域 | AI（人工智慧）與機器視覺（machine vision） |

### 1.2 為什麼要用 OpenCV

1. **開源免費**：無授權費，學術與商業皆可使用。
2. **高度最佳化**：底層用 C/C++ 撰寫，並可用 SIMD / GPU（CUDA、OpenCL）加速，效能遠勝純 Python 迴圈。
3. **跨平台**：Windows、Linux、macOS、Android、iOS、Raspberry Pi / 嵌入式裝置。
4. **生態完整**：與 **NumPy**（矩陣運算）、**Matplotlib**（顯示）無縫整合 —— 這正是本課程的組合。
5. **模組化**：核心（core）、影像處理（imgproc）、特徵（features2d）、影片（video）、機器學習（ml）、深度學習推論（dnn）等。

### 1.3 課程用的標準匯入寫法（必背）

```python
import cv2                      # OpenCV 本體
import numpy as np              # 矩陣運算（OpenCV 的影像就是 NumPy 陣列）
import matplotlib.pyplot as plt # 顯示圖片 / 畫多圖對比
import urllib.request           # 下載範例圖片
```

> **考點**：`cv2` 是套件名稱；`pip install opencv-python`（要完整功能可裝 `opencv-contrib-python`）。
> `cv2.__version__` 可查版本（本機環境為 5.0.0，PDF 舊寫法在 4.x / 5.x 都適用）。

### 1.4 最小可執行範例

```python
import cv2

image = cv2.imread("photo.jpg")          # 讀取（BGR 順序）
print(type(image))                        # <class 'numpy.ndarray'>
print(image.shape)                        # (height, width, 3)  → 注意是 H, W 不是 W, H
cv2.imshow("Window", image)               # 開視窗顯示
cv2.waitKey(0)                            # 等待按鍵（0 = 無限等待）
cv2.destroyAllWindows()                   # 關閉所有視窗
```

**三個必記事實**

1. 影像是 **NumPy 陣列**，形狀是 `(rows/height, cols/width, channels)`。
2. 通道順序預設是 **BGR**（不是 RGB）。
3. `cv2.imshow()` 後一定要 `cv2.waitKey()`，否則視窗不會更新。

---

## 2. OpenCV Applications

PDF 列出六大應用，以下逐一補充「用什麼技術做」：

| 應用 | 英文 | 背後的 OpenCV 技術 |
|------|------|-------------------|
| 人臉辨識 | Face recognition | Haar Cascade / DNN（`cv2.dnn`）、LBPH、FaceRecognizer；人臉偵測用 `CascadeClassifier` |
| 自動駕駛 | Autonomous vehicles | 車道線偵測（Canny + Hough）、物件偵測、光流（optical flow）、視覺測距（stereo） |
| 醫療影像 | Medical imaging | 影像增強、去雜訊（median / bilateral）、分割（threshold + contour）、區域量測 |
| 工業檢測 | Industrial inspection | 瑕疵檢測、尺寸量測、模板匹配（`matchTemplate`）、形態學 |
| 監控系統 | Surveillance systems | 背景相減（`createBackgroundSubtractorMOG2`）、移動偵測、追蹤（CSRT/KCF）、車牌辨識 |
| 機械人與無人機 | Robotics and drones | **Visual SLAM**、ArUco marker 定位、姿態估測（PnP）、避障 |

### 2.1 補充：每個應用對應課程哪一節

- 人臉 / 物件偵測 → 第 11、12 節（Feature Extraction / Matching）
- 自動駕駛車道線 → 第 10 節（Edge Detection）+ Hough 變換
- 醫療 / 工業 → 第 5、9 節（Pre-processing / Filtering）
- 監控 → 第 6 節（Matrix Operations，ROI 與遮罩）
- 機械人 / AR → 第 8、12 節（Transformations / Feature Matching）

### 2.2 真實業界案例（口試可舉例）

- **OpenCV + YOLO**：工地安全帽偵測、口罩偵測。
- **OpenCV + Tesseract**：車牌 / 發票 OCR（先前處理再辨識）。
- **OpenCV 全景拼接**（stitching 模組）：手機全景照片。
- **OpenCV ArUco**：倉庫機械人定位貼紙。

---

## 3. Color Spaces

**色彩空間（Color Space）**= 用一組數字來描述顏色的座標系統。同一個像素在不同色彩空間有不同的表示法。

### 3.1 PDF 列出的五種

| 色彩空間 | 通道 | 範圍 | 特點 / 用途 |
|---------|------|------|------------|
| **BGR** | 3（Blue, Green, Red） | 0–255 | **OpenCV 預設**的影像格式（與 RGB 相反） |
| **RGB** | 3（Red, Green, Blue） | 0–255 | 一般顯示器 / Matplotlib / PIL 的標準格式 |
| **Grayscale（灰階）** | **1**（單通道 intensity） | 0–255（0=黑, 255=白） | 資料量只剩 1/3，處理更快；多數演算法（Canny、ORB）只需要灰階 |
| **HSV** | 3（Hue, Saturation, Value） | H:0–179, S:0–255, V:0–255 | **把顏色與亮度分離**，做顏色分割（color segmentation）最準 |
| **LAB** | 3（L\*, a\*, b\*） | L:0–100, a/b:-128–127 | **感知均勻（perceptually uniform）**，對光照變化最穩健 |

### 3.2 HSV 深入（考試常問）

- **H (Hue) 色相**：顏色種類（紅 / 綠 / 藍…）。**在 OpenCV 中範圍是 0–179**（不是 0–360，因為要塞進 uint8）。
- **S (Saturation) 飽和度**：顏色的鮮豔程度，0 = 灰，255 = 最鮮豔。
- **V (Value) 明度**：亮度，0 = 黑。
- **為什麼好用**：光照變強只會改 V，不太改 H。所以「找紅色球」時用 HSV 比用 BGR 穩定得多。

**常用 HSV 範圍（OpenCV 尺度）**

| 顏色 | 低界 `(H,S,V)` | 高界 `(H,S,V)` |
|------|----------------|----------------|
| 紅（第一段） | `(0, 100, 100)` | `(10, 255, 255)` |
| 紅（第二段，跨 180） | `(170, 100, 100)` | `(180, 255, 255)` |
| 綠 | `(40, 100, 100)` | `(80, 255, 255)` |
| 藍 | `(100, 100, 100)` | `(130, 255, 255)` |
| 黃 | `(20, 100, 100)` | `(35, 255, 255)` |

> 紅色在 H 環上跨過 0，所以要 **兩個 mask 相加**。

### 3.3 LAB 深入

- **L**：亮度（Lightness）。
- **a**：綠 ↔ 紅 軸。
- **b**：藍 ↔ 黃 軸。
- **優點**：感知上「等距」—— 兩色的 LAB 距離 ≈ 人眼感覺的差異。所以 **LAB 對光照改變的穩健性（illumination robustness）最好**，常用於顏色差異比對、白平衡、顏色恆常性。

### 3.4 記憶口訣

```
BGR  → OpenCV 的母語
RGB  → 顯示器/Matplotlib 的母語
Gray → 快（單通道）
HSV  → 分顏色最準（H 不受亮度影響）
LAB  → 抗光照最強（感知均勻）
```

---

## 4. Color Space Conversion

### 4.1 核心函式：`cv2.cvtColor()`

```python
dst = cv2.cvtColor(src, code)
```

| 參數 | 說明 |
|------|------|
| `src` | 來源影像（NumPy 陣列） |
| `code` | 轉換代碼（見下表） |
| `dst` | 回傳轉換後的影像 |

**常用轉換代碼**

| code | 用途 |
|------|------|
| `cv2.COLOR_BGR2RGB` | BGR → RGB（**修正顏色顯示**，Matplotlib 用） |
| `cv2.COLOR_RGB2BGR` | RGB → BGR |
| `cv2.COLOR_BGR2GRAY` | BGR → 灰階（**加速處理**） |
| `cv2.COLOR_BGR2HSV` | BGR → HSV（**顏色分割**） |
| `cv2.COLOR_HSV2BGR` | HSV → BGR（做回原圖） |
| `cv2.COLOR_BGR2LAB` | BGR → LAB（**抗光照**） |
| `cv2.COLOR_BGR2YCrCb` | 常用於膚色偵測 |

### 4.2 PDF 的四個重點

1. **`cv2.cvtColor()` 負責格式互轉** —— 幾乎所有色彩相關任務的第一步。
2. **BGR → Gray 是為了加快處理**（單通道，資料量 1/3；Canny、ORB、threshold 都需要）。
3. **BGR → HSV 是為了顏色分割**（用 `cv2.inRange()` 抓特定顏色）。
4. **LAB 提升光照穩健性**（不同光源下顏色判斷仍準）。
5. **轉換常能提升偵測準確度**（conversion often improves detection accuracy）—— 因為演算法在合適的空間工作效果最好。

### 4.3 完整範例：修正常見的「顏色錯亂」

```python
import cv2
import matplotlib.pyplot as plt

image_bgr = cv2.imread("photo.jpg")        # OpenCV 讀入 = BGR
image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)   # 轉成 RGB

# 錯誤示範：直接把 BGR 丟給 Matplotlib → 紅藍互換，人臉會變藍
plt.imshow(image_bgr)     # ← 顏色錯
# 正確做法
plt.imshow(image_rgb)     # ← 顏色對
plt.show()
```

### 4.4 完整範例：用 HSV 做顏色分割（實務必考）

```python
import cv2
import numpy as np

image_bgr = cv2.imread("photo.jpg")
hsv = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2HSV)

# 紅色有兩段 H
lower_red1, upper_red1 = np.array([0, 100, 100]),   np.array([10, 255, 255])
lower_red2, upper_red2 = np.array([170, 100, 100]), np.array([180, 255, 255])

mask = cv2.inRange(hsv, lower_red1, upper_red1) | cv2.inRange(hsv, lower_red2, upper_red2)
result = cv2.bitwise_and(image_bgr, image_bgr, mask=mask)
cv2.imshow("Red only", result)
cv2.waitKey(0)
```

### 4.5 常見錯誤

| 錯誤 | 後果 | 修正 |
|------|------|------|
| 忘記 BGR→RGB 就交給 Matplotlib | 紅藍對調 | 先 `cvtColor` |
| 把 RGB 當 BGR 再 `cvtColor(BGR2RGB)` | 顏色被換兩次（換回錯的） | 只轉一次 |
| 灰階圖當彩色圖處理 | `cvtColor(gray, COLOR_BGR2GRAY)` 會報錯 | 檢查 `image.shape` 的通道數 |
| HSV 上下界用 numpy 陣列而非 list | `inRange` 可能型別錯誤 | 用 `np.array([...])` |
| 灰階轉 HSV | OpenCV 不支援 `GRAY2HSV` | 先回 BGR 再轉 HSV |

---


---

## 5. Image Pre-processing

> **一句話**：前處理 = 在跑演算法之前，把影像「整理乾淨」，讓後面的偵測更準、更快。

### 5.1 前處理的五個步驟 + 對應 API

| 步驟 | 說明 | 主要 API |
|------|------|---------|
| **1. Resize 調整尺寸** | 統一到標準尺寸，降低運算量 | `cv2.resize(src, dsize, fx, fy, interpolation)` |
| **2. Crop 裁剪** | 取出感興趣區域（ROI） | NumPy 切片 `image[y1:y2, x1:x2]` |
| **3. Normalize 正規化** | 統一亮度 / 對比 | `cv2.normalize()`、`cv2.convertScaleAbs()`、`cv2.equalizeHist()` |
| **4. Denoise 去雜訊** | 分析前先移除雜訊 | `cv2.GaussianBlur()`、`cv2.medianBlur()`、`cv2.bilateralFilter()` |
| **5. Threshold 二值化** | 做分割（segmentation） | `cv2.threshold()`、`cv2.adaptiveThreshold()`、`cv2.inRange()` |

### 5.2 Resize 詳解

```python
resized = cv2.resize(image, (640, 480))           # 指定 (寬 W, 高 H) ← 注意順序！
resized = cv2.resize(image, None, fx=0.5, fy=0.5) # 按比例縮小一半
```

**插值法（interpolation）選擇 —— 常考**

| 常數 | 何時用 |
|------|--------|
| `cv2.INTER_LINEAR` | **預設**，放大縮小都可用（速度與品質平衡） |
| `cv2.INTER_NEAREST` | 最快，但會有鋸齒；標籤圖 / mask 用 |
| `cv2.INTER_CUBIC` | 放大時品質較好（較慢） |
| `cv2.INTER_AREA` | **縮小時最好**（避免摩爾紋） |
| `cv2.INTER_LANCZOS4` | 品質最高、最慢 |

> ⚠️ `cv2.resize` 的 `dsize` 是 **(width, height)**，而 `image.shape` 是 **(height, width, channels)** —— 兩者相反，是考試最常見陷阱。

### 5.3 Crop / ROI

```python
roi = image[y1:y2, x1:x2]     # 先 Y 後 X！
# 例：取 100~300 列、150~350 行
roi = image[100:300, 150:350]
```

- **切片是「視圖（view）」不是複本**：改 `roi` 會連原圖一起改。要獨立就 `.copy()`。
- 越界不會報錯，會自動截短 —— 所以務必先檢查 `image.shape`。

### 5.4 正規化 / 增強對比

```python
# 方法一：線性拉伸到 0-255
norm = cv2.normalize(image, None, 0, 255, cv2.NORM_MINMAX)

# 方法二：調 alpha（對比）與 beta（亮度）
bright = cv2.convertScaleAbs(image, alpha=1.2, beta=30)

# 方法三：直方圖均衡化（只支援單通道，最常用於灰階）
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
eq = cv2.equalizeHist(gray)

# 方法四：CLAHE（自適應，效果較自然）
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
eq = clahe.apply(gray)
```

### 5.5 二值化 Threshold

```python
ret, binary = cv2.threshold(src_gray, thresh, maxval, type)
```

| 參數 | 說明 |
|------|------|
| `src_gray` | **必須是單通道灰階圖** |
| `thresh` | 門檻值（例如 127） |
| `maxval` | 超過門檻時給的值（通常 255） |
| `type` | 見下表 |

| type | 行為 |
|------|------|
| `cv2.THRESH_BINARY` | `> thresh` → maxval，否則 0 |
| `cv2.THRESH_BINARY_INV` | 反過來（**常用於找白色物件的前景**） |
| `cv2.THRESH_TRUNC` | 超過門檻就截斷為門檻值 |
| `cv2.THRESH_TOZERO` | 低於門檻變 0，其餘不變 |
| `cv2.THRESH_OTSU` | **自動選最佳門檻**（與 BINARY 併用） |
| `cv2.THRESH_TRIANGLE` | 三角形法自動門檻 |

**Otsu 範例**

```python
ret, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
print("Otsu 自動算出的門檻 =", ret)
```

**自適應門檻（光照不均時用）**

```python
binary = cv2.adaptiveThreshold(gray, 255,
                               cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                               cv2.THRESH_BINARY, 11, 2)
```

### 5.6 前處理三步

1. **Fix the Colors（修正顏色）**
   OpenCV 預設以 BGR 讀入照片，轉成 RGB 才能正常顯示顏色。
2. **Simplify Image（簡化影像）**
   移除顏色通道產生 Grayscale，並縮放像素尺寸以加快處理速度。
3. **Clean & Filter（清理與濾波）**
   套用模糊（Blurring）消除不必要雜訊，並用二值化（Thresholding）取出乾淨的黑白形狀。

### 5.7 前處理標準流程（可直接抄進考卷）

```python
import cv2
import numpy as np

image_bgr = cv2.imread("photo.jpg")
image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)   # 1. 修顏色
gray      = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2GRAY)  # 2. 轉灰階
small     = cv2.resize(gray, (320, 320))                 # 3. 縮小
blurred   = cv2.GaussianBlur(small, (5, 5), 0)           # 4. 去雜訊
_, binary = cv2.threshold(blurred, 127, 255, cv2.THRESH_BINARY)  # 5. 二值化
```


---

## 6. Matrix Operations

> **核心觀念**：影像就是 **NumPy 矩陣**，所以所有矩陣技巧都能用在影像上。

### 6.1 PDF 的五個重點

| 重點 | 說明 | 寫法 |
|------|------|------|
| **影像是 NumPy 矩陣** | 灰階 = 2D 陣列 `(H, W)`；彩色 = 3D 陣列 `(H, W, 3)` | `image.shape` |
| **用列與行索引存取像素** | 先 Y（列）後 X（行） | `pixel = image[y, x]` |
| **加法與減法** | 調亮 / 調暗、找差異 | `cv2.add()` / `cv2.subtract()` |
| **遮罩與位元運算** | 選取 / 合成區域 | `cv2.bitwise_and/or/not/xor` |
| **有效率地取出 ROI** | 切片是 view，零複製、極快 | `roi = image[y1:y2, x1:x2]` |

### 6.2 影像矩陣的結構

```python
image.shape          # (356, 413, 3) → 高 356, 寬 413, 3 通道
image[0, 0]          # 左上角像素 → array([B, G, R])
image[100, 200, 2]   # 第 100 列、200 行 的 R 通道值
image[:, :, 0]       # 全部 Blue 通道（2D）
image.dtype          # uint8（0–255）
image.size           # 總元素數 = H*W*C
```

> **順序**：`image[列 Y, 行 X, 通道]` = `image[高度, 寬度, 通道]`。

### 6.3 像素層級運算

```python
# 1. 直接改像素（會直接改到原圖）
image[50, 50] = [255, 0, 0]            # 該點變藍（BGR）

# 2. 整塊填色（把 ROI 蓋成黑色）
image[100:200, 100:200] = 0

# 3. 整張圖加亮 / 減暗
bright = np.clip(image.astype(np.int16) + 50, 0, 255).astype(np.uint8)
dark   = cv2.subtract(image, 50)       # 自動飽和，不會 overflow
```

**⚠️ uint8 溢位陷阱（必考）**

```python
img = np.full((3, 3, 3), 200, dtype=np.uint8)   # 模擬一張全 200 的影像

print((img + 100)[0, 0, 0])        # → 44     NumPy 加法會 wrap around（300 % 256 = 44）
print(cv2.add(img, 100)[0, 0, 0])  # → 255    OpenCV 做飽和運算（saturate）
print(cv2.subtract(img, 50)[0, 0, 0])  # → 150
```

**本機實測結果（OpenCV 5.0.0 / NumPy 2.4.6）**

| 運算式 | 結果 | 行為 |
|--------|------|------|
| `img + 100` | **44** | 溢位（overflow）→ 爆掉 |
| `cv2.add(img, 100)` | **255** | 飽和（saturate）→ 封頂在 255 |
| `cv2.subtract(img, 50)` | **150** | 正常，且不會變成負數 |
| `np.clip(img.astype(np.int16) + 50, 0, 255).astype(np.uint8)` | **250** | 手動安全做法 |

→ **加法請用 `cv2.add()`，不要用 `+`**（除非刻意要 wrap）。

> ⚠️ **OpenCV 5.x 小差異**：`cv2.add()` 的第二個參數建議傳**同形狀的陣列**或 `np.full_like(img, 100)`。
> 在 OpenCV 5.0 中傳入 Python 純量（`100`）對 2D/3D 影像仍可運作，但傳入 `np.uint8(100)` 這種 NumPy 純量會報 `src2 is not a numpy array, neither a scalar`。為求穩定，統一寫 `cv2.add(img, np.full_like(img, 100))` 最保險。

### 6.4 加權混合：`cv2.addWeighted()`

```python
dst = cv2.addWeighted(src1, alpha, src2, beta, gamma)
# 公式：dst = src1*alpha + src2*beta + gamma
```

| 參數 | 說明 |
|------|------|
| `src1, src2` | 兩張**尺寸與型別相同**的圖 |
| `alpha, beta` | 各自權重（常讓 `alpha + beta = 1`） |
| `gamma` | 附加常數（整體加亮 / 減暗） |

**用途**：透明疊圖（watermark）、製作 tint 濾鏡、影像混合。

### 6.5 位元運算與遮罩

```python
mask   = cv2.inRange(hsv, lower, upper)                 # 產生黑白遮罩
result = cv2.bitwise_and(image, image, mask=mask)       # 只保留遮罩白色處
inv    = cv2.bitwise_not(mask)                          # 反轉遮罩
combo  = cv2.bitwise_or(img1, img2)                     # 合成
```

| 函式 | 行為（逐位元） |
|------|----------------|
| `bitwise_and` | 兩者皆 1 才 1（**取交集 / 套遮罩**） |
| `bitwise_or` | 任一 1 就 1（**取聯集**） |
| `bitwise_xor` | 相異才 1（**找差異**） |
| `bitwise_not` | 反相（**黑↔白反轉**） |

> 遮罩（mask）必須是 **單通道 uint8**，白色（255）= 保留，黑色（0）= 排除。

### 6.6 翻轉與旋轉

```python
flipped_h = cv2.flip(image, 1)    # 1 = 水平鏡像（左右翻）
flipped_v = cv2.flip(image, 0)    # 0 = 垂直翻轉（上下翻）
flipped_b = cv2.flip(image, -1)   # -1 = 同時水平 + 垂直

rotated_cw  = cv2.rotate(image, cv2.ROTATE_90_CLOCKWISE)         # 順時針 90°
rotated_ccw = cv2.rotate(image, cv2.ROTATE_90_COUNTERCLOCKWISE)  # 逆時針 90°
rotated_180 = cv2.rotate(image, cv2.ROTATE_180)                  # 180°
```

### 6.7 矩陣拼接與重塑

```python
h_concat = np.hstack([img1, img2])            # 水平拼接（高度要相同）
v_concat = np.vstack([img1, img2])            # 垂直拼接（寬度要相同）
side_by_side = cv2.hconcat([img1, img2])      # OpenCV 版本
reshaped = image.reshape(-1)                  # 攤平成 1D（做統計 / ML 特徵）
```

### 6.8 四大操作對照表

| PDF 標題 | 說明 | API |
|---------|------|-----|
| **Cropping & ROI** | 用 2D 陣列座標 `[Y, X]` 切出子網格，取得感興趣區域 | `image[y1:y2, x1:x2]` |
| **Draw Overlays** | 直接覆寫矩陣像素值，加上邊界框、目標圓、文字標籤 | `cv2.rectangle/circle/putText` |
| **Flip & Rotate** | 重新索引像素位置，做水平鏡像或順時針旋轉 | `cv2.flip` / `cv2.rotate` |
| **Matrix Blending** | 用加權加法數學合併兩個影像矩陣，做出半透明疊圖 | `cv2.addWeighted` |


---

## 7. Drawing Functions

> **用途**：在影像上「畫標註」—— 邊界框、中心點、文字標籤。工業檢測與 AR 顯示必用。

### 7.1 五大繪圖函式

| 函式 | 畫什麼 | 簽名 |
|------|--------|------|
| `cv2.line()` | 直線 | `cv2.line(img, pt1, pt2, color, thickness, lineType)` |
| `cv2.rectangle()` | 矩形 / 邊界框 | `cv2.rectangle(img, pt1, pt2, color, thickness)` |
| `cv2.circle()` | 圓形 | `cv2.circle(img, center, radius, color, thickness)` |
| `cv2.polylines()` | 多邊形 | `cv2.polylines(img, [pts], isClosed, color, thickness)` |
| `cv2.putText()` | 文字標註 | `cv2.putText(img, text, org, font, scale, color, thickness, lineType)` |

### 7.2 顏色與粗細規則（超常考）

- **顏色是 BGR 元組**：紅 = `(0, 0, 255)`、綠 = `(0, 255, 0)`、藍 = `(255, 0, 0)`、白 = `(255, 255, 255)`、黑 = `(0, 0, 0)`。
- **`thickness = -1`** → **填滿（filled）**；`1` 是細線；`2` 是粗線。
- **`lineType = cv2.LINE_AA`** → 抗鋸齒，線條較平滑漂亮。
- 座標是 **(x, y)**，即 **(行, 列)** —— 與 NumPy 的 `[y, x]` **相反**，必考陷阱。
- **繪圖會直接改到原圖（in-place）**。要保留原圖請先 `canvas = image.copy()`。

### 7.3 完整範例（可直接執行）

```python
import cv2
import numpy as np

canvas = np.zeros((400, 600, 3), dtype="uint8")   # 黑色畫布

# 1. 直線（左上到右下）
cv2.line(canvas, (0, 0), (600, 400), (255, 255, 255), 2)

# 2. 矩形邊界框（粗細 3，空心）
cv2.rectangle(canvas, (50, 50), (250, 200), (0, 0, 255), 3)

# 3. 圓形（中心 (400,150)，半徑 60，綠色，填滿）
cv2.circle(canvas, (400, 150), 60, (0, 255, 0), -1)

# 4. 多邊形（三角形）
pts = np.array([[300, 350], [500, 350], [400, 220]], np.int32)
cv2.polylines(canvas, [pts], isClosed=True, color=(255, 0, 0), thickness=3)

# 5. 文字標註
cv2.putText(canvas, "OpenCV", (60, 320),
            cv2.FONT_HERSHEY_SIMPLEX, 1.2, (255, 255, 0), 2, cv2.LINE_AA)

cv2.imshow("Drawing Demo", canvas)
cv2.waitKey(0)
cv2.destroyAllWindows()
```

### 7.4 `putText` 常用字型

| 常數 | 外觀 |
|------|------|
| `cv2.FONT_HERSHEY_SIMPLEX` | 最常用、清晰（**建議背這個**） |
| `cv2.FONT_HERSHEY_PLAIN` | 細小 |
| `cv2.FONT_HERSHEY_DUPLEX` | 較粗 |
| `cv2.FONT_HERSHEY_COMPLEX` | 複雜襯線 |
| `cv2.FONT_HERSHEY_SCRIPT_SIMPLEX` | 手寫體 |
| `cv2.FONT_ITALIC` | 可與上面用 `+` 疊加 |

> **注意**：`cv2.putText()` 只能畫 **ASCII 英數字**，**不支援中文**。要畫中文需用 PIL（`ImageDraw` + 中文字型檔）。

### 7.5 量測文字大小（排版用）

```python
(text_w, text_h), baseline = cv2.getTextSize("OpenCV", cv2.FONT_HERSHEY_SIMPLEX, 1.2, 2)
```

### 7.6 實務：在偵測結果上畫邊界框

```python
x, y, w, h = 100, 80, 150, 200
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.putText(image, "object 92%", (x, y - 10),
            cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
cv2.circle(image, (x + w // 2, y + h // 2), 4, (0, 0, 255), -1)   # 中心點
```


---

## 8. Transformations

> **幾何變換**：改變像素的「位置」，不改變像素的「顏色」。

### 8.1 PDF 的五種變換

| 變換 | 說明 | 自由度（DOF） | API |
|------|------|--------------|-----|
| **Translation 平移** | 移動影像位置 | 2 | `cv2.warpAffine()` + 平移矩陣 |
| **Rotation 旋轉** | 改變方向 | 1（+中心點） | `cv2.getRotationMatrix2D()` + `cv2.warpAffine()` |
| **Scaling 縮放** | 放大 / 縮小 | 2 | `cv2.resize()` / `warpAffine` |
| **Affine 仿射** | **保持平行線仍平行** | 6 | `cv2.getAffineTransform()`（需 3 點）+ `cv2.warpAffine()` |
| **Perspective 透視** | 校正視角（可讓平行線不再平行） | 8 | `cv2.getPerspectiveTransform()`（需 4 點）+ `cv2.warpPerspective()` |

### 8.2 平移 Translation

```python
import cv2
import numpy as np

image = cv2.imread("photo.jpg")
h, w = image.shape[:2]

# 平移矩陣 M = [[1, 0, tx], [0, 1, ty]]   （tx 向右, ty 向下）
M = np.float32([[1, 0, 100], [0, 1, 50]])
shifted = cv2.warpAffine(image, M, (w, h))
```

### 8.3 旋轉 Rotation

```python
center = (w // 2, h // 2)
M = cv2.getRotationMatrix2D(center, angle=45, scale=1.0)   # 逆時針 45 度
rotated = cv2.warpAffine(image, M, (w, h))
```

| 參數 | 說明 |
|------|------|
| `center` | 旋轉中心 `(x, y)` |
| `angle` | **逆時針為正**（正數 = 逆時針） |
| `scale` | 同時縮放比例（1.0 = 不縮放） |

> ⚠️ 旋轉後角落會被切掉。要完整保留需計算新的邊界尺寸，或加 padding。

### 8.4 仿射 Affine（3 點對 3 點）

```python
src_pts = np.float32([[50, 50], [200, 50], [50, 200]])       # 原圖 3 點
dst_pts = np.float32([[10, 100], [200, 50], [100, 250]])     # 目標 3 點

M = cv2.getAffineTransform(src_pts, dst_pts)
affine = cv2.warpAffine(image, M, (w, h))
```

- **特性**：平行線保持平行、形狀不歪斜（等角變換 + 均勻縮放 + 切變）。
- 常見用途：傾斜校正、資料增強（augmentation）。

### 8.5 透視 Perspective（4 點對 4 點）

```python
src_pts = np.float32([[56, 65], [368, 52], [28, 387], [389, 390]])
dst_pts = np.float32([[0, 0], [300, 0], [0, 300], [300, 300]])

M = cv2.getPerspectiveTransform(src_pts, dst_pts)
warped = cv2.warpPerspective(image, M, (300, 300))
```

- **特性**：可修正視角（viewing angle），把斜拍的文件「拉正」。
- 常見用途：**車牌校正、文件掃描（document scanner）、鳥瞰圖（bird's-eye view）**。

### 8.6 `warpAffine` vs `warpPerspective` 對比

| 項目 | `warpAffine` | `warpPerspective` |
|------|--------------|-------------------|
| 矩陣大小 | 2 × 3 | 3 × 3 |
| 需要的對應點 | 3 | 4 |
| 平行線 | 保持平行 | 不保證 |
| 用途 | 平移 / 旋轉 / 縮放 / 傾斜 | 視角校正 / 投影 |

### 8.7 邊界填補（borderMode）

```python
result = cv2.warpAffine(image, M, (w, h),
                        flags=cv2.INTER_LINEAR,
                        borderMode=cv2.BORDER_CONSTANT,
                        borderValue=(0, 0, 0))     # 空白處填黑色
```

| borderMode | 效果 |
|------------|------|
| `cv2.BORDER_CONSTANT` | 填固定顏色 |
| `cv2.BORDER_REPLICATE` | 複製邊緣像素 |
| `cv2.BORDER_REFLECT` | 鏡射 |
| `cv2.BORDER_WRAP` | 環繞 |

---

## 9. Filtering Techniques

> **濾波 = 卷積（convolution）**：用一個小矩陣（kernel）在影像上滑動，重新計算每個像素值。

### 9.1 PDF 的四種濾波器

| 濾波器 | API | 特性 | 適用 |
|--------|-----|------|------|
| **Average Blur** | `cv2.blur(img, (k, k))` | 取 kernel 內平均值，**平滑影像** | 快速模糊、均勻去雜訊 |
| **Gaussian Blur** | `cv2.GaussianBlur(img, (k, k), sigma)` | 依距離加權（中央權重最大），**減少隨機雜訊** | 最常用，前處理首選 |
| **Median Blur** | `cv2.medianBlur(img, k)` | 取中位數，**移除椒鹽雜訊（salt-and-pepper）** | 黑白斑點雜訊 |
| **Bilateral Filter** | `cv2.bilateralFilter(img, d, sigmaColor, sigmaSpace)` | **保留邊緣**的平滑（雙邊濾波） | 美顏、需保邊的場合（慢） |

### 9.2 Kernel 大小規則（必考）

- **必須是正奇數（positive odd numbers）**：3、5、7、11、21…
- **數字越大 → 模糊越強**。
- 為什麼要奇數？因為 kernel 需要一個明確的中心像素。

```python
blurred = cv2.blur(image, (5, 5))                     # 5x5 平均
blurred = cv2.GaussianBlur(image, (21, 21), 0)        # 21x21 高斯（很模糊）
blurred = cv2.medianBlur(image, 5)                    # 5x5 中位數（單一數字！）
```

> ⚠️ `cv2.medianBlur()` 只收 **一個整數**，不是 tuple。

### 9.3 Gaussian 的 sigma 參數

```python
cv2.GaussianBlur(src, ksize, sigmaX, sigmaY=0, borderType=...)
```

- `sigmaX = 0` → **由 kernel 大小自動推算**（實務上幾乎都填 0）。
- sigma 越大，模糊越強。

### 9.4 Bilateral Filter 三個參數

```python
cv2.bilateralFilter(src, d, sigmaColor, sigmaSpace)
```

| 參數 | 意義 |
|------|------|
| `d` | 鄰域直徑（設 5–9 常見；-1 表示由 sigmaSpace 推算） |
| `sigmaColor` | 顏色相似度容忍度（**越大 → 越多顏色混合**） |
| `sigmaSpace` | 空間距離容忍度（越大 → 越遠的像素也納入） |

**關鍵**：一般模糊會把邊緣也糊掉；**bilateral 只模糊「顏色相近」的區域，所以邊界保留**。

### 9.5 卷積原理（考概念題用）

以 3×3 平均濾波為例：

```
Kernel = 1/9 * [[1,1,1],
                [1,1,1],
                [1,1,1]]
新像素值 = Σ(kernel × 對應鄰域像素)
```

- **卷積核總和 = 1** → 整體亮度不變。
- 總和 > 1 → 變亮；< 1 → 變暗。
- 二階微分核（Laplacian）總和 = 0 → 找邊緣。

### 9.6 形態學濾波（Morphological Operations）——程式碼重點

處理**二值圖（binary mask）**的形狀運算：

| 操作 | API | 效果 |
|------|-----|------|
| **Erosion 侵蝕** | `cv2.erode(mask, kernel, iterations=1)` | **白色區域縮小**，移除細小雜訊點 |
| **Dilation 膨脹** | `cv2.dilate(mask, kernel, iterations=1)` | **白色區域擴大**，填補小洞 |
| **Opening 開運算** | `cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)` | **先侵蝕再膨脹** → 移除背景小白點（去雜訊） |
| **Closing 閉運算** | `cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)` | **先膨脹再侵蝕** → 填補物件內小黑洞 |
| **Gradient 梯度** | `cv2.MORPH_GRADIENT` | 膨脹 − 侵蝕 = 物件輪廓 |

```python
kernel = np.ones((5, 5), np.uint8)          # 5x5 的「刷子」
eroded_mask  = cv2.erode(mask, kernel, iterations=1)
dilated_mask = cv2.dilate(mask, kernel, iterations=1)
opened_mask  = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
```

**記憶法**：
- **侵蝕**：白色變瘦 → 小黑點消失。
- **膨脹**：白色變胖 → 小黑洞被填。
- **Opening**：先去斑（remove background specks）。
- **Closing**：先補洞。
- 兩者順序相反，**「開」= 先侵蝕，「閉」= 先膨脹**。

### 9.7 濾波器選擇決策表

| 情境 | 建議 |
|------|------|
| 只是要快、不在意細節 | `cv2.blur()` |
| 一般前處理（**預設答案**） | `cv2.GaussianBlur()` |
| 椒鹽雜訊 / 黑白斑點 | `cv2.medianBlur()` |
| 要平滑但保留邊緣 | `cv2.bilateralFilter()` |
| 二值 mask 去雜點 | `cv2.morphologyEx(..., MORPH_OPEN, ...)` |
| 二值 mask 補洞 | `cv2.morphologyEx(..., MORPH_CLOSE, ...)` |

### 9.8 總結

> **Filtering improves image quality** —— 濾波能提升影像品質，是後續邊緣偵測與特徵擷取成功的關鍵前提。


---

## 10. Edge Detection

> **邊緣**：影像中亮度（強度）急劇變化（steep intensity gradient）的位置 —— 通常就是物件的輪廓。

### 10.1 PDF 列出的三種方法

| 方法 | API | 特性 | 說明 |
|------|-----|------|------|
| **Sobel** | `cv2.Sobel(src, ddepth, dx, dy, ksize)` | **偵測梯度（gradient）** | 一階微分，分水平 / 垂直方向；`dx=1, dy=0` 找垂直邊，`dx=0, dy=1` 找水平邊 |
| **Laplacian** | `cv2.Laplacian(src, ddepth, ksize)` | **突顯快速強度變化** | 二階微分，一次抓所有方向的邊（對雜訊敏感） |
| **Canny** | `cv2.Canny(image, threshold1, threshold2)` | **準確的邊緣偵測**（業界標準） | 多階段：去雜訊 → 算梯度 → 非極大值抑制 → 雙門檻 + 遲滯 |

### 10.2 Sobel 詳解

```python
sobel_x = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=3)   # 水平梯度（找垂直邊）
sobel_y = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=3)   # 垂直梯度（找水平邊）

# 因為可能出現負值，要取絕對值並轉回 uint8
sobel_x = cv2.convertScaleAbs(sobel_x)
sobel_y = cv2.convertScaleAbs(sobel_y)
sobel_combined = cv2.addWeighted(sobel_x, 0.5, sobel_y, 0.5, 0)
```

- `ddepth = cv2.CV_64F`：**必須用浮點數**，否則負梯度會被截成 0。

### 10.3 Laplacian 詳解

```python
laplacian = cv2.Laplacian(gray, cv2.CV_64F)
laplacian = cv2.convertScaleAbs(laplacian)
```

- 二階微分，**對雜訊非常敏感** → 使用前務必先 Gaussian Blur。

### 10.4 Canny 詳解（最重要）

```python
edges = cv2.Canny(image, threshold1=100, threshold2=200)
```

| 參數 | 說明 |
|------|------|
| `image` | **單通道 8-bit 灰階圖**（彩色要先 `cvtColor`） |
| `threshold1` | **低門檻**：較低 → 偵測到較多（較弱的）邊緣 |
| `threshold2` | **高門檻**：較高 → 只保留強邊緣 |
| `apertureSize` | Sobel kernel 大小，預設 3 |
| `L2gradient` | `True` 用較精確的梯度公式（較慢） |

**雙門檻 + 遲滯（hysteresis）機制 —— 考概念題必答**

1. 梯度 **> threshold2** → **確定是邊緣**（strong edge），保留。
2. 梯度 **< threshold1** → **確定不是邊緣**，丟棄。
3. 介於兩者之間（weak edge）→ **只有連接到強邊緣時才保留**。

→ 所以 **低門檻越低 → 邊越多（也越多雜訊）；高門檻越高 → 邊越少越乾淨**。

**建議比例**：`threshold2 : threshold1 ≈ 2:1` 或 `3:1`。

**完整 Canny 流程**

```python
import cv2
import matplotlib.pyplot as plt
import urllib.request

# 1. 下載範例圖
url = "https://raw.githubusercontent.com/opencv/opencv/master/samples/data/smarties.png"
urllib.request.urlretrieve(url, "smarties.png")

# 2. 讀圖並轉灰階（邊緣偵測只在單通道上運作）
image_bgr = cv2.imread("smarties.png")
image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
gray      = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2GRAY)

# 3. Canny 邊緣偵測
edges = cv2.Canny(gray, threshold1=100, threshold2=200)

# 4. 顯示
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1); plt.imshow(image_rgb); plt.title("Original Photo"); plt.axis("off")
plt.subplot(1, 2, 2); plt.imshow(edges, cmap="gray"); plt.title("Canny Edge Outlines"); plt.axis("off")
plt.show()
```

### 10.5 邊緣偵測後：找輪廓（Find Contours）——

```python
contours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
```

| 參數 | 常見值 |
|------|--------|
| `mode` | `cv2.RETR_EXTERNAL`（只取最外層）、`RETR_LIST`（全部）、`RETR_TREE`（含階層） |
| `method` | `cv2.CHAIN_APPROX_SIMPLE`（壓縮線段）、`CHAIN_APPROX_NONE`（全部點） |

> ⚠️ **OpenCV 4.x / 5.x** 回傳 **2 個值**（`contours, hierarchy`）；OpenCV 3.x 回傳 3 個值。這是版本陷阱題。

**邊界框（Bounding Boxes）**

```python
for c in contours:
    x, y, w, h = cv2.boundingRect(c)                  # 軸對齊矩形
    cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)

    rect = cv2.minAreaRect(c)                         # 最小面積旋轉矩形
    box  = cv2.boxPoints(rect).astype(int)
    cv2.drawContours(image, [box], 0, (0, 0, 255), 2)

    area = cv2.contourArea(c)                         # 面積（過濾小雜點）
    if area < 100:
        continue
```

**形狀遮罩（Shape Masking）**

```python
mask = np.zeros(gray.shape, dtype=np.uint8)
cv2.drawContours(mask, [largest_contour], -1, 255, thickness=-1)   # 填滿輪廓
isolated = cv2.bitwise_and(image, image, mask=mask)                # 只留下目標
```

### 10.6 總結

> **Edges help identify object boundaries** —— 邊緣幫助辨識物件邊界，是分割、量測、追蹤的基礎。


---

## 11. Feature Extraction

> **特徵（Feature）**：影像中**獨特、可重複偵測**的局部圖案，例如角點（corner）、邊、斑塊（blob）。
> **關鍵性質**：對**尺度（scale）**、**旋轉（rotation）**、**光照（illumination）**變化要穩定 —— 這樣才能在不同照片中認出同一個物件。

### 11.1 PDF 列出的三種演算法

| 演算法 | 全名 | 特性 | 授權 |
|--------|------|------|------|
| **SIFT** | Scale-Invariant Feature Transform | **尺度不變**、旋轉不變，最穩健準確，但較慢 | 專利已於 2020 到期，OpenCV 主模組可用 |
| **SURF** | Speeded-Up Robust Features | **比 SIFT 更快**的近似版本 | 專利仍在，需 `opencv-contrib-python` 且常需編譯 `NONFREE` |
| **ORB** | Oriented FAST and Rotated BRIEF | **效率高且授權友善**（完全免費），速度快，適合即時應用 | 免費、無專利（**本課程用 ORB**） |

### 11.2 名詞定義

| 名詞 | 說明 |
|------|------|
| **Keypoint Detection 關鍵點偵測** | 在不同尺度與旋轉下，找出顯著且不變的興趣點（角點、邊） |
| **Feature Descriptors 特徵描述子** | 計算代表關鍵點周圍局部像素鄰域的**數值向量簽名（vector signature）** |

### 11.3 ORB 深入（課程實作重點）

**ORB = Oriented FAST（找關鍵點）+ Rotated BRIEF（做描述子）**

- **FAST**：非常快的角點偵測器（比較中心像素與周圍 16 個像素的亮度）。
- **Oriented**：加上方向計算（intensity centroid），使特徵具**旋轉不變性**。
- **BRIEF**：用二元（binary）位元比較產生描述子 → 因此**匹配時用 Hamming 距離**。
- **Rotated**：把 BRIEF 的取樣點旋轉到主方向 → 具旋轉不變性。
- **描述子維度**：ORB 預設 **32 bytes = 256 bits** → 所以 `descriptors.shape` 是 `(keypoints, 32)`。

**完整範例**

```python
import cv2
import numpy as np
import matplotlib.pyplot as plt
import urllib.request

# 1. 下載範例圖
url = "https://raw.githubusercontent.com/opencv/opencv/master/samples/data/smarties.png"
urllib.request.urlretrieve(url, "smarties.png")

# 2. 讀圖並轉灰階（特徵偵測在灰階上運作）
image_bgr = cv2.imread("smarties.png")
image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
gray      = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2GRAY)

# 3. 建立 ORB 偵測器物件
# nfeatures=500 → 最多找最強的 500 個特徵點
orb = cv2.ORB_create(nfeatures=500)

# 4. 找出關鍵點（位置）與描述子（指紋）
keypoints, descriptors = orb.detectAndCompute(gray, None)

# 5. 把關鍵點畫在圖上
# DRAW_RICH_KEYPOINTS 會畫出圓圈，顯示特徵的大小與方向
image_keypoints = cv2.drawKeypoints(
    image_rgb, keypoints, None, color=(0, 255, 0),
    flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

plt.figure(figsize=(6, 6))
plt.imshow(image_keypoints)
plt.title("ORB Keypoints Found (%d points)" % len(keypoints))
plt.axis("off")
plt.show()

# 6. 印出描述子矩陣形狀
print("Descriptors matrix shape (keypoints count, fingerprint size):", descriptors.shape)
```

**本機實測輸出（與 PDF 完全一致）**

```
keypoints: 493
descriptors: (493, 32)
```

### 11.4 `cv2.ORB_create()` 常用參數

| 參數 | 預設 | 說明 |
|------|------|------|
| `nfeatures` | 500 | 保留最強的特徵點數量上限 |
| `scaleFactor` | 1.2 | 金字塔每層的縮放比例 |
| `nlevels` | 8 | 影像金字塔層數 |
| `edgeThreshold` | 31 | 邊界忽略區域大小 |
| `fastThreshold` | 20 | FAST 角點門檻 |

### 11.5 三種演算法比較表（必背）

| 比較項 | SIFT | SURF | ORB |
|--------|------|------|-----|
| 尺度不變 | ✅ | ✅ | ✅ |
| 旋轉不變 | ✅ | ✅ | ✅ |
| 速度 | 慢 | 中 | **最快** |
| 準確度 | **最高** | 高 | 中 |
| 描述子型別 | float（128 維） | float（64/128 維） | **binary（256 bits = 32 bytes）** |
| 距離度量 | Euclidean | Euclidean | **Hamming** |
| 專利 / 授權 | 已到期 | 仍有 | **完全免費** |
| 適用 | 高精度離線任務 | 需較快又較準 | **即時 / 手機 / 嵌入式** |

### 11.6 總結

> **Features represent unique image patterns** —— 特徵代表影像中獨特的圖案，是把「像素」轉換成「可比較的數學描述」的橋樑。


---

## 12. Feature Matching

> **特徵匹配**：比較兩張圖的**描述子向量**，找出對應的同一個點 —— 這是物件辨識、拼接、AR 的核心。

### 12.1 PDF 列出的兩個匹配器

| 匹配器 | 全名 | 特性 | 適用 |
|--------|------|------|------|
| **BFMatcher** | Brute-Force Matcher | **直接比較所有描述子**（逐一計算距離），最簡單、最準 | 資料量小；想確保找到最佳匹配 |
| **FLANN** | Fast Library for Approximate Nearest Neighbors | **快速最近鄰搜尋**（近似演算法），大規模特徵時快很多 | 特徵點很多時（如 SIFT 上萬點） |

### 12.2 BFMatcher 詳解

```python
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
matches = bf.match(des1, des2)
```

| 參數 | 說明 |
|------|------|
| `normType` | **距離度量**：`cv2.NORM_HAMMING`（**用於 ORB / BRIEF 等 binary 描述子**）、`cv2.NORM_L2`（用於 SIFT / SURF 等 float 描述子） |
| `crossCheck` | `True` → **雙向驗證**：A 匹配 B，且 B 也匹配 A，才保留 → 可大幅減少錯誤匹配 |

**常用方法**

| 方法 | 回傳 | 用途 |
|------|------|------|
| `bf.match(des1, des2)` | 每個 query 點的**最佳 1 個**匹配 | 一般匹配 |
| `bf.knnMatch(des1, des2, k=2)` | 每個 query 的**最佳 k 個** | Lowe's ratio test |
| `bf.radiusMatch(...)` | 距離在門檻內的所有匹配 | 特定容差 |

### 12.3 Lowe's Ratio Test（過濾錯誤匹配，超常考）

```python
matches = bf.knnMatch(des1, des2, k=2)
good = []
for m, n in matches:
    if m.distance < 0.75 * n.distance:      # 最佳匹配明顯優於次佳
        good.append([m])
```

**原理**：如果最佳匹配與次佳匹配距離差不多，代表這個特徵不夠獨特（可能是誤配），所以丟掉。**比例門檻通常取 0.7–0.8**。

### 12.4 FLANN 詳解

```python
FLANN_INDEX_KDTREE = 1
index_params  = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)
search_params = dict(checks=50)

flann = cv2.FlannBasedMatcher(index_params, search_params)
matches = flann.knnMatch(des1, des2, k=2)
```

| 參數 | 說明 |
|------|------|
| `algorithm` | `FLANN_INDEX_KDTREE`（**用於 SIFT/SURF float 描述子**）或 `FLANN_INDEX_LSH`（**用於 ORB binary 描述子**） |
| `trees` | KD-tree 數量（越多越準越慢） |
| `checks` | 搜尋時檢查的次數（越多越準越慢） |

> ⚠️ **FLANN + ORB 要注意**：ORB 是 binary 描述子，KD-tree 不適用，需用 LSH（Locality Sensitive Hashing）。

### 12.5 完整範例：ORB + BFMatcher

```python
import cv2
import numpy as np
import matplotlib.pyplot as plt
import urllib.request

# 0. 準備影像
url = "https://raw.githubusercontent.com/opencv/opencv/master/samples/data/smarties.png"
urllib.request.urlretrieve(url, "smarties.png")

image_bgr = cv2.imread("smarties.png")
image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
gray      = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2GRAY)
orb       = cv2.ORB_create(nfeatures=500)

# 1. 建立旋轉版本作為「目標照片」
h, w = gray.shape
center = (w // 2, h // 2)
rotation_matrix = cv2.getRotationMatrix2D(center, angle=45, scale=1.0)

gray_rotated = cv2.warpAffine(gray, rotation_matrix, (w, h))
rgb_rotated  = cv2.warpAffine(image_rgb, rotation_matrix, (w, h))

# 2. 對兩張圖都取出關鍵點與描述子
kp1, des1 = orb.detectAndCompute(gray, None)
kp2, des2 = orb.detectAndCompute(gray_rotated, None)

# 3. 建立暴力匹配器（Brute-Force Matcher）
# NORM_HAMMING 用來量度 ORB 描述子之間的差異
# crossCheck=True 確保 A 匹配 B 時，B 也匹配 A（雙向驗證）
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)

# 4. 比較描述子，找出匹配對
matches = bf.match(des1, des2)

# 5. 依距離排序（距離越小 = 匹配越強）
matches = sorted(matches, key=lambda x: x.distance)

# 6. 畫出最強的前 30 個匹配
matched_image = cv2.drawMatches(
    image_rgb, kp1, rgb_rotated, kp2, matches[:30], None,
    flags=cv2.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)

plt.figure(figsize=(12, 6))
plt.imshow(matched_image)
plt.title("Top 30 Feature Matches (Original vs 45-Degree Rotated)")
plt.axis("off")
plt.show()
```

**本機實測輸出**

```
matches: 280
matched_image shape: (356, 826, 3)
```

### 12.6 `cv2.drawMatches()` 參數

```python
cv2.drawMatches(img1, kp1, img2, kp2, matches, outImg, matchColor, singlePointColor, matchesMask, flags)
```

| flags | 效果 |
|-------|------|
| `cv2.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS` | **只畫匹配線，不畫未匹配的點**（最常用） |
| `cv2.DrawMatchesFlags_DEFAULT` | 畫所有關鍵點 |
| `cv2.DrawMatchesFlags_DRAW_RICH_KEYPOINTS` | 顯示大小與方向 |

### 12.7 Homography 與 RANSAC

```python
src_pts = np.float32([kp1[m.queryIdx].pt for m in matches]).reshape(-1, 1, 2)
dst_pts = np.float32([kp2[m.trainIdx].pt for m in matches]).reshape(-1, 1, 2)

H, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)
print("Inliers:", int(mask.sum()), "/", len(matches))
```

| 概念 | 說明 |
|------|------|
| **Homography（單應性矩陣）** | 一個 **3×3** 矩陣，描述兩張圖之間的**幾何空間變換**（平面→平面） |
| **RANSAC** | **RANdom SAmple Consensus**：隨機抽樣估模型，反覆迭代，**剔除離群值（outliers）** |
| `reprojThreshold = 5.0` | 重投影誤差門檻（像素）；超過此值的匹配視為 outlier |
| 回傳 `mask` | 每個匹配是 inlier(1) 還是 outlier(0) |

**用途**：物件辨識（找出目標在畫面中的位置）、影像拼接、AR 平面疊圖。

### 12.8 四個重點

1. **BFMatcher 直接比較描述子**（brute-force，逐一比對）。
2. **FLANN 提供快速最近鄰搜尋**（approximate nearest neighbor）。
3. **用於物件辨識（object recognition）**。
4. **支援影像拼接（image stitching）與 AR（擴增實境）**。


---

## 13. Real-World Projects

課程列出五個實戰專案，以下補充實作要點：

### 13.1 Panorama Generation（全景圖生成）

- **流程**：ORB/SIFT 找特徵 → BFMatcher/FLANN 匹配 → RANSAC 找 Homography → `cv2.warpPerspective` 對齊 → 接縫融合（blending）。
- **關鍵**：多張圖要有 20–30% 重疊；用 `cv2.Stitcher_create()` 可一鍵完成。
- **難點**：曝光差異（需 blending）、接縫鬼影（需 multi-band blending）。

### 13.2 Visual SLAM（視覺同時定位與建圖）

- **全名**：Simultaneous Localization and Mapping。
- **流程**：特徵擷取 → 特徵匹配 → 估相機運動（Essential / Fundamental Matrix）→ 三角化建 3D 點 → 迴環偵測（loop closure）。
- **用途**：機械人自主導航、無人機、AR 眼鏡。
- **常用**：ORB-SLAM 系列（就是用 ORB！）。

### 13.3 Object Tracking（物件追蹤）

- **傳統方法**：背景相減 `cv2.createBackgroundSubtractorMOG2()`、光流 `cv2.calcOpticalFlowPyrLK()`。
- **現代方法**：OpenCV 內建追蹤器 `cv2.TrackerCSRT_create()`、`cv2.TrackerKCF_create()`（先框選目標，再逐格追蹤）。
- **流程**：初始化 ROI → 逐格更新 → 重畫邊界框。
- **用途**：人流統計、運動分析、交通監控。

### 13.4 Augmented Reality（擴增實境）

- **流程**：偵測 marker（**ArUco**）或平面特徵 → 算 pose（姿態）→ `cv2.projectPoints` 投影 3D 模型 → 疊加。
- **OpenCV 工具**：`cv2.aruco` 模組（marker 偵測 + 姿態估測）。
- **用途**：AR 貼紙、教育互動、虛擬試戴。

### 13.5 Industrial Quality Control（工業品質控制）

- **流程**：固定光源拍照 → 前處理（灰階 + 模糊 + 二值化）→ 輪廓 / 形態學 → 量測尺寸或比對模板 → 判定 OK/NG。
- **常用技術**：`cv2.matchTemplate()` 模板匹配、`cv2.contourArea()` 面積檢測、像素當量轉換（pixel → mm）。
- **優勢**：24 小時、不會疲勞、可測微米級尺寸。

### 13.6 五個專案對應的技術速查

| 專案 | 主要技術 | 課程章節 |
|------|---------|---------|
| Panorama | Feature Matching + Homography | 11, 12 |
| Visual SLAM | Feature + Camera Geometry | 11, 12 |
| Object Tracking | Background Subtraction / Optical Flow | 6, 9 |
| Augmented Reality | Marker Detection + Pose + Transform | 8, 12 |
| Industrial QC | Pre-processing + Contour + Measure | 5, 9, 10 |


---

## 14. OpenCV Programming Examples（程式範例）

> 本章完整收錄 課程的程式碼，並加上逐行解釋。
> **本機驗證**：以下所有程式碼已在 OpenCV 5.0.0 / NumPy 2.4.6 / Matplotlib 3.11.2 環境實際執行通過。

### 14.0 環境安裝與通用設定

```bash
pip install opencv-python numpy matplotlib
```

```python
import cv2
import numpy as np
import matplotlib.pyplot as plt
import urllib.request

print(cv2.__version__)     # 例如 5.0.0 或 4.10.0
```

**顯示圖片的兩種方式比較**

| 方式 | 語法 | 優點 | 缺點 |
|------|------|------|------|
| OpenCV 視窗 | `cv2.imshow()` + `cv2.waitKey(0)` | 原生、快 | 一次只能看一張，不能排版 |
| Matplotlib | `plt.subplot()` + `plt.imshow()` | **可並排對比多張圖、可存檔** | 需注意 BGR→RGB |

> **全部用 Matplotlib 的 `plt.subplot` 做並排對比** —— 因為教學上要同時看到「處理前 vs 處理後」。

**Matplotlib 顯示的三個必記細節**

1. `plt.imshow()` 接收的是 **RGB** → 用 `cv2.cvtColor(..., cv2.COLOR_BGR2RGB)` 轉換。
2. 灰階 / 二值圖要加 **`cmap="gray"`**，否則會用彩色 colormap 顯示。
3. `plt.axis("off")` 隱藏座標軸，畫面更乾淨。

---

### 14.1 Pre-processing

#### 14.1.1 概念

| 步驟 | 英文 | 內容 |
|------|------|------|
| **修正顏色** | Fix the Colors | OpenCV 預設以 **BGR** 順序載入照片。我們轉成 **RGB** 讓顏色正常顯示。 |
| **簡化影像** | Simplify Image | 移除顏色通道產生 **Grayscale**，並縮小像素尺寸以**加快處理時間**。 |
| **清理與濾波** | Clean & Filter | 套用 **Blurring** 消除不必要雜訊，用 **Thresholding** 取出乾淨的黑白形狀。 |

#### 14.1.2 範例一：顏色順序 BGR vs RGB

```python
import cv2
import numpy as np
import matplotlib.pyplot as plt

# 1. 建立一張 300x300、3 通道的黑色像素圖（Blue, Green, Red）
# np.zeros 建立全黑畫布（所有像素為 0）
image = np.zeros((300, 300, 3), dtype="uint8")

# 2. 在中間畫一個實心紅色方塊
# OpenCV 使用 (Blue, Green, Red) 順序 -> (0, 0, 255) 代表 255 紅色
cv2.rectangle(image, (50, 50), (250, 250), (0, 0, 255), -1)

# 3. 把 BGR（OpenCV 格式）轉成 RGB（Matplotlib 格式）
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# 4. 展示差異
plt.figure(figsize=(8, 4))

plt.subplot(1, 2, 1)
plt.imshow(image)                     # 因為原圖是 BGR，所以顯示成錯誤的顏色（藍色）
plt.title("Wrong Color (Raw BGR)")
plt.axis("off")

plt.subplot(1, 2, 2)
plt.imshow(image_rgb)                 # 轉換後顯示正確顏色（紅色）
plt.title("Correct Color (Converted RGB)")
plt.axis("off")

plt.show()
```

**逐行重點**

| 程式碼 | 說明 |
|--------|------|
| `np.zeros((300, 300, 3), dtype="uint8")` | 建立 (H, W, C) = (300, 300, 3) 的全黑畫布；`uint8` 是影像標準型別（0–255） |
| `cv2.rectangle(img, pt1, pt2, color, -1)` | `(50,50)` 左上角、`(250,250)` 右下角；**`-1` = 填滿** |
| `(0, 0, 255)` | **BGR** → 藍 0、綠 0、紅 255 = 紅色 |
| `cv2.cvtColor(image, cv2.COLOR_BGR2RGB)` | 關鍵修正：把通道順序對調 |
| `plt.subplot(1, 2, 1)` | 1 列 2 行，第 1 格 |

> **結論**：同一個陣列 `(0,0,255)`，在 OpenCV 眼中是紅色，在 Matplotlib 眼中是藍色 —— 這就是「Wrong Color」的原因。

#### 14.1.3 範例二：高斯模糊

```python
# 套用高斯模糊
# (21, 21) 是模糊強度 / kernel 大小（必須是正奇數）
# 奇數越大 = 模糊越強
blurred_image = cv2.GaussianBlur(image_rgb, (21, 21), 0)

# 顯示原圖 vs 模糊後
plt.figure(figsize=(8, 4))

plt.subplot(1, 2, 1)
plt.imshow(image_rgb)
plt.title("Original (Sharp Edges)")
plt.axis("off")

plt.subplot(1, 2, 2)
plt.imshow(blurred_image)
plt.title("Blurred (Smoothed Edges)")
plt.axis("off")

plt.show()
```

**重點**
- `ksize = (21, 21)`：**兩個數字都要是正奇數**，越大越模糊。
- `sigmaX = 0`：讓 OpenCV 依 kernel 大小自動計算標準差。
- 效果：紅色方塊的**硬邊變成漸層**（Sharp Edges → Smoothed Edges）。
- **為什麼要模糊**：消除雜訊，避免後續邊緣偵測把雜訊當成邊。

#### 14.1.4 前處理完整流程（可直接背）

```python
image_bgr = cv2.imread("photo.jpg")
image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)      # 1. 修顏色
gray      = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2GRAY)     # 2. 簡化（灰階）
small     = cv2.resize(gray, (300, 300))                    #    縮小加速
blurred   = cv2.GaussianBlur(small, (21, 21), 0)            # 3. 去雜訊
_, binary = cv2.threshold(blurred, 127, 255, cv2.THRESH_BINARY)  # 4. 二值化
```


---

### 14.2 Matrix Operations

#### 14.2.1 概念

| 操作 | 英文 | 說明 |
|------|------|------|
| **裁剪與 ROI** | Cropping & ROI | 用 2D 陣列座標 **`[Y, X]`** 切出特定子網格，取出感興趣區域（Region of Interest） |
| **繪製疊加層** | Draw Overlays | **直接覆寫矩陣的像素值**，加上邊界框、目標圓、文字標籤 |
| **翻轉與旋轉** | Flip & Rotate | **重新索引像素位置**，做水平鏡像或順時針旋轉像素網格 |
| **矩陣混合** | Matrix Blending | 用**加權加法數學**合併兩個影像矩陣，做出半透明疊圖 |

#### 14.2.2 範例一：ROI 裁剪

```python
import cv2
import numpy as np
import matplotlib.pyplot as plt
import urllib.request

# 下載範例圖片
url = "https://raw.githubusercontent.com/opencv/opencv/master/samples/data/smarties.png"
urllib.request.urlretrieve(url, "smarties.png")

# 載入並轉成 RGB
image_bgr = cv2.imread("smarties.png")
image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)

# 矩陣切片語法：image[startY : endY, startX : endX]
# 取出 Y=100 到 300、X=150 到 350 的像素
cropped_roi = image_rgb[100:300, 150:350]

# 顯示完整矩陣 vs 切出的子矩陣
plt.figure(figsize=(8, 4))

plt.subplot(1, 2, 1)
plt.imshow(image_rgb)
plt.title("Full Pixel Grid (512x512)")
plt.axis("off")

plt.subplot(1, 2, 2)
plt.imshow(cropped_roi)
plt.title("Cropped ROI Sub-Grid (200x200)")
plt.axis("off")

plt.show()
```

**重點**
- 切片語法 `image[startY:endY, startX:endX]`：**先 Y（列）後 X（行）**。
- `100:300` → 高度 200 列；`150:350` → 寬度 200 行 → 結果是 **200×200** 的子圖。
- 原始圖片實際尺寸為 **413×356**（寬×高），但這是一張設計好的教學圖，所以切片後是乾淨的 200×200 區域。
- ROI 是**視圖（view）**，改它會改到原圖。

#### 14.2.3 範例二：矩陣混合 / 藍色疊圖

```python
# 1. 建立一張形狀相同的深藍色疊加層矩陣
blue_tint = np.zeros_like(image_rgb)
blue_tint[:, :, 2] = 220          # 設定 Blue 通道（index 2）強度為 220

# 2. 把原圖（70% 權重）與藍色層（30% 權重）混合
# 語法：cv2.addWeighted(img1, weight1, img2, weight2, gamma_offset)
blended_photo = cv2.addWeighted(image_rgb, 0.7, blue_tint, 0.3, 0)

plt.figure(figsize=(8, 4))

plt.subplot(1, 2, 1)
plt.imshow(image_rgb)
plt.title("Original Matrix")
plt.axis("off")

plt.subplot(1, 2, 2)
plt.imshow(blended_photo)
plt.title("70% Image + 30% Blue Overlay")
plt.axis("off")

plt.show()
```

**逐行重點**

| 程式碼 | 說明 |
|--------|------|
| `np.zeros_like(image_rgb)` | 建立**形狀與型別完全相同**的全黑矩陣（避免尺寸不合） |
| `blue_tint[:, :, 2] = 220` | `: , :` = 全部列與行；`2` = **第 3 個通道**。在 **RGB** 順序中 index 2 = **Blue** |
| `cv2.addWeighted(a, 0.7, b, 0.3, 0)` | 公式：`dst = a*0.7 + b*0.3 + 0`，權重和 = 1 → 亮度整體不變 |

> ⚠️ **通道索引陷阱**：`image_rgb` 的 index 2 是 **Blue**；若用 `image_bgr` 則 index 2 是 **Red**。這是本課程最愛考的細節。

**公式推導（考計算題）**

若某像素原值為 `(200, 100, 50)`（RGB），藍色層為 `(0, 0, 220)`：

```
R = 200*0.7 + 0*0.3   + 0 = 140
G = 100*0.7 + 0*0.3   + 0 = 70
B = 50*0.7  + 220*0.3 + 0 = 35 + 66 = 101
→ 結果像素 = (140, 70, 101)
```

#### 14.2.4 補充：繪圖疊加與翻轉旋轉

```python
# --- Draw Overlays：直接在矩陣上覆寫像素 ---
overlay = image_rgb.copy()                                   # 先複製，保留原圖
cv2.rectangle(overlay, (100, 80), (250, 280), (0, 255, 0), 3)   # 綠色邊界框
cv2.circle(overlay, (175, 180), 8, (255, 0, 0), -1)             # 紅色中心點
cv2.putText(overlay, "Target", (100, 70),
            cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)      # 文字標籤

# --- Flip & Rotate：重新索引像素位置 ---
mirrored  = cv2.flip(image_rgb, 1)                                # 水平鏡像
upside    = cv2.flip(image_rgb, 0)                                # 上下翻轉
rotated   = cv2.rotate(image_rgb, cv2.ROTATE_90_CLOCKWISE)        # 順時針 90 度

# --- 並排顯示四張圖 ---
plt.figure(figsize=(12, 6))
for i, (img, title) in enumerate([
        (overlay,  "Draw Overlays"),
        (mirrored, "Horizontal Mirror"),
        (upside,   "Vertical Flip"),
        (rotated,  "Rotate 90 CW")], start=1):
    plt.subplot(2, 2, i)
    plt.imshow(img)
    plt.title(title)
    plt.axis("off")
plt.tight_layout()
plt.show()
```


---

### 14.3 Transformation and Filtering

#### 14.3.1 概念

| 操作 | 英文 | 說明 |
|------|------|------|
| **邊緣偵測** | Edge Detection | 用 **Canny 門檻**找出陡峭的強度梯度，突顯結構輪廓 |
| **尋找輪廓** | Find Contours | 沿偵測到的邊緣點，把連續的像素邊界曲線連接成**向量形狀輪廓** |
| **邊界框** | Bounding Boxes | 在獨立目標周圍套上**軸對齊矩形**或**最小面積包圍形狀** |
| **形狀遮罩** | Shape Masking | 把向量形狀畫到**二值遮罩**上，從整個畫面中裁出並隔離目標物件 |

#### 14.3.2 範例一：Canny 邊緣偵測

```python
import cv2
import numpy as np
import matplotlib.pyplot as plt
import urllib.request

# 1. 下載範例圖片
url = "https://raw.githubusercontent.com/opencv/opencv/master/samples/data/smarties.png"
urllib.request.urlretrieve(url, "smarties.png")

# 2. 載入並轉成灰階（邊緣偵測只在 1 個通道上運作）
image_bgr = cv2.imread("smarties.png")
image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
gray      = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2GRAY)

# 3. 套用 Canny 邊緣偵測器
# 語法：cv2.Canny(image, low_threshold, high_threshold)
# 門檻越低 → 偵測到越淡的邊；門檻越高 → 只保留很強的邊
edges = cv2.Canny(gray, threshold1=100, threshold2=200)

# 顯示原圖 vs 輪廓圖
plt.figure(figsize=(10, 5))

plt.subplot(1, 2, 1)
plt.imshow(image_rgb)
plt.title("Original Photo")
plt.axis("off")

plt.subplot(1, 2, 2)
plt.imshow(edges, cmap="gray")
plt.title("Canny Edge Outlines")
plt.axis("off")

plt.show()
```

**重點**
- 輸入**必須是單通道灰階**（`COLOR_BGR2GRAY`）。
- 輸出 `edges` 是 **單通道二值圖**（只有 0 和 255）→ 顯示時要 **`cmap="gray"`**。
- 結果：每個糖果球的**白色圓形外框**被畫出來（黑底白線）。
- 本機實測：邊緣像素數 = **3157** 個。

#### 14.3.3 範例二：形態學運算

```python
# 1. 建立一個 5x5 的全 1 網格（用來塑形的「刷子」/ kernel）
kernel = np.ones((5, 5), np.uint8)

# 2. 侵蝕（Erosion）：縮小白色區域 / 移除細小雜訊點
eroded_mask = cv2.erode(mask, kernel, iterations=1)

# 3. 膨脹（Dilation）：擴大白色區域 / 填補形狀內部的小洞
dilated_mask = cv2.dilate(mask, kernel, iterations=1)

# 4. 開運算（Opening，先侵蝕後膨脹）：最適合移除背景雜點
opened_mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)

# 顯示比較
plt.figure(figsize=(12, 6))

plt.subplot(2, 2, 1)
plt.imshow(mask, cmap="gray")
plt.title("Original Binary Mask")
plt.axis("off")

plt.subplot(2, 2, 2)
plt.imshow(eroded_mask, cmap="gray")
plt.title("1. Erosion (Thins edges/removes noise)")
plt.axis("off")

plt.subplot(2, 2, 3)
plt.imshow(dilated_mask, cmap="gray")
plt.title("2. Dilation (Thickens edges/fills holes)")
plt.axis("off")

plt.subplot(2, 2, 4)
plt.imshow(opened_mask, cmap="gray")
plt.title("3. Opening (Cleans background noise)")
plt.axis("off")

plt.tight_layout()
plt.show()
```

**`mask` 從哪裡來？** 先用二值化產生：

```python
gray = cv2.cvtColor(cv2.imread("smarties.png"), cv2.COLOR_BGR2GRAY)
_, mask = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY)
# 或用 HSV + inRange 抓特定顏色
```

**重點對照表**

| 操作 | 白色區域 | 主要效果 |
|------|---------|---------|
| Erosion | **變小** | 移除細小雜訊點、分離相連物件 |
| Dilation | **變大** | 填補小洞、連接斷開的部分 |
| Opening（侵蝕→膨脹） | 大致不變 | **移除背景小白點**（去雜訊） |
| Closing（膨脹→侵蝕） | 大致不變 | **填補物件內小黑洞** |

- `kernel` 用 `np.ones((5,5), np.uint8)`：5×5 的方形刷子。
- `iterations=1`：重複次數；**次數越多，效果越強**。
- `cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)` = `dilate(erode(mask))`。

#### 14.3.4 補充：找輪廓 + 邊界框 + 形狀遮罩

```python
# --- 1. Edge Detection ---
gray  = cv2.cvtColor(cv2.imread("smarties.png"), cv2.COLOR_BGR2GRAY)
blur  = cv2.GaussianBlur(gray, (5, 5), 0)          # 先模糊去雜訊（Canny 前必做）
edges = cv2.Canny(blur, 100, 200)

# --- 2. Find Contours ---
contours, hierarchy = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
print("找到輪廓數量:", len(contours))

# --- 3. Bounding Boxes ---
image_bgr = cv2.imread("smarties.png")
image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
result = image_rgb.copy()

for c in contours:
    if cv2.contourArea(c) < 50:            # 過濾太小的雜訊輪廓
        continue
    x, y, w, h = cv2.boundingRect(c)       # 軸對齊邊界框
    cv2.rectangle(result, (x, y), (x + w, y + h), (0, 255, 0), 2)

    rect = cv2.minAreaRect(c)              # 最小面積旋轉矩形
    box  = cv2.boxPoints(rect).astype(int)
    cv2.drawContours(result, [box], 0, (255, 0, 0), 1)

# --- 4. Shape Masking ---
mask = np.zeros(gray.shape, dtype=np.uint8)
largest = max(contours, key=cv2.contourArea)           # 最大輪廓
cv2.drawContours(mask, [largest], -1, 255, thickness=-1)   # 填滿該輪廓
isolated = cv2.bitwise_and(image_rgb, image_rgb, mask=mask)

# --- 顯示 ---
plt.figure(figsize=(12, 4))
for i, (img, t) in enumerate([(result, "Bounding Boxes"),
                              (mask, "Shape Mask"),
                              (isolated, "Isolated Target")], start=1):
    plt.subplot(1, 3, i)
    plt.imshow(img, cmap="gray" if img.ndim == 2 else None)
    plt.title(t)
    plt.axis("off")
plt.tight_layout()
plt.show()
```

**重要 API 速記**

| API | 用途 |
|-----|------|
| `cv2.findContours()` | 找輪廓 → 回傳 `(contours, hierarchy)` |
| `cv2.contourArea(c)` | 輪廓面積（過濾雜訊） |
| `cv2.arcLength(c, True)` | 輪廓周長（給 approxPolyDP 用） |
| `cv2.boundingRect(c)` | 軸對齊矩形 → `(x, y, w, h)` |
| `cv2.minAreaRect(c)` | 最小面積旋轉矩形 → `((cx, cy), (w, h), angle)` |
| `cv2.boxPoints(rect)` | 旋轉矩形的 4 個頂點 |
| `cv2.drawContours(img, [c], -1, color, -1)` | 畫 / 填滿輪廓 |
| `cv2.approxPolyDP(c, eps, True)` | 多邊形近似（判斷形狀用） |


---

### 14.4 Feature Extraction and Matching

#### 14.4.1 概念

| 步驟 | 英文 | 說明 |
|------|------|------|
| **關鍵點偵測** | Keypoint Detection | 在**不同尺度與旋轉**下，找出顯著且不變的興趣點（角點、邊） |
| **特徵描述子** | Feature Descriptors | 計算代表關鍵點周圍**局部像素鄰域**的數值向量簽名 |
| **描述子匹配** | Descriptor Matching | 用**距離度量**（如 Hamming 或 Euclidean 距離）比對兩張圖的描述子向量 |
| **單應性與 RANSAC** | Homography & RANSAC | 估計 **3×3 幾何空間變換**，並過濾掉錯誤的匹配離群值 |

#### 14.4.2 範例一：ORB 關鍵點偵測

```python
import cv2
import numpy as np
import matplotlib.pyplot as plt
import urllib.request

# 1. 下載範例圖片
url = "https://raw.githubusercontent.com/opencv/opencv/master/samples/data/smarties.png"
urllib.request.urlretrieve(url, "smarties.png")

# 2. 載入並轉成灰階（特徵偵測在灰階上運作）
image_bgr = cv2.imread("smarties.png")
image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
gray      = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2GRAY)

# 3. 建立 ORB 偵測器物件
# nfeatures=500 → 限制只搜尋最強的 500 個顯著特徵
orb = cv2.ORB_create(nfeatures=500)

# 4. 找出關鍵點（位置）與描述子（指紋）
keypoints, descriptors = orb.detectAndCompute(gray, None)

# 5. 把偵測到的關鍵點畫在圖上
# DRAW_RICH_KEYPOINTS 會畫出圓圈，顯示特徵的大小與方向
image_keypoints = cv2.drawKeypoints(
    image_rgb, keypoints, None, color=(0, 255, 0),
    flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

plt.figure(figsize=(6, 6))
plt.imshow(image_keypoints)
plt.title("ORB Keypoints Found (%d points)" % len(keypoints))
plt.axis("off")
plt.show()

# 印出描述子矩陣形狀，讓學生看到資料結構
print("Descriptors matrix shape (keypoints count, fingerprint size):", descriptors.shape)
```

**本機實測輸出（與 PDF 完全相同）**

```
keypoints: 493
Descriptors matrix shape (keypoints count, fingerprint size): (493, 32)
```

**解讀 `(493, 32)`**

- **493** = 偵測到的關鍵點數量（`nfeatures=500` 是上限，實際找到 493 個）。
- **32** = 每個特徵的描述子長度 = **32 bytes = 256 bits**（BRIEF 的二元指紋）。
- 所以 **第 i 個關鍵點** 的描述子就是 `descriptors[i]`，是一個 32 元素的 uint8 陣列。

**`drawKeypoints` 的 `flags` 比較**

| flags | 效果 |
|-------|------|
| `cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS` | **畫圓圈，圓大小 = 特徵尺度，含方向線**（教學用最清楚） |
| `cv2.DRAW_MATCHES_FLAGS_DEFAULT` | 只畫小圓點 |

#### 14.4.3 範例二：ORB + BFMatcher 特徵匹配

```python
# 1. 建立一張旋轉版本作為「目標照片」
h, w = gray.shape
center = (w // 2, h // 2)
rotation_matrix = cv2.getRotationMatrix2D(center, angle=45, scale=1.0)

gray_rotated = cv2.warpAffine(gray, rotation_matrix, (w, h))
rgb_rotated  = cv2.warpAffine(image_rgb, rotation_matrix, (w, h))

# 2. 對「兩張圖」都取出關鍵點與描述子
kp1, des1 = orb.detectAndCompute(gray, None)
kp2, des2 = orb.detectAndCompute(gray_rotated, None)

# 3. 建立暴力匹配器（Brute-Force Matcher）
# NORM_HAMMING 用來量度 ORB 描述子之間的差異
# crossCheck=True 確保 A 匹配 B 時，B 也匹配 A（雙向驗證）
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)

# 4. 比較描述子，找出匹配對
matches = bf.match(des1, des2)

# 5. 依距離排序（距離越小 = 匹配越強）
matches = sorted(matches, key=lambda x: x.distance)

# 6. 畫出最強的前 30 個匹配
matched_image = cv2.drawMatches(
    image_rgb, kp1, rgb_rotated, kp2, matches[:30], None,
    flags=cv2.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)

# 顯示匹配結果
plt.figure(figsize=(12, 6))
plt.imshow(matched_image)
plt.title("Top 30 Feature Matches (Original vs 45-Degree Rotated)")
plt.axis("off")
plt.show()
```

**本機實測輸出**

```
matches: 280
matched_image shape: (356, 826, 3)
```

**逐行重點**

| 程式碼 | 說明 |
|--------|------|
| `cv2.getRotationMatrix2D(center, 45, 1.0)` | 產生 **2×3** 旋轉矩陣；45 度（**正數 = 逆時針**） |
| `cv2.warpAffine(gray, M, (w, h))` | 套用仿射變換；`(w, h)` 是輸出尺寸 |
| `orb.detectAndCompute(img, None)` | 回傳 `(keypoints, descriptors)`；第二個參數是 mask（None = 全圖） |
| `cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)` | **ORB 用 Hamming 距離**；`crossCheck` 做雙向驗證 |
| `bf.match(des1, des2)` | 每個 des1 找 des2 中最近的 1 個 |
| `sorted(matches, key=lambda x: x.distance)` | **距離越小 = 越相似**，所以升序排序 |
| `matches[:30]` | 只取最好的 30 個（避免畫面太亂） |
| `DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS` | 只畫匹配連線 |

**`matches[i]` 物件的屬性**

| 屬性 | 意義 |
|------|------|
| `m.queryIdx` | 在第一張圖的關鍵點索引（`kp1` 的 index） |
| `m.trainIdx` | 在第二張圖的關鍵點索引（`kp2` 的 index） |
| `m.distance` | 兩個描述子之間的距離（越小越匹配） |

#### 14.4.4 為什麼 45 度旋轉後仍能匹配？

因為 ORB 的特徵具備 **旋轉不變性（rotation invariance）**：

1. FAST 偵測器找出角點。
2. 計算該點的**主方向**（intensity centroid）。
3. BRIEF 取樣點**旋轉到主方向**後才產生描述子。

→ 所以同一顆糖果球在原圖與旋轉圖上的描述子幾乎相同，能成功匹配。這也是 **Feature Matching 支援物件辨識與影像拼接** 的原因。

#### 14.4.5 完整進階範例：物件辨識（含 RANSAC 過濾）

```python
# 1. 匹配後取 good matches（Lowe's ratio test）
bf = cv2.BFMatcher(cv2.NORM_HAMMING)
raw = bf.knnMatch(des1, des2, k=2)
good = [m for m, n in raw if m.distance < 0.75 * n.distance]
print("Good matches:", len(good))

# 2. 取匹配點的座標
if len(good) > 10:
    src_pts = np.float32([kp1[m.queryIdx].pt for m in good]).reshape(-1, 1, 2)
    dst_pts = np.float32([kp2[m.trainIdx].pt for m in good]).reshape(-1, 1, 2)

    # 3. RANSAC 估 Homography（3x3 矩陣），剔除 outliers
    H, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)
    print("Inliers:", int(mask.sum()), "/", len(good))

    # 4. 用 Homography 把目標物框出來
    h, w = gray.shape
    corners = np.float32([[0, 0], [w, 0], [w, h], [0, h]]).reshape(-1, 1, 2)
    projected = cv2.perspectiveTransform(corners, H)
    cv2.polylines(rgb_rotated, [np.int32(projected)], True, (0, 255, 0), 3)

    plt.imshow(rgb_rotated)
    plt.title("Detected Object via Homography + RANSAC")
    plt.axis("off")
    plt.show()
```

**關鍵概念（考概念題必答）**

| 概念 | 說明 |
|------|------|
| **Homography 矩陣** | 3×3 矩陣，描述兩平面之間的投影變換（8 個自由度） |
| **RANSAC 的作用** | 從含雜訊的匹配中，**迭代隨機抽樣**找出最多 inliers 的模型，**剔除 outliers** |
| **為什麼需要它** | `crossCheck` 與 ratio test 仍會有誤配，RANSAC 是最後一道防線 |
| **`mask`** | 布林/uint8 陣列，1 = inlier（可信任），0 = outlier |


---

## 15. Summary

### 15.1 五點總結

| # | 原文 | 中文解釋 |
|---|------|---------|
| 1 | OpenCV is a powerful computer vision toolkit | OpenCV 是功能強大的電腦視覺工具庫（2500+ 最佳化演算法、開源免費） |
| 2 | Pre-processing improves image quality | 前處理（轉色彩空間、縮放、去雜訊、二值化）能提升影像品質，是成功的前提 |
| 3 | Matrix operations enable image manipulation | 矩陣運算（切片 ROI、位元遮罩、加權混合）讓影像可以被任意操控 |
| 4 | Transformations and filters enhance analysis | 幾何變換與濾波（邊緣偵測、輪廓、形態學）強化分析能力 |
| 5 | Feature matching enables intelligent vision systems | 特徵匹配（ORB + BFMatcher + RANSAC）讓系統具備「智慧」——能辨識、定位、拼接 |

### 15.2 全課程流程圖（一頁看懂）

<!-- OPENCV-FIGURE:pipeline -->
<figure style="margin:20px 0;padding:14px 12px;background:#0d1117;border:1px solid #222b36;border-radius:12px;text-align:center;-webkit-print-color-adjust:exact;print-color-adjust:exact">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 900 1170" role="img" aria-label="OpenCV 12 步影像處理流程" style="width:100%;height:auto;display:block">
<defs>
<marker id="ain" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 z" fill="#2dd4bf"/></marker>
<marker id="apar" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 z" fill="#58a6ff"/></marker>
<marker id="aana" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 z" fill="#fbbf24"/></marker>
<marker id="afeat" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 z" fill="#c084fc"/></marker>
<marker id="agray" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 z" fill="#7d8590"/></marker>
</defs>
<rect x="0.75" y="0.75" width="898.5" height="1168.5" rx="16" fill="#0d1117" stroke="#222b36" stroke-width="1.5"/>
<text x="48" y="52" font-size="25" fill="#e6edf3" font-weight="700" font-family="'Segoe UI','Microsoft JhengHei','Noto Sans TC',sans-serif">OpenCV 影像處理 12 步流程</text>
<text x="48" y="82" font-size="14.5" fill="#8b949e" font-family="'Segoe UI','Microsoft JhengHei','Noto Sans TC',sans-serif">從讀取到 Homography：每一步用哪個 API、拿到什麼產出</text>
<rect x="150" y="120" width="600" height="64" rx="10" fill="#161b22" stroke="#2dd4bf66" stroke-width="1.5"/>
<circle cx="182" cy="152.0" r="15" fill="#2dd4bf" opacity="0.92"/>
<text x="182" y="157.5" font-size="14" fill="#08141a" font-weight="700" text-anchor="middle" font-family="'Segoe UI','Microsoft JhengHei','Noto Sans TC',sans-serif">1</text>
<text x="210" y="147" font-size="15.5" fill="#e6edf3" font-weight="700" font-family="'Segoe UI','Microsoft JhengHei','Noto Sans TC',sans-serif">讀取　cv2.imread()</text>
<text x="210" y="168" font-size="12" fill="#8b949e" font-family="'Segoe UI','Microsoft JhengHei','Noto Sans TC',sans-serif">得到 BGR 的 NumPy 矩陣</text>
<rect x="150" y="202" width="600" height="64" rx="10" fill="#161b22" stroke="#2dd4bf66" stroke-width="1.5"/>
<circle cx="182" cy="234.0" r="15" fill="#2dd4bf" opacity="0.92"/>
<text x="182" y="239.5" font-size="14" fill="#08141a" font-weight="700" text-anchor="middle" font-family="'Segoe UI','Microsoft JhengHei','Noto Sans TC',sans-serif">2</text>
<text x="210" y="229" font-size="15.5" fill="#e6edf3" font-weight="700" font-family="'Segoe UI','Microsoft JhengHei','Noto Sans TC',sans-serif">色彩空間　cvtColor()</text>
<text x="210" y="250" font-size="12" fill="#8b949e" font-family="'Segoe UI','Microsoft JhengHei','Noto Sans TC',sans-serif">BGR → RGB / Gray / HSV / LAB</text>
<rect x="150" y="284" width="600" height="64" rx="10" fill="#161b22" stroke="#2dd4bf66" stroke-width="1.5"/>
<circle cx="182" cy="316.0" r="15" fill="#2dd4bf" opacity="0.92"/>
<text x="182" y="321.5" font-size="14" fill="#08141a" font-weight="700" text-anchor="middle" font-family="'Segoe UI','Microsoft JhengHei','Noto Sans TC',sans-serif">3</text>
<text x="210" y="311" font-size="15.5" fill="#e6edf3" font-weight="700" font-family="'Segoe UI','Microsoft JhengHei','Noto Sans TC',sans-serif">前處理</text>
<text x="210" y="332" font-size="12" fill="#8b949e" font-family="'Segoe UI','Microsoft JhengHei','Noto Sans TC',sans-serif">resize → blur → threshold</text>
<path d="M 450.0 184 L 450.0 200" fill="none" stroke="#7d8590" stroke-width="2" marker-end="url(#ain)"/>
<path d="M 450.0 266 L 450.0 282" fill="none" stroke="#7d8590" stroke-width="2" marker-end="url(#ain)"/>
<path d="M 450.0 348 L 450.0 372" fill="none" stroke="#7d8590" stroke-width="2"/>
<path d="M 200.0 372 L 700.0 372" fill="none" stroke="#7d8590" stroke-width="2"/>
<path d="M 200.0 372 L 200.0 394" fill="none" stroke="#7d8590" stroke-width="2" marker-end="url(#apar)"/>
<path d="M 450.0 372 L 450.0 394" fill="none" stroke="#7d8590" stroke-width="2" marker-end="url(#apar)"/>
<path d="M 700.0 372 L 700.0 394" fill="none" stroke="#7d8590" stroke-width="2" marker-end="url(#apar)"/>
<rect x="90" y="396" width="220" height="84" rx="10" fill="#1c2230" stroke="#58a6ff66" stroke-width="1.5"/>
<circle cx="114" cy="420" r="13" fill="#58a6ff" opacity="0.92"/>
<text x="114" y="425" font-size="12.5" fill="#08141a" font-weight="700" text-anchor="middle" font-family="'Segoe UI','Microsoft JhengHei','Noto Sans TC',sans-serif">4</text>
<text x="134" y="426" font-size="14.5" fill="#e6edf3" font-weight="700" font-family="'Segoe UI','Microsoft JhengHei','Noto Sans TC',sans-serif">矩陣運算</text>
<text x="106" y="456" font-size="11.5" fill="#8b949e" font-family="'Segoe UI','Microsoft JhengHei','Noto Sans TC',sans-serif">ROI / 遮罩 / 混合</text>
<rect x="340" y="396" width="220" height="84" rx="10" fill="#1c2230" stroke="#58a6ff66" stroke-width="1.5"/>
<circle cx="364" cy="420" r="13" fill="#58a6ff" opacity="0.92"/>
<text x="364" y="425" font-size="12.5" fill="#08141a" font-weight="700" text-anchor="middle" font-family="'Segoe UI','Microsoft JhengHei','Noto Sans TC',sans-serif">5</text>
<text x="384" y="426" font-size="14.5" fill="#e6edf3" font-weight="700" font-family="'Segoe UI','Microsoft JhengHei','Noto Sans TC',sans-serif">繪圖標註</text>
<text x="356" y="456" font-size="11.5" fill="#8b949e" font-family="'Segoe UI','Microsoft JhengHei','Noto Sans TC',sans-serif">line / rect / text</text>
<rect x="590" y="396" width="220" height="84" rx="10" fill="#1c2230" stroke="#58a6ff66" stroke-width="1.5"/>
<circle cx="614" cy="420" r="13" fill="#58a6ff" opacity="0.92"/>
<text x="614" y="425" font-size="12.5" fill="#08141a" font-weight="700" text-anchor="middle" font-family="'Segoe UI','Microsoft JhengHei','Noto Sans TC',sans-serif">6</text>
<text x="634" y="426" font-size="14.5" fill="#e6edf3" font-weight="700" font-family="'Segoe UI','Microsoft JhengHei','Noto Sans TC',sans-serif">幾何變換</text>
<text x="606" y="456" font-size="11.5" fill="#8b949e" font-family="'Segoe UI','Microsoft JhengHei','Noto Sans TC',sans-serif">warpAffine / Perspective</text>
<path d="M 200.0 480 L 200.0 504" fill="none" stroke="#7d8590" stroke-width="2"/>
<path d="M 450.0 480 L 450.0 504" fill="none" stroke="#7d8590" stroke-width="2"/>
<path d="M 700.0 480 L 700.0 504" fill="none" stroke="#7d8590" stroke-width="2"/>
<path d="M 200.0 504 L 700.0 504" fill="none" stroke="#7d8590" stroke-width="2"/>
<path d="M 450.0 504 L 450.0 538" fill="none" stroke="#7d8590" stroke-width="2" marker-end="url(#aana)"/>
<rect x="150" y="540" width="600" height="64" rx="10" fill="#161b22" stroke="#fbbf2466" stroke-width="1.5"/>
<circle cx="182" cy="572.0" r="15" fill="#fbbf24" opacity="0.92"/>
<text x="182" y="577.5" font-size="14" fill="#08141a" font-weight="700" text-anchor="middle" font-family="'Segoe UI','Microsoft JhengHei','Noto Sans TC',sans-serif">7</text>
<text x="210" y="567" font-size="15.5" fill="#e6edf3" font-weight="700" font-family="'Segoe UI','Microsoft JhengHei','Noto Sans TC',sans-serif">濾波</text>
<text x="210" y="588" font-size="12" fill="#8b949e" font-family="'Segoe UI','Microsoft JhengHei','Noto Sans TC',sans-serif">Gaussian / Median / Bilateral / Morphology</text>
<rect x="150" y="622" width="600" height="64" rx="10" fill="#161b22" stroke="#fbbf2466" stroke-width="1.5"/>
<circle cx="182" cy="654.0" r="15" fill="#fbbf24" opacity="0.92"/>
<text x="182" y="659.5" font-size="14" fill="#08141a" font-weight="700" text-anchor="middle" font-family="'Segoe UI','Microsoft JhengHei','Noto Sans TC',sans-serif">8</text>
<text x="210" y="649" font-size="15.5" fill="#e6edf3" font-weight="700" font-family="'Segoe UI','Microsoft JhengHei','Noto Sans TC',sans-serif">邊緣　Canny()</text>
<text x="210" y="670" font-size="12" fill="#8b949e" font-family="'Segoe UI','Microsoft JhengHei','Noto Sans TC',sans-serif">Canny 邊緣偵測</text>
<rect x="150" y="704" width="600" height="64" rx="10" fill="#161b22" stroke="#fbbf2466" stroke-width="1.5"/>
<circle cx="182" cy="736.0" r="15" fill="#fbbf24" opacity="0.92"/>
<text x="182" y="741.5" font-size="14" fill="#08141a" font-weight="700" text-anchor="middle" font-family="'Segoe UI','Microsoft JhengHei','Noto Sans TC',sans-serif">9</text>
<text x="210" y="731" font-size="15.5" fill="#e6edf3" font-weight="700" font-family="'Segoe UI','Microsoft JhengHei','Noto Sans TC',sans-serif">輪廓 / 邊界框</text>
<text x="210" y="752" font-size="12" fill="#8b949e" font-family="'Segoe UI','Microsoft JhengHei','Noto Sans TC',sans-serif">findContours → boundingRect</text>
<rect x="150" y="786" width="600" height="64" rx="10" fill="#161b22" stroke="#c084fc66" stroke-width="1.5"/>
<circle cx="182" cy="818.0" r="15" fill="#c084fc" opacity="0.92"/>
<text x="182" y="823.5" font-size="14" fill="#08141a" font-weight="700" text-anchor="middle" font-family="'Segoe UI','Microsoft JhengHei','Noto Sans TC',sans-serif">10</text>
<text x="210" y="813" font-size="15.5" fill="#e6edf3" font-weight="700" font-family="'Segoe UI','Microsoft JhengHei','Noto Sans TC',sans-serif">特徵　ORB_create()</text>
<text x="210" y="834" font-size="12" fill="#8b949e" font-family="'Segoe UI','Microsoft JhengHei','Noto Sans TC',sans-serif">keypoints + descriptors</text>
<rect x="150" y="868" width="600" height="64" rx="10" fill="#161b22" stroke="#c084fc66" stroke-width="1.5"/>
<circle cx="182" cy="900.0" r="15" fill="#c084fc" opacity="0.92"/>
<text x="182" y="905.5" font-size="14" fill="#08141a" font-weight="700" text-anchor="middle" font-family="'Segoe UI','Microsoft JhengHei','Noto Sans TC',sans-serif">11</text>
<text x="210" y="895" font-size="15.5" fill="#e6edf3" font-weight="700" font-family="'Segoe UI','Microsoft JhengHei','Noto Sans TC',sans-serif">匹配　BFMatcher</text>
<text x="210" y="916" font-size="12" fill="#8b949e" font-family="'Segoe UI','Microsoft JhengHei','Noto Sans TC',sans-serif">+ Lowe ratio test</text>
<rect x="150" y="950" width="600" height="64" rx="10" fill="#161b22" stroke="#c084fc66" stroke-width="1.5"/>
<circle cx="182" cy="982.0" r="15" fill="#c084fc" opacity="0.92"/>
<text x="182" y="987.5" font-size="14" fill="#08141a" font-weight="700" text-anchor="middle" font-family="'Segoe UI','Microsoft JhengHei','Noto Sans TC',sans-serif">12</text>
<text x="210" y="977" font-size="15.5" fill="#e6edf3" font-weight="700" font-family="'Segoe UI','Microsoft JhengHei','Noto Sans TC',sans-serif">Homography + RANSAC</text>
<text x="210" y="998" font-size="12" fill="#8b949e" font-family="'Segoe UI','Microsoft JhengHei','Noto Sans TC',sans-serif">→ 辨識 / 拼接 / AR</text>
<path d="M 450.0 604 L 450.0 620" fill="none" stroke="#fbbf24" stroke-width="2" marker-end="url(#aana)"/>
<path d="M 450.0 686 L 450.0 702" fill="none" stroke="#fbbf24" stroke-width="2" marker-end="url(#aana)"/>
<path d="M 450.0 768 L 450.0 784" fill="none" stroke="#c084fc" stroke-width="2" marker-end="url(#afeat)"/>
<path d="M 450.0 850 L 450.0 866" fill="none" stroke="#c084fc" stroke-width="2" marker-end="url(#afeat)"/>
<path d="M 450.0 932 L 450.0 948" fill="none" stroke="#c084fc" stroke-width="2" marker-end="url(#afeat)"/>
<circle cx="55" cy="1056" r="7" fill="#2dd4bf"/>
<text x="70" y="1060" font-size="13" fill="#8b949e" font-family="'Segoe UI','Microsoft JhengHei','Noto Sans TC',sans-serif">輸入／前處理</text>
<circle cx="270" cy="1056" r="7" fill="#58a6ff"/>
<text x="285" y="1060" font-size="13" fill="#8b949e" font-family="'Segoe UI','Microsoft JhengHei','Noto Sans TC',sans-serif">平行處理</text>
<circle cx="485" cy="1056" r="7" fill="#fbbf24"/>
<text x="500" y="1060" font-size="13" fill="#8b949e" font-family="'Segoe UI','Microsoft JhengHei','Noto Sans TC',sans-serif">影像分析</text>
<circle cx="700" cy="1056" r="7" fill="#c084fc"/>
<text x="715" y="1060" font-size="13" fill="#8b949e" font-family="'Segoe UI','Microsoft JhengHei','Noto Sans TC',sans-serif">特徵與匹配</text>
<text x="48" y="1102" font-size="13" fill="#8b949e" font-family="'Segoe UI','Microsoft JhengHei','Noto Sans TC',sans-serif">步驟 4–6 是三條平行路線：影像可以只做其中一項，也可以依序組合。</text>
</svg>
<figcaption style="font-size:13.5px;color:#9aa7b4;margin-top:10px;line-height:1.65;text-align:left">圖 1：OpenCV 的 12 步影像處理流程。步驟 4–6 是三條平行路線，其餘是主線；顏色代表四個階段（輸入／前處理 → 平行處理 → 影像分析 → 特徵與匹配）。</figcaption>
</figure>
<!-- /OPENCV-FIGURE -->

### 15.3 考試前最後檢查清單

- [ ] 我能說出 OpenCV 是什麼、誰維護、支援哪些語言、有多少演算法
- [ ] 我能列出 6 個 OpenCV 應用
- [ ] 我能比較 BGR / RGB / Gray / HSV / LAB 的用途
- [ ] 我記得 HSV 的 H 範圍是 **0–179**
- [ ] 我能寫出 `cv2.cvtColor()` 的 4 個常用 code
- [ ] 我能寫出完整前處理流程（修顏色 → 灰階 → resize → blur → threshold）
- [ ] 我知道 `cv2.resize` 的 dsize 是 **(W, H)**，而 `shape` 是 **(H, W, C)**
- [ ] 我知道切片是 `[y1:y2, x1:x2]`，**先 Y 後 X**
- [ ] 我記得繪圖座標是 **(x, y)**，`thickness=-1` 代表填滿
- [ ] 我記得 `cv2.add()` 會飽和，`+` 會溢位（uint8 300 → 44）
- [ ] 我能寫出 `cv2.addWeighted()` 的公式
- [ ] 我能分辨 `warpAffine`（2×3, 3 點）與 `warpPerspective`（3×3, 4 點）
- [ ] 我能說出 4 種濾波器的差別與適用場景
- [ ] 我記得 kernel 必須是**正奇數**
- [ ] 我能解釋 Canny 的雙門檻 + 遲滯機制
- [ ] 我能寫出 `cv2.findContours` 在 OpenCV 4/5 回傳 **2 個值**
- [ ] 我能比較 SIFT / SURF / ORB（速度、準確度、授權、距離度量）
- [ ] 我知道 ORB 用 **Hamming** 距離，描述子是 **32 bytes**
- [ ] 我能解釋 RANSAC 如何剔除 outliers
- [ ] 我能列出 5 個實戰專案


---

## 附錄 A：API 速查表

### A.1 讀取 / 顯示 / 儲存

| API | 說明 |
|-----|------|
| `cv2.imread(path, flag)` | 讀圖。flag：`cv2.IMREAD_COLOR`(1, 預設)、`IMREAD_GRAYSCALE`(0)、`IMREAD_UNCHANGED`(-1) |
| `cv2.imwrite(path, img)` | 存圖（回傳 True/False） |
| `cv2.imshow(name, img)` | 顯示（需配 `waitKey`） |
| `cv2.waitKey(ms)` | 等待按鍵；`0` = 無限等待，回傳按鍵 ASCII |
| `cv2.destroyAllWindows()` | 關閉全部視窗 |
| `cv2.VideoCapture(0)` | 開啟鏡頭 / 影片 |
| `cap.read()` | 讀取一格 → `(ret, frame)` |
| `cap.release()` | 釋放資源 |

### A.2 色彩空間

| API | 說明 |
|-----|------|
| `cv2.cvtColor(src, code)` | 色彩空間轉換 |
| `cv2.inRange(src, lower, upper)` | 依範圍產生遮罩 |
| `cv2.split(img)` / `cv2.merge([b,g,r])` | 分離 / 合併通道 |

### A.3 幾何與尺寸

| API | 說明 |
|-----|------|
| `cv2.resize(src, dsize, fx, fy, interpolation)` | 縮放（dsize = (W, H)） |
| `img[y1:y2, x1:x2]` | ROI 切片 |
| `cv2.flip(src, code)` | 1=水平, 0=垂直, -1=兩者 |
| `cv2.rotate(src, code)` | 90/180/270 度旋轉 |
| `cv2.warpAffine(src, M, dsize)` | 仿射變換（2×3 矩陣） |
| `cv2.getRotationMatrix2D(center, angle, scale)` | 產生旋轉矩陣 |
| `cv2.getAffineTransform(src_pts, dst_pts)` | 由 3 點產生仿射矩陣 |
| `cv2.getPerspectiveTransform(src_pts, dst_pts)` | 由 4 點產生透視矩陣 |
| `cv2.warpPerspective(src, M, dsize)` | 透視變換（3×3 矩陣） |

### A.4 濾波與形態學

| API | 說明 |
|-----|------|
| `cv2.blur(src, ksize)` | 平均模糊 |
| `cv2.GaussianBlur(src, ksize, sigmaX)` | 高斯模糊 |
| `cv2.medianBlur(src, k)` | 中位數模糊（k 是整數） |
| `cv2.bilateralFilter(src, d, sigmaColor, sigmaSpace)` | 雙邊濾波（保邊） |
| `cv2.erode(src, kernel, iterations)` | 侵蝕 |
| `cv2.dilate(src, kernel, iterations)` | 膨脹 |
| `cv2.morphologyEx(src, op, kernel)` | 開 / 閉 / 梯度 / 頂帽 / 黑帽 |
| `cv2.getStructuringElement(shape, ksize)` | 產生橢圓 / 十字 kernel |

### A.5 邊緣與輪廓

| API | 說明 |
|-----|------|
| `cv2.Sobel(src, ddepth, dx, dy, ksize)` | Sobel 梯度 |
| `cv2.Scharr(...)` | Scharr（Sobel 的精確版） |
| `cv2.Laplacian(src, ddepth)` | 拉普拉斯（二階微分） |
| `cv2.Canny(src, t1, t2)` | Canny 邊緣偵測 |
| `cv2.HoughLinesP(...)` | 直線偵測（車道線） |
| `cv2.HoughCircles(...)` | 圓形偵測 |
| `cv2.findContours(src, mode, method)` | 找輪廓 → `(contours, hierarchy)` |
| `cv2.contourArea(c)` / `cv2.arcLength(c, True)` | 面積 / 周長 |
| `cv2.boundingRect(c)` | 軸對齊邊界框 |
| `cv2.minAreaRect(c)` / `cv2.boxPoints(r)` | 旋轉邊界框 |
| `cv2.minEnclosingCircle(c)` | 最小外接圓 |
| `cv2.approxPolyDP(c, eps, True)` | 多邊形近似 |
| `cv2.convexHull(c)` | 凸包 |
| `cv2.matchTemplate(img, tpl, method)` | 模板匹配 |

### A.6 特徵與匹配

| API | 說明 |
|-----|------|
| `cv2.ORB_create(nfeatures=500)` | 建立 ORB 偵測器 |
| `cv2.SIFT_create()` | 建立 SIFT 偵測器（OpenCV 4.4+ 主模組可用） |
| `orb.detectAndCompute(img, mask)` | → `(keypoints, descriptors)` |
| `cv2.drawKeypoints(img, kp, out, color, flags)` | 畫關鍵點 |
| `cv2.BFMatcher(normType, crossCheck)` | 暴力匹配器 |
| `bf.match(des1, des2)` | 最佳 1 對 1 匹配 |
| `bf.knnMatch(des1, des2, k)` | 最佳 k 個匹配 |
| `cv2.FlannBasedMatcher(index_params, search_params)` | FLANN 快速匹配 |
| `cv2.drawMatches(...)` | 畫匹配結果 |
| `cv2.findHomography(src, dst, cv2.RANSAC, thresh)` | → `(H, mask)` |
| `cv2.perspectiveTransform(pts, H)` | 用 H 轉換座標 |

### A.7 繪圖與文字

| API | 說明 |
|-----|------|
| `cv2.line(img, pt1, pt2, color, thickness)` | 直線 |
| `cv2.rectangle(img, pt1, pt2, color, thickness)` | 矩形 |
| `cv2.circle(img, center, radius, color, thickness)` | 圓 |
| `cv2.ellipse(...)` | 橢圓 |
| `cv2.polylines(img, [pts], isClosed, color, thickness)` | 多邊形 |
| `cv2.fillPoly(img, [pts], color)` | 填滿多邊形 |
| `cv2.putText(img, text, org, font, scale, color, thickness, lineType)` | 文字 |
| `cv2.getTextSize(text, font, scale, thickness)` | 量文字尺寸 |
| `cv2.arrowedLine(...)` | 箭頭線 |

### A.8 常數對照

| 常數 | 值 / 說明 |
|------|----------|
| `cv2.COLOR_BGR2RGB` | 4 |
| `cv2.COLOR_BGR2GRAY` | 6 |
| `cv2.COLOR_BGR2HSV` | 40 |
| `cv2.COLOR_BGR2LAB` | 44 |
| `cv2.THRESH_BINARY` | 0 |
| `cv2.THRESH_BINARY_INV` | 1 |
| `cv2.THRESH_OTSU` | 8 |
| `cv2.NORM_HAMMING` | 6（binary 描述子用） |
| `cv2.NORM_L2` | 4（float 描述子用） |
| `cv2.RETR_EXTERNAL` | 0 |
| `cv2.CHAIN_APPROX_SIMPLE` | 2 |
| `cv2.MORPH_OPEN` / `MORPH_CLOSE` | 2 / 3 |
| `cv2.INTER_LINEAR` | 1 |
| `cv2.LINE_AA` | 16 |


---

## 附錄 B：常見錯誤與陷阱

### B.1 十大陷阱總表

| # | 陷阱 | 錯誤寫法 | 正確寫法 |
|---|------|---------|---------|
| 1 | **BGR vs RGB** | `plt.imshow(image_bgr)` 直接顯示 | `plt.imshow(cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB))` |
| 2 | **座標順序** | `image[x, y]` | `image[y, x]`（先列後行） |
| 3 | **切片順序** | `image[x1:x2, y1:y2]` | `image[y1:y2, x1:x2]` |
| 4 | **resize 尺寸** | `cv2.resize(img, image.shape)` | `cv2.resize(img, (width, height))` |
| 5 | **繪圖座標** | `cv2.rectangle(img, (y, x), ...)` | `cv2.rectangle(img, (x, y), ...)` |
| 6 | **uint8 溢位** | `image + 100` | `cv2.add(image, 100)` |
| 7 | **kernel 偶數** | `cv2.GaussianBlur(img, (20, 20), 0)` | `cv2.GaussianBlur(img, (21, 21), 0)` |
| 8 | **Canny 用彩色圖** | `cv2.Canny(image_bgr, 100, 200)` | 先 `cvtColor(..., COLOR_BGR2GRAY)` |
| 9 | **findContours 解包** | `_, contours, _ = cv2.findContours(...)` | `contours, _ = cv2.findContours(...)`（4.x/5.x） |
| 10 | **ORB 用 NORM_L2** | `cv2.BFMatcher(cv2.NORM_L2)` | `cv2.BFMatcher(cv2.NORM_HAMMING)` |

### B.2 執行期錯誤訊息對照

| 錯誤訊息 | 原因 | 解法 |
|---------|------|------|
| `(-215:Assertion failed) !_src.empty()` | `imread` 找不到檔案（回傳 `None`） | 檢查路徑；Windows 路徑用 `r"C:\..."` 或 `/` |
| `(-215) scn == 3 \|\| scn == 4` | 對灰階圖做只支援彩色的操作 | 先轉回 BGR，或改用灰階版本 API |
| `(-215) scn == 1` | Canny / threshold 收到彩色圖 | 先轉灰階 |
| `(-215) mv[i].size == mv[0].size` | `addWeighted` 兩圖尺寸不同 | 先 `resize` 成相同尺寸 |
| `(-215) ksize.width > 0 && ksize.width % 2 == 1` | kernel 是偶數或 0 | 用正奇數 |
| `(-215) type == CV_8UC1` | `findContours` 收到彩色圖 | 先二值化 / 轉灰階 |
| `has no attribute 'SIFT_create'` | 舊版本或缺少 contrib | `pip install opencv-contrib-python` |
| `cv2.cvtColor ... GRAY2HSV` | 灰階直接轉 HSV | 先 `GRAY2BGR` 再 `BGR2HSV` |
| `TypeError: Expected Ptr<cv::UMat>` | 傳入 Python list 而非 numpy array | 用 `np.array([...], np.float32)` |
| `plt.imshow` 顯示成彩色怪圖 | 灰階圖沒加 `cmap="gray"` | `plt.imshow(img, cmap="gray")` |

### B.3 `cv2.imshow` 常見問題

| 問題 | 原因 / 解法 |
|------|-----------|
| 視窗一片灰 / 沒畫面 | 沒有 `cv2.waitKey(0)` |
| 程式卡住不結束 | `waitKey(0)` 無限等待，要按鍵；改用 `waitKey(1)` |
| Jupyter / Colab 中沒視窗 | 不支援 GUI；改用 `matplotlib` 顯示 |

### B.4 中文路徑問題（Windows 常見）

```python
# 錯誤：含中文或反斜線被當轉義字元
cv2.imread("C:\Users\陳大文\圖片.png")

# 正確做法一：raw string
cv2.imread(r"C:\Users\princ\Downloads\photo.png")

# 正確做法二：正斜線
cv2.imread("C:/Users/princ/Downloads/photo.png")

# 正確做法三：中文路徑需用 imdecode
import numpy as np
img = cv2.imdecode(np.fromfile(path, dtype=np.uint8), cv2.IMREAD_COLOR)
```


---

## 附錄 C：離線執行提示

課程範例都靠 `urllib.request.urlretrieve()` 從 GitHub 下載 `smarties.png`。
**考試環境若沒有網路**，可改用下列任一種方式：

```python
# 方式一：本機已有檔案
image_bgr = cv2.imread("smarties.png")

# 方式二：用自己的圖片
image_bgr = cv2.imread(r"C:\Users\princ\Downloads\photo.jpg")

# 方式三：完全自己生成測試圖（不需任何外部檔案）
import numpy as np, cv2
image_bgr = np.zeros((400, 400, 3), dtype=np.uint8)
cv2.circle(image_bgr, (120, 150), 60, (0, 0, 255), -1)     # 紅球
cv2.circle(image_bgr, (280, 150), 60, (0, 255, 0), -1)     # 綠球
cv2.circle(image_bgr, (200, 300), 60, (255, 0, 0), -1)     # 藍球
```

> **注意**：`cv2.imshow()` 在無圖形介面的環境（如部分伺服器 / Colab）會失敗，請改用 `matplotlib.pyplot` 顯示。

### C.1 無網路環境的替代下載點

若考試機有網路但 GitHub 被封鎖，可用 OpenCV 官方 CDN 鏡像或本機圖片替代：

```python
# 檢查下載是否成功
import os
if not os.path.exists("smarties.png"):
    print("找不到 smarties.png，請改用本機圖片")
    image_bgr = cv2.imread("local_photo.jpg")
else:
    image_bgr = cv2.imread("smarties.png")
```

---

## 附錄 D：一頁精華（考前 10 分鐘）

```python
import cv2
import numpy as np
import matplotlib.pyplot as plt

# ========== 1. 讀取 ==========
img_bgr = cv2.imread("photo.jpg")                          # BGR
img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)         # 修顏色
gray    = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY)        # 灰階
hsv     = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2HSV)         # 顏色分割
lab     = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2LAB)         # 抗光照

# ========== 2. 前處理 ==========
small   = cv2.resize(gray, (320, 320))                     # dsize = (W, H)
blur    = cv2.GaussianBlur(small, (5, 5), 0)               # kernel 正奇數
_, bin_ = cv2.threshold(blur, 127, 255, cv2.THRESH_BINARY)
otsu_th, bin2 = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

# ========== 3. 矩陣運算 ==========
roi    = img_rgb[100:300, 150:350]                         # [Y, X] 先 Y 後 X
flip_h = cv2.flip(img_rgb, 1)                              # 1=水平
tint   = np.zeros_like(img_rgb); tint[:, :, 2] = 220       # RGB 的 index2 = Blue
blend  = cv2.addWeighted(img_rgb, 0.7, tint, 0.3, 0)       # 加權混合

# ========== 4. 繪圖 ==========
canvas = img_rgb.copy()
cv2.rectangle(canvas, (100, 80), (250, 280), (0, 0, 255), 2)      # 紅框
cv2.circle(canvas, (175, 180), 8, (0, 255, 0), -1)                # 綠點(填滿)
cv2.putText(canvas, "Target", (100, 70),
            cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 0), 2, cv2.LINE_AA)

# ========== 5. 變換 ==========
h, w = img_bgr.shape[:2]
M        = cv2.getRotationMatrix2D((w // 2, h // 2), 45, 1.0)     # 逆時針 45°
rotated  = cv2.warpAffine(img_rgb, M, (w, h))                     # 2x3, 3 點
# M_persp = cv2.getPerspectiveTransform(src4, dst4)               # 3x3, 4 點
# warped  = cv2.warpPerspective(img_rgb, M_persp, (300, 300))

# ========== 6. 濾波 / 形態學 ==========
med    = cv2.medianBlur(gray, 5)                           # 椒鹽雜訊
bilat  = cv2.bilateralFilter(img_rgb, 9, 75, 75)           # 保邊
kernel = np.ones((5, 5), np.uint8)
eroded = cv2.erode(bin_, kernel, iterations=1)             # 白色變小
dilat  = cv2.dilate(bin_, kernel, iterations=1)            # 白色變大
opened = cv2.morphologyEx(bin_, cv2.MORPH_OPEN, kernel)    # 去背景雜點

# ========== 7. 邊緣 / 輪廓 ==========
edges = cv2.Canny(blur, 100, 200)                          # 單通道輸入
contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL,
                               cv2.CHAIN_APPROX_SIMPLE)     # 4.x/5.x 回傳 2 個值
for c in contours:
    if cv2.contourArea(c) < 50:
        continue
    x, y, ww, hh = cv2.boundingRect(c)

# ========== 8. 特徵 / 匹配 ==========
orb = cv2.ORB_create(nfeatures=500)
kp1, des1 = orb.detectAndCompute(gray, None)               # des 形狀 (N, 32)
kp2, des2 = orb.detectAndCompute(cv2.flip(gray, 1), None)
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)      # ORB → Hamming
matches = sorted(bf.match(des1, des2), key=lambda m: m.distance)
out = cv2.drawMatches(img_rgb, kp1, cv2.flip(img_rgb, 1), kp2, matches[:30], None,
                      flags=cv2.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)
```

**口訣**

```
BGR 進、RGB 出（顯示用）
先 Y 後 X（切片）
(W, H) 是 resize、(H, W) 是 shape
kernel 要奇數、thickness -1 是填滿
加法用 cv2.add（會飽和）
ORB 配 Hamming、SIFT 配 L2
匹配後 RANSAC 剔 outlier
```

---

<a id="mc-exam"></a>

## 附錄 E：互動式線上測驗（60 題）

> **60 題單選、滿分 60 分、建議 75 分鐘。**
> 測驗以**互動網頁**形式提供（點選即時計分、進度自動儲存）；本筆記**不再收錄非互動的紙本題目**，避免與線上版重複。

### E.1 開始測驗

**👉 [開始 60 題線上測驗](mc-quiz.html)**

線上版功能：

- **點選答案**即自動計分，並即時顯示得分
- **作答進度自動存在你的瀏覽器**（localStorage）——關掉網頁、隔天再開都能繼續
- 可切換「只顯示未答」或「只顯示答錯」的題目，快速複習
- 按「顯示答案」才揭曉正解與解析，不會一開始就被暴雷
- 需要紙本時，直接在該頁按列印即可

### E.2 時間分配建議

| 階段 | 時間 | 做什麼 |
|---|---|---|
| 第一輪 | 0–40 分鐘 | 快速作答有把握的題目，不確定先標記跳過 |
| 第二輪 | 40–65 分鐘 | 回頭處理標記的難題 |
| 第三輪 | 65–75 分鐘 | 檢查有沒有漏答 |

### E.3 評分參考

| 分數 | 程度 | 建議 |
|---|---|---|
| 54–60 | 優異 | 直接看附錄 D 一頁精華即可上場 |
| 45–53 | 良好 | 複習錯題所屬章節 |
| 36–44 | 及格邊緣 | 重讀主要章節 + 附錄 A |
| 0–35 | 需加強 | 整份筆記重讀一遍，再重做本卷 |

> 答錯的題目請回到對應章節複習。

---

*本學習筆記涵蓋全部主題與程式範例，並補充 API 參數、常見錯誤與模擬試題。*
*模擬試題為附錄 E 的線上互動測驗（60 題）。*
*所有程式碼已於本機 OpenCV 5.0.0 / NumPy 2.4.6 / Matplotlib 3.11.2 環境實測通過。*

---

## 目錄

| # | 章節 |
|---|------|
| 1 | [What is OpenCV?](#1-what-is-opencv) |
| 2 | [OpenCV Applications](#2-opencv-applications) |
| 3 | [Color Spaces](#3-color-spaces) |
| 4 | [Color Space Conversion](#4-color-space-conversion) |
| 5 | [Image Pre-processing](#5-image-pre-processing) |
| 6 | [Matrix Operations](#6-matrix-operations) |
| 7 | [Drawing Functions](#7-drawing-functions) |
| 8 | [Transformations](#8-transformations) |
| 9 | [Filtering Techniques](#9-filtering-techniques) |
| 10 | [Edge Detection](#10-edge-detection) |
| 11 | [Feature Extraction](#11-feature-extraction) |
| 12 | [Feature Matching](#12-feature-matching) |
| 13 | [Real-World Projects](#13-real-world-projects) |
| 14 | [OpenCV Programming Examples（程式範例）](#14-opencv-programming-examples程式範例) |
| 15 | [Summary](#15-summary) |
| A | [附錄 A：API 速查表](#附錄-aapi-速查表) |
| B | [附錄 B：常見錯誤與陷阱](#附錄-b常見錯誤與陷阱) |
| C | [附錄 C：離線執行提示](#附錄-c離線執行提示) |
| D | [附錄 D：一頁精華（考前 10 分鐘）](#附錄-d一頁精華考前-10-分鐘) |
| E | [附錄 E：互動式線上測驗（60 題）](#附錄-e互動式線上測驗60-題) |
