这段时间学习了一下opencv和pytorch,然后准备做一个小的项目练一下手。主要实现的功能是刷脸登录系统。
源代码在GITHUB上,链接 github源代码连接
前期准备
环境配置
如果想要运行这份代码,需要先下载以下包:
pytorch、opencv、numpy、torchvision
有关pytorch的下载,你可以参考我的这篇文章使用anaconda安装pytorch
硬件配置
只需要电脑有摄像头,然后电脑能跑深度学习的代码(我提供的模型里面只包含了我自己的数据集训练的参数,所以如果要能识别你自己,你需要跑一遍深度学习的代码)
代码部分
这次编写代码我采用的是模块化的方式,把很多函数、不同功能都分散开封装成包,然后需要导入。下面就按运行的顺序开始堆上代码。
代码结构如图:
识别部分
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#coder:UstarZzz
#date:2019/7/19
import cv2
from func import train_model
class Recognizer():
def __init__(self,cam_id,address):
self.id = cam_id
self.classfier = cv2.CascadeClassifier(address)
self.color = (0,255,0)
"""
to get capture object
:parameter:none
:return:cap
if you want to use camera to capture pictures,you just need to use
get_cap()
but if you want to capture pictures in your specific video files,you should use
get_cap(from_camera=False,path='your own path')
"""
def get_cap(self,from_camera=True,path='video.mp4'):
cv2.namedWindow('recognition area')
if(from_camera == True):
cap = cv2.VideoCapture(self.id)
if(from_camera == False):
cap = cv2.VideoCapture(path)
return cap
"""
to get state,frame
:parameter:cap
:returns:state,frame
"""
def get_video(self,cap):
state,frame = cap.read()
return state,frame
"""
to frame the portrait in the picture
:parameter:frame
:return:none
"""
def rect_face(self,frame,num,save=False,path='E:/code/control_system/pic/zyx_test'):
#change RGB to GREY
grey = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
facerects = self.classfier.detectMultiScale(grey,scaleFactor=1.2,minNeighbors=3,minSize=(32,32))
if len(facerects)>0:
for facerect in facerects:
x,y,w,h = facerect
if(save == True):
img_name = '%s/%d.jpg' % (path, num)
image = frame[y - 10: y + h + 10, x - 10: x + w + 10]
cv2.imwrite(img_name, image)
cv2.rectangle(frame, (x - 10, y - 10), (x + w + 10, y + h + 10), self.color, 2)
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(frame, 'num:%d' % (num), (x + 30, y + 30), font, 1, (255, 0, 255), 4)
if(save == False):
image = frame[y - 10: y + h + 10, x - 10: x + w + 10]
prediction,mark = train_model.test(all=False,from_camera=True,image=image)
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.rectangle(frame,(x-10,y-10),(x+w+10,y+h+10),self.color,2)
if(mark > 600):
if(prediction == 0):
cv2.putText(frame, 'LiuDehua', (x + 30, y + 30), font, 1, (255, 0, 255), 4)
if(prediction == 1):
cv2.putText(frame, 'ZhengYuxing', (x + 30, y + 30), font, 1, (255, 0, 255), 4)
else:
pass
"""
to show the picture
:parameter:frame
:return:keycode
""