现在模型训练已经完成,只需要一个预测函数判断拍摄的照片是否是boss即可,在boss_train.py里的Model添加predeict实现函数。
def predict(self, image):
# 依然是根据后端系统确定维度顺序
if K.image_dim_ordering() == 'th' and image.shape != (1, 3, IMAGE_SIZE, IMAGE_SIZE):
image = resize_with_pad(image) #尺寸必须与训练集一致都应该是IMAGE_SIZE x IMAGE_SIZE
image = image.reshape((1, 3, IMAGE_SIZE, IMAGE_SIZE)) #与模型训练不同,这次只是针对1张图片进行预测
elif K.image_dim_ordering() == 'tf' and image.shape != (1, IMAGE_SIZE, IMAGE_SIZE, 3):
image = resize_with_pad(image)
image = image.reshape((1, IMAGE_SIZE, IMAGE_SIZE, 3))
# 浮点并归一化
image = image.astype('float32')
image /= 255
# 给出输入属于各个类别的概率,我们是二值类别,则该函数会给出输入图像属于0和1的概率各为多少
result = self.model.predict_proba(image)
print(result)
# 给出类别预测:0或者1
result = self.model.predict_classes(image)
# 返回类别预测结果
return result[0]
以下是最终的实现代码:
# -*- coding:utf-8 -*-
import cv2
from boss_train import Model
from image_show import show_image
if __name__ == '__main__':
cap = cv2.VideoCapture(0)
# 人脸识别分类器本地存储路径
cascade_path = "haarcascade_frontalface_default.xml"
#加载模型
model = Model()
model.load()
while True:
_, frame = cap.read()
cv2.imshow("识别朕", frame)
##图像灰化,降低计算复杂度
frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 使用人脸识别分类器,读入分类器
cascade = cv2.CascadeClassifier(cascade_path)
# 利用分类器识别出哪个区域为人脸
facerect = cascade.detectMultiScale(frame_gray, scaleFactor=1.2, minNeighbors=3, minSize=(8, 8))
if len(facerect) > 0:
print('face detected')
color = (255, 255, 255) # 白
for rect in facerect:
# 截取脸部图像提交给模型识别这是谁
cv2.rectangle(frame, tuple(rect[0:2]), tuple(rect[0:2] + rect[2:4]), color, thickness=2)
x, y = rect[0:2]
width, height = rect[2:4]
image = frame[y - 10: y + height, x: x + width]
result = model.predict(image)
if result == 0: # boss
print('Boss is approaching')
#cv2.imshow("识别朕", frame)
show_image()
else:
print('Not boss')
#10msec的带灯时间
k = cv2.waitKey(10)
#Esc退出
if k == 27:
break
# 释放摄像头并销毁所有窗口
cap.release()
cv2.destroyAllWindows()
当我走进摄像头的视野,电脑桌面跳出预备的照片,测试显示结果不错。
注意:增加自身训练数据集可提高对boss识别精度,增加其他人的训练数据量,可减少误判。