一個人臉識別的例子
程序中用到了公共數據集, 歡迎去我的git上下載源碼,源碼里帶有數據集
git:https://github.com/linyi0604/Computer-Vision
腳本中一個三個函數
第一個: 調用本機攝像頭采集一些自己的照片 作為數據集的一部分
第二個:把自己的照片 和公共數據集照片一並讀取 作為輸入數據
第三個: 預測函數 調用第二個函數拿到x 和y 進行訓練后 開啟攝像頭 進行預測
1 # coding:utf-8
2
3 import cv2 4 import os 5 import numpy as np 6
7
8 # 1 生成人臉識別數據
9 # 圖像是灰度格式,后綴名.pgm
10 # 圖像是正方形 圖像大小要一樣 在這里使用200*200
11 def generate(): 12 # 加載檢測圖像中人臉位置的對象, xml文件需要去opencv文件夾里面找, 放到項目里面來引入
13 face_cascade = cv2.CascadeClassifier("../data/haarcascade_frontalface_default.xml") 14 # 調用本機攝像頭
15 camera = cv2.VideoCapture(0) 16 count = 0 17 # 讀取攝像頭
18 while True: 19 # 讀入 幀
20 ret, frame = camera.read() 21 # 變為灰度圖像
22 gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) 23 # 檢測人臉位置
24 faces = face_cascade.detectMultiScale(gray, 1.3, 5) 25 # 將圖片中人臉位置單獨拿出來改變成200*200大小的圖片 存入本地 作為數據集
26 for (x, y, w, h) in faces: 27 img = cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2) 28 f = cv2.resize(gray[y:y+h, x:x+w], (200, 200)) 29 cv2.imwrite("./data/%s.pgm" % str(count), f) 30 count += 1
31
32 cv2.imshow("camera", frame) 33 # 如果按鍵q就退出 否則等50毫秒
34 if cv2.waitKey(50) & 0xff == ord("q"): 35 break
36
37 camera.release() 38 cv2.destroyAllWindows() 39
40
41 # 讀取生成好的數據 在我項目目錄下整理好的
42 def readImages(): 43 x, y = [], [] 44 path = "./data/faces/"
45 image_file = os.listdir(path) 46 image_files = [path + i for i in image_file] 47 for file in image_files: 48 images = os.listdir(file) 49 label = file.split("/")[-1][1:] 50 for i in images: 51 img = cv2.imread(file + "/" + i, cv2.IMREAD_GRAYSCALE) 52 img = cv2.resize(img, (200, 200)) 53 x.append(np.asarray(img, dtype=np.uint8)) 54 y.append(int(label)) 55
56 y = np.asarray(y, dtype=np.int32) 57 return x, y 58
59
60 # 檢測人臉
61 def face_rec(): 62 # 獲取數據
63 x, y = readImages() 64
65 # 人臉識別的模型
66 model = cv2.face.EigenFaceRecognizer_create() 67 # fisherfaces算法的模型
68 # model = cv2.face.FisherFaceRecognizer_create()
69 # LBPH算法的模型
70 # model = cv2.face.LBPHFaceRecognizer_create()
71 """
72 Eigenfaces和Fisherfaces 預測時候產生0到20000的評分 73 低於4000 5000 的評分都是相當可靠的 74 LBPH 產生評分不同,低於50是可靠的 高於80是不可靠的 75 """
76
77 # 訓練模型
78 model.train(np.asarray(x), np.asarray(y)) 79
80 # 開攝像頭
81 camera = cv2.VideoCapture(0) 82 # 加載檢測人臉對象
83 face_cascade = cv2.CascadeClassifier("../data/haarcascade_frontalface_default.xml") 84 while True: 85 # 讀取當前幀
86 read, img = camera.read() 87 # 當前幀下檢測人臉
88 faces = face_cascade.detectMultiScale(img, 1.3, 5) 89 for (x, y, w, h) in faces: 90 # 畫出人臉
91 img = cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2) 92 # 轉成灰度圖
93 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 94 # 拿出人臉部分
95 roi = gray[x: x+w, y: y+h] 96 try: 97 # 更改大小
98 roi = cv2.resize(roi, (200, 200), interpolation=cv2.INTER_LINEAR) 99 # 進行預測
100 params = model.predict(roi) 101 # 在圖像上寫預測結果
102 # 1.2是字體大小 2是粗細
103 img = cv2.putText(img, str(params[0]), (x, y), cv2.FONT_HERSHEY_SIMPLEX, 1.2, (0, 255, 0), 2) 104 # prams是一個二元素列表, 第一個元素是預測結果,第二個元素是得分情況
105 print(params) 106
107 except Exception as e: 108 print(e) 109 cv2.imshow("detect face", img) 110 if cv2.waitKey(5) & 0xff == ord("q"): 111 break
112
113 cv2.destroyAllWindows() 114
115
116 if __name__ == '__main__': 117 # 調用攝像頭 采集人臉照片數據
118 # generate()
119
120 # 檢測人臉
121 face_rec()