Try   HackMD

CJSHS AI Course Week 2

Week 1 連結

https://hackmd.io/@Titi/ByNUY-x2kx

Week 2 課程

Face Recognition (人臉辨識)

開啟 Colab

Face Recognition (人臉辨識)

  • 安裝必要套件
!pip install -q insightface onnxruntime
  • 載入模組
import insightface import cv2 import numpy as np import os from google.colab import files from matplotlib import pyplot as plt
  • 載入 ArcFace 模型(包含偵測與特徵提取)
app = insightface.app.FaceAnalysis(name='buffalo_l') app.prepare(ctx_id=0)
  • 定義工具函式:Cosine 相似度 + 顯示圖片
def cosine_similarity(a, b): return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)) def show_img(img, title='Image'): img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) plt.imshow(img) plt.title(title) plt.axis("off") plt.show()
  • 上傳臉部資料庫圖片(檔名將作為人名,例如 alice.jpg)
print("上傳人臉資料庫圖片(1 人 1 張)") uploaded = files.upload() face_db = {} for filename in uploaded.keys(): name = os.path.splitext(filename)[0] img = cv2.imread(filename) faces = app.get(img) if faces: face_db[name] = faces[0].embedding print(f"✅ {name} 加入資料庫") else: print(f"⚠️ 無法辨識人臉:{filename}")
  • 上傳要辨識的新圖片
print("上傳要辨識的新圖片") uploaded_query = files.upload() query_img = None query_emb = None for filename in uploaded_query.keys(): query_img = cv2.imread(filename) faces = app.get(query_img) if not faces: print("❌ 沒有偵測到人臉") else: query_emb = faces[0].embedding show_img(query_img, title="Query Image")
  • 辨識結果
if query_emb is not None: best_match = None best_score = -1 for name, db_emb in face_db.items(): sim = cosine_similarity(query_emb, db_emb) print(f"{name} 相似度:{sim:.4f}") if sim > best_score: best_score = sim best_match = name if best_score > 0.6: print(f"✅ 辨識結果:{best_match}(相似度 {best_score:.4f})") else: print("⚠️ 查無此人")

作業

  1. 成功執行以上程式碼。
  2. 上傳3個人的照片,再額外輸入1張3人其中1人的照片和1張不是這3個人的照片。
  3. 建立長榮中學GPT資料庫