https://hackmd.io/@Titi/ByNUY-x2kx
!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
app = insightface.app.FaceAnalysis(name='buffalo_l')
app.prepare(ctx_id=0)
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()
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("⚠️ 查無此人")