為了讓大家能直觀看到「圖像轉換過程」與「多模態資料特徵拼接(Horizontal Concatenation)」的效果,我們用 「學生幾何頭像與期中考成績多模態整合」 的實作範例。
這個範例會在執行後,直接畫出一張 4 步驟轉換對照圖(如視覺化預覽圖所示),讓我們一眼看懂:
原始圖像 (Raw Image 64x64x3) $\rightarrow$ 2. 壓縮尺寸 (Resized 16x16x3) $\rightarrow$ 3. 像素歸一化 (Normalized Heatmap 0.0~1.0) $\rightarrow$ 4. 特徵拼接 (Multimodal Feature Vector)
# Weeek10_CV.py
import cv2
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
# =========================================================
# 步驟 1:建立示範圖像 (模擬 3 位學生的不同圖案大頭貼)
# =========================================================
def create_avatar(pattern_type):
img = np.zeros((64, 64, 3), dtype=np.uint8)
if pattern_type == 'circle':
cv2.circle(img, (32, 32), 20, (255, 100, 50), -1) # 藍橘幾何圖
cv2.rectangle(img, (10, 10), (25, 25), (50, 200, 255), -1)
elif pattern_type == 'square':
cv2.rectangle(img, (15, 15), (50, 50), (50, 255, 100), -1) # 綠粉幾何圖
cv2.circle(img, (50, 50), 10, (200, 50, 255), -1)
elif pattern_type == 'triangle':
pts = np.array([[32, 10], [10, 54], [54, 54]], np.int32)
cv2.fillPoly(img, [pts], (255, 255, 50)) # 青藍三角形
cv2.circle(img, (32, 32), 8, (255, 50, 50), -1)
return img
raw_images = [
create_avatar('circle'),
create_avatar('square'),
create_avatar('triangle'),
]
# =========================================================
# 步驟 2:影像前處理管線 (Resize -> Normalization -> Flatten)
# =========================================================
def preprocess_avatar(img, target_size=(16, 16)):
# 1. 調整尺寸 (Resize 64x64 -> 16x16)
img_resized = cv2.resize(img, target_size, interpolation=cv2.INTER_AREA)
# 2. 像素歸一化 (0~255 -> 0.0~1.0)
img_norm = img_resized / 255.0
# 3. 展平 (Flatten 16x16x3 -> 768 維一維向量)
img_flat = img_norm.flatten()
return img_resized, img_norm, img_flat
processed_data = [preprocess_avatar(img) for img in raw_images]
resized_imgs = [p[0] for p in processed_data]
norm_imgs = [p[1] for p in processed_data]
flat_vectors = np.array([p[2] for p in processed_data])
# =========================================================
# 步驟 3:結構化表格數據前處理 (學生年齡與成績)
# =========================================================
df_students = pd.DataFrame(
{'Age': [20, 22, 21], 'Midterm_Score': [85, 92, 78]}
)
# 使用 StandardScaler 縮放表格資料
scaler = StandardScaler()
X_tabular = scaler.fit_transform(df_students)
# =========================================================
# 步驟 4:多模態特徵水平拼接 (Multimodal Feature Fusion)
# =========================================================
# 將表格特徵 (3 筆 x 2 欄) 與 展平影像特徵 (3 筆 x 768 欄) 水平縫合
X_multimodal = np.hstack([X_tabular, flat_vectors])
print(f'表格特徵維度: {X_tabular.shape}')
print(f'影像特徵維度: {flat_vectors.shape}')
print(f'最終多模態特徵矩陣 (X_multimodal) 維度: {X_multimodal.shape}') # (3, 770)
# =========================================================
# 步驟 5:前處理轉換效果視覺化 (畫圖呈現給學生看)
# =========================================================
fig, axes = plt.subplots(3, 4, figsize=(13, 8))
fig.suptitle(
'Multimodal Preprocessing Pipeline: Image to Feature Vector',
fontsize=14,
fontweight='bold',
)
titles = [
'1. Raw (64x64x3)',
'2. Resized (16x16x3)',
'3. Pixel Norm [0, 1]',
'4. Multimodal Vector (Stitched)',
]
for i in range(3):
# 1. 原始圖片 (需做 BGR -> RGB 轉換)
axes[i, 0].imshow(cv2.cvtColor(raw_images[i], cv2.COLOR_BGR2RGB))
axes[i, 0].set_ylabel(f'Student {i+1}', fontsize=12, fontweight='bold')
# 2. Resized 圖片
axes[i, 1].imshow(cv2.cvtColor(resized_imgs[i], cv2.COLOR_BGR2RGB))
# 3. 歸一化熱圖
axes[i, 2].imshow(norm_imgs[i][:, :, 0], cmap='viridis', vmin=0, vmax=1)
# 4. 多模態向量前 15 欄位展示 (前 2 欄為 Age/Score,後續為 P0, P1...)
axes[i, 3].imshow(
X_multimodal[i, :15].reshape(1, 15), cmap='Blues', aspect='auto'
)
axes[i, 3].set_xticks(range(15))
axes[i, 3].set_xticklabels(
['Age', 'Score'] + [f'P{j}' for j in range(13)], rotation=45, fontsize=8
)
axes[i, 3].set_yticks([])
for col_idx, title in enumerate(titles):
axes[0, col_idx].set_title(title, fontsize=11, fontweight='bold')
plt.tight_layout()
plt.show()
- 輸出的圖像: 第 1 欄至第 3 欄清楚展現了「圖片如何在保持特徵的前提下被縮小、像素如何被歸一化成 0.0 ~ 1.0 的數字」
- 多模態縫合過程(第 4 欄):
游標指著第 4 欄的最左邊:「這兩格是 Z-Score 標準化後的 Age 與 Score」。
游標指著第 4 欄右邊一長串:「後面的 P0 到 P767 就是剛剛展平的影像像素數字」。
結論:這樣電腦就可以用同一筆資料(一列列 Row),同時學習到學生的成績背景與大頭貼外貌特徵!