Keras之CNN:基于Keras利用cv2建立训练存储卷积神经网络模型(2+1)并调用摄像头进行实时人脸识别
Keras之CNN:基于Keras利用cv2建立训练存储卷积神经网络模型(2+1)并调用摄像头进行实时人脸识别
输出结果
设计思路
核心代码
# -*- coding:utf-8 -*-
import cv2
from train_model import Model
from read_data import read_name_list
from timeit import default_timer as timer ### to calculate FPS
class Camera_reader(object):
def __init__(self):
self.model = Model()
self.model.load()
self.img_size = 128
def build_camera(self):
face_cascade = cv2.CascadeClassifier('F:\\Program Files\\Python\\Python36\\Lib\\site-packages\\cv2\\data\\haarcascade_frontalface_alt.xml')
# print(face_cascade) #输出<CascadeClassifier 000002240244CC70>
name_list = read_name_list('F:\\File_Python\\Python_example\\face_recognition_name\\After_cut_picture')
# print(name_list)
cameraCapture = cv2.VideoCapture(0)
success, frame = cameraCapture.read()
while success and cv2.waitKey(1) == -1:
success, frame = cameraCapture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
ROI = gray[x:x + w, y:y + h]
ROI = cv2.resize(ROI, (self.img_size, self.img_size), interpolation=cv2.INTER_LINEAR)
label,prob = self.model.predict(ROI)
if prob >0.7:
show_name = name_list[label]
else:
show_name = 'Stranger'
cv2.putText(frame, show_name, (x, y - 20), cv2.FONT_HERSHEY_SIMPLEX, 1, 255, 2)
frame = cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)
cv2.imshow("Camera", frame)
cameraCapture.release()
cv2.destroyAllWindows()
def detect_video(self):
face_cascade = cv2.CascadeClassifier('F:\\Program Files\\Python\\Python36\\Lib\\site-packages\\cv2\\data\\haarcascade_frontalface_alt.xml')
name_list = read_name_list('F:\\File_Python\\Python_example\\face_recognition_name\\After_cut_picture')
video = cv2.VideoCapture(video_path) ### TODO: will video path other than 0 be used?
success, frame = video.read()
accum_time = 0
curr_fps = 0
fps = "FPS: ??" #fps = "FPS: ??"
prev_time = timer()
while success and cv2.waitKey(1) == -1:
success, frame = video.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
curr_time = timer()
exec_time = curr_time - prev_time
prev_time = curr_time
accum_time = accum_time + exec_time
curr_fps = curr_fps + 1 #1
if accum_time > 1:
accum_time = accum_time - 1 #1
fps = "FPS: " + str(curr_fps)
curr_fps = 0 #0
for (x, y, w, h) in faces:
ROI = gray[x:x + w, y:y + h]
ROI = cv2.resize(ROI, (self.img_size, self.img_size), interpolation=cv2.INTER_LINEAR) #cv2.INTER_LINEAR图像尺寸变换的方法,默认的双线性插值
label,prob = self.model.predict(ROI)
if prob >0.7:
show_name = name_list[label]
else:
show_name = 'Stranger'
cv2.putText(frame, show_name, (x, y - 20), cv2.FONT_HERSHEY_SIMPLEX, 1, 255, 2)
frame = cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)
cv2.namedWindow("result", cv2.WINDOW_NORMAL)
cv2.imshow("result",frame)
if __name__ == '__main__':
camera = Camera_reader()
camera.build_camera()
# video_path='F:/File_Python/Python_example/YOLOv3_use_TF/RunMan1.mp4'
# camera.detect_video()
赞 (0)