資料搜集:輸入影片産生人臉偵測照片序列檔案,存放在兩個目錄,一個為辨識目標,一個為驗證資料。
建立模型:利用類神經網路訓練程式,訓練人臉辨識模型,産生訓練結果模型檔。
成果應用:執行臉部辨識程式,標示影像中的人臉。
附上訓練過程及辨識結果圖片,報告內容有三點:工作流程,結果說明,心得。
python3相關套件:
pip3 install opencv-python
pip3 install scikit-learn
6. 參考資料:類神經網路
其他偵測模型:haarcascades
# Import the necessary modules and libraries
import cv2
import os
import shutil
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades +'haarcascade_frontalface_default.xml')
#讀取辨識用影片檔
cap = cv2.VideoCapture("twofaces.mp4")
if os.path.isdir("data"):
shutil.rmtree("data")
os.mkdir("data")
else: os.mkdir("data")
#設定照片處理大小
IMAGE_SIZE = 64
num = 0
while True:
ret, img = cap.read()
if ret == False: break;
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.1, 5, 4 )
for (x, y, w, h) in faces:
image = img[y: y+h, x: x+w]
#調整圖片大小到設定值,儲存成檔案
image = cv2.resize(image, (IMAGE_SIZE, IMAGE_SIZE))
cv2.imwrite('data/%d.png'%num, image)
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 1)
num += 1
cv2.imshow('img', img)
k = cv2.waitKey(1)
if k == 27: break
cap.release()
cv2.destroyAllWindows()
# Import the necessary modules and libraries
import random
import os
import sys
import numpy as np
import cv2
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
import pickle
#設定照片處理大小
IMAGE_SIZE = 64
#設定辨識目標存放目錄名稱
TARGET_NAME = 'Wang'
images = []
labels = []
def read_path(path_name):
for dir_item in os.listdir(path_name):
full_path = os.path.join(path_name, dir_item)
if os.path.isdir(full_path):
read_path(full_path)
else:
#設定處理圖檔格式
if dir_item.endswith('.png'):
image = cv2.imread(full_path)
image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
image = np.reshape(image, (-1))
images.append(image)
if path_name.endswith('/'+TARGET_NAME): labels.append(1)
else: labels.append(0)
return images,labels
def load_dataset(path_name):
images,labels = read_path(path_name)
return images, labels
load_dataset("./data/")
X_train, X_test, y_train, y_test = train_test_split(images, labels, test_size=.3)
#建立類神經模型
clf = MLPClassifier(solver='adam', max_iter=2000,
verbose=True, hidden_layer_sizes=[100, 100])
clf.fit(X_train, y_train)
score = clf.score(X_test, y_test)
print("Final score: ", score)
pickle.dump(clf, open(TARGET_NAME+"_model.sav", 'wb'))
import cv2
import numpy as np
import pickle
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades +'haarcascade_frontalface_default.xml')
#讀取辨識用影片檔
cap = cv2.VideoCapture("twofaces.mp4")
#設定照片處理大小
IMAGE_SIZE = 64
#讀取辨識用模型檔
clf = pickle.load(open("Wang_model.sav", 'rb'))
TARGET_NAME = "Wang"
while True:
ret, img = cap.read()
if ret == False: break;
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.1, 5, 4 )
for (x, y, w, h) in faces:
image = gray[y: y+h, x: x+w]
image = cv2.resize(image, (IMAGE_SIZE, IMAGE_SIZE))
image = np.reshape(image, (1, -1))
faceID = clf.predict(image)[0]
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 1)
if faceID == 1:
#文字顯示辨識結果
cv2.putText(img, TARGET_NAME, (x + 30, y + 30),
cv2.FONT_HERSHEY_SIMPLEX, 1, (255,0,255), 2)
cv2.imshow('img', img)
k = cv2.waitKey(10)
if k == 27: break
cap.release()
cv2.destroyAllWindows()
工作流程:你有道靈光從天靈蓋噴出來,你知道嗎?年紀輕輕,就有一身橫練的筋骨,簡直是百年一見的練武奇材,如果有一天,讓你打通任督二脈,那還不飛天啦!《功夫》
結果說明:正所謂!我不入地獄,誰入地獄。警惡懲奸,維護世界和平這任務,就交給你了,好不好?這本“如來神掌秘笈”是無價之寶,你我有緣,就收你十塊傳授給你吧!《功夫》
心得:我們雖然窮,但不亂說髒話,我們不去偷,我們不去搶;不屬於自己的東西我們不會拿。你要努力讀書,將來做一個有用的人。我呀,就是小時候沒有書念,所以現在跟不上時代...《長江七號》
延伸應用一:應用在兩個不同人
clf1 = pickle.load(open("Wang_model.sav", 'rb'))
clf2 = pickle.load(open("Lin_model.sav", 'rb'))
......
faceID = clf1.predict(image)[0]
if faceID == 1:......
faceID = clf2.predict(image)[0]
if faceID == 1:......
延伸應用二:在同一個模型訓練兩個不同人
if path_name.endswith('/'+TARGET_NAME1): labels.append(1)
elif path_name.endswith('/'+TARGET_NAME2): labels.append(2)
else: labels.append(0)