├── README.md ├── face.py ├── faceDetection.py ├── mysql_test.py ├── opencv人脸识别测试教程.docx ├── testopencv_camera.py └── uploadDetection.py /README.md: -------------------------------------------------------------------------------- 1 | # raspberry_pi 2 | 大四毕业设计做的基于树莓派的人脸识别系统(调用百度云api) 3 | 4 | 1.face.py可以单独运行 5 | 6 | 2.mysql_test.py是测试树莓派数据库连接 7 | 8 | 3.testopencv_camera.py是测试树莓派安装opencv是否安装成功, 并测试摄像头 9 | 10 | 4.那个word教程随便看看就可以 11 | 5. faceDetection.py和uploadDetection.py同时运行. faceDetection.py调用摄像头锁定人脸拍照, 将照片保存到本地; uploadDetection.py将本地照片上传到百度云, 处理返回结果 12 | -------------------------------------------------------------------------------- /face.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | 3 | from picamera import PiCamera 4 | from aip import AipFace 5 | import urllib.request 6 | import RPi.GPIO as GPIO 7 | import base64 8 | import time 9 | import cv2 10 | import pymysql.cursors 11 | import sys 12 | import datetime 13 | 14 | #打开数据库连接 15 | conn=pymysql.connect(host='localhost',user='root',passwd='123456',db='rapberry',port=3306) 16 | 17 | #使用cursor()方法获取操作游标 18 | cur=conn.cursor() 19 | 20 | #获取当前时间 21 | dt=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") 22 | 23 | #百度人脸识别API账号信息 24 | APP_ID = '15777534' 25 | API_KEY = 'iRCGkO9cV0iZOC4tNM4pjsIR' 26 | SECRET_KEY ='WAaSwk2alCMc5fqefijAGOS9YEHLL4ga' 27 | 28 | client = AipFace(APP_ID, API_KEY, SECRET_KEY)#创建一个客户端用以访问百度云 29 | 30 | #图像编码方式 31 | IMAGE_TYPE='BASE64' 32 | camera = PiCamera()#定义一个摄像头对象,首先使用picamera模块当中的PiCamera方法创建返回一个camera的对象 33 | #用户组 34 | GROUP = 'raspberry_pi' 35 | 36 | #初始化相机并获取对原始相机捕获的引用 37 | #照相函数 38 | def getimage(): 39 | #摄像界面为1024*768 40 | camera.resolution = (1024, 768) #设置图像的width和height 41 | camera.saturation = 80 # 设置图像视频的饱和度 42 | camera.framerate = 32 #这里可能用的Fraction是一个分数模块来存储分数1/6,保证分数运算的精度,记得调用模块 43 | 44 | time.sleep(0.1)#让相机预热 45 | camera.start_preview()#开始摄像 46 | time.sleep(2) 47 | camera.capture('faceimage.jpg')#拍照并保存 48 | time.sleep(2) 49 | 50 | #对图片的格式进行转换 51 | def transimage(): 52 | f = open('faceimage.jpg','rb') 53 | img = base64.b64encode(f.read()) 54 | return img 55 | 56 | #上传到百度api进行人脸检测 57 | def go_api(image): 58 | result = client.search(str(image, 'utf-8'), IMAGE_TYPE, GROUP);#在百度云人脸库中寻找有没有匹配的人脸 59 | if result['error_msg'] == 'SUCCESS':#如果成功了 60 | name = result['result']['user_list'][0]['user_id']#获取名字 61 | score = result['result']['user_list'][0]['score']#获取相似度 62 | print("相似度%d!" %score) 63 | if score > 80:#如果相似度大于80 64 | if name == 'linhaitao': 65 | #print("欢迎%s !" % name) 66 | print("欢迎林海涛") 67 | time.sleep(3) 68 | if name == 'mayun': 69 | #print("欢迎%s !" % name) 70 | print("欢迎马云") 71 | time.sleep(3) 72 | if name == "liyanhong": 73 | #print("欢迎%s !" % name) 74 | print("欢迎李彦宏") 75 | if name == "zhaoliying": 76 | #print("欢迎%s !" % name) 77 | print("欢迎赵丽颖") 78 | else: 79 | print("对不起,我不认识你!我不能给你开门!!!") 80 | name = 'Unknow' 81 | return 0 82 | current_time = time.asctime(time.localtime(time.time()))#获取当前时间 83 | 84 | #写入mysql 85 | try: 86 | #执行sql语句 87 | cur.execute("insert into person values('%s','%s')"%(name, dt)) 88 | cur.close() 89 | #提交到数据库执行 90 | conn.commit() 91 | print("插入成功") 92 | except: 93 | #发生错误时回滚 94 | conn.rollback() 95 | print("插入失败") 96 | finally: 97 | #关闭数据库链接 98 | conn.close() 99 | return 1 100 | if result['error_msg'] == 'pic not has face': 101 | print('检测不到人脸,请把人脸对准摄像头重试,谢谢!') 102 | time.sleep(2) 103 | return 0 104 | 105 | #主函数 106 | if __name__ == '__main__': 107 | while True: 108 | print('准备开始人脸识别') 109 | if True: 110 | getimage()#拍照 111 | img = transimage()#转换照片格式 112 | res = go_api(img)#将转换了格式的图片上传到百度云 113 | if(res == 1):#是人脸库中的人 114 | print("开门") 115 | else: 116 | print("关门") 117 | print('稍等三秒进入下一个') 118 | time.sleep(3) 119 | 120 | -------------------------------------------------------------------------------- /faceDetection.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | ''' 3 | Haar Cascade Face detection with OpenCV 4 | ''' 5 | 6 | from picamera import PiCamera 7 | from aip import AipFace 8 | import urllib.request 9 | import RPi.GPIO as GPIO 10 | import base64 11 | import time 12 | import cv2 13 | import pymysql.cursors 14 | import pymysql 15 | import sys 16 | import datetime 17 | import urllib3 18 | 19 | import numpy as np 20 | import cv2 21 | 22 | # OpenCV 包含很多预训练分类器 23 | #加载分类器 24 | faceCascade = cv2.CascadeClassifier('Cascades/haarcascade_frontalface_default.xml') 25 | 26 | cap = cv2.VideoCapture(0) 27 | cap.set(3,640) # set Width 28 | cap.set(4,480) # set Height 29 | 30 | # For each person, enter one numeric face id 31 | face_id = input('\n enter user id end press ==> ') 32 | 33 | count = 0#测试用 34 | 35 | #在循环内部调用摄像头,并以grayscale模式加载我们的输入视频 36 | while True: 37 | ret, img = cap.read() 38 | #img = cv2.flip(img, -1)#旋转图像 39 | gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 40 | #gray= cv2.cvtColor(img,cv2.COLOR_GRAY2RGB)#灰度图像转为彩色图像 41 | 42 | #调用分类器函数(比例因子、邻近数、人脸检测的最小尺寸) 43 | ''' 44 | gray 表示输入 grayscale 图像 45 | scaleFactor 表示每个图像缩减的比例大小 46 | minNeighbors 表示每个备选矩形框具备的邻近数量。数字越大,假正类越少 47 | minSize 表示人脸识别的最小矩形大小 48 | ''' 49 | faces = faceCascade.detectMultiScale( 50 | gray, 51 | scaleFactor=1.2, 52 | minNeighbors=5, 53 | minSize=(30, 30) 54 | ) 55 | 56 | #函数将检测到的人脸的位置返回为一个矩形,左上角 (x,y),w 表示宽度,h 表示高度 ==> (x,y,w,h) 57 | for (x,y,w,h) in faces: 58 | cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 59 | roi_gray = gray[y:y+h, x:x+w] 60 | roi_color = img[y:y+h, x:x+w] 61 | 62 | count += 1 63 | print("这是一条测试数据"+str(count)) 64 | #cv2.imwrite("./dataset/faceimage.jpg", gray[y:y+h,x:x+w])#写入黑白 65 | cv2.imwrite("./dataset/faceimage.jpg", img[y:y+h,x:x+w])#写入彩色 66 | 67 | cv2.imshow('video',img) 68 | 69 | k = cv2.waitKey(30) & 0xff 70 | if k == 27: # press 'ESC' to quit 71 | break 72 | 73 | cap.release() 74 | cv2.destroyAllWindows() 75 | -------------------------------------------------------------------------------- /mysql_test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | 3 | #import MySQLdb 4 | import pymysql.cursors 5 | import time 6 | import sys 7 | import datetime 8 | 9 | #打开数据库连接 10 | #conn=MySQLdb.connect(host='localhost',user='root',passwd='123456',db='rapberry',port=3306) 11 | conn=pymysql.connect(host='localhost',user='root',passwd='123456',db='rapberry',port=3306) 12 | 13 | #使用cursor()方法获取操作游标 14 | cur=conn.cursor() 15 | 16 | #SQL插入语句 17 | #sql = "insert into person values(%s, %s) " % (name, current_time) 18 | #sql = "select * from person" 19 | 20 | ''' 21 | #使用字典传递 22 | sql = "INSERT INTO person(name, time) VALUES (%(n)s, %(t)s)" 23 | value = {"n":name,"t":curren_time} 24 | ''' 25 | 26 | ''' 27 | user_id = "test123" 28 | password = "password" 29 | 30 | con.execute('insert into Login values("%s", "%s")' % \ 31 | (user_id, password)) 32 | ''' 33 | 34 | #获取当前时间 35 | username = "test111" 36 | #current_time= time.asctime(time.localtime(time.time())) 37 | dt=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") 38 | #sql_insert="insert into person(name,time) values(%s,str_to_date(\'%s\','%%Y-%%m-%%d %%H:%%i:%%s'))" %(name,time.strftime("%Y-%m-%d %H:%M:%S")) 39 | 40 | #str_to_date(\'%s\','%%Y-%%m-%%d %%H:%%i:%%s') 41 | try: 42 | #执行sql语句 43 | #cur.execute("insert into person(name,time) values(%s,%s)" %(name,time.strftime("%Y-%m-%d %H:%M:%S"))) 44 | #cur.execute('insert into person(name,time) values(%s, %s)' %(name,str_to_date(current_time))) 45 | #cur.execute('insert into test1(name) values(%s)'%name) 46 | cur.execute("insert into person values('%s','%s')"%(username, dt)) 47 | #cur.execute(sql, value) 48 | ''' 49 | # 获取所有记录列表 50 | results = cur.fetchall() 51 | for row in results: 52 | name = row[0] 53 | time = row[1] 54 | # 打印结果 55 | print "name=%s,time=%s" % (name, time) 56 | ''' 57 | cur.close() 58 | #提交到数据库执行 59 | conn.commit() 60 | print("插入成功") 61 | print(time.strftime('%Y-%m-%d %H:%M:%S')) 62 | except: 63 | #发生错误时回滚 64 | conn.rollback() 65 | print("插入失败") 66 | finally: 67 | #关闭数据库链接 68 | conn.close() 69 | 70 | 71 | 72 | 73 | -------------------------------------------------------------------------------- /opencv人脸识别测试教程.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AidenLin/raspberry_pi/068d691f7d0dca11fbc7a737dd660c21543b69df/opencv人脸识别测试教程.docx -------------------------------------------------------------------------------- /testopencv_camera.py: -------------------------------------------------------------------------------- 1 | from picamera.array import PiRGBArray 2 | from picamera import PiCamera 3 | import time 4 | import cv2 5 | 6 | camera = PiCamera() 7 | camera.resolution = (640, 480) 8 | camera.framerate = 32 9 | rawCapture = PiRGBArray(camera, size=(640, 480)) 10 | 11 | time.sleep(0.1) 12 | 13 | for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True): 14 | image = frame.array 15 | 16 | cv2.imshow("Frame", image) 17 | key = cv2.waitKey(1) & 0xFF 18 | 19 | rawCapture.truncate(0) 20 | 21 | if key == ord("q"): 22 | break 23 | -------------------------------------------------------------------------------- /uploadDetection.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | 3 | from picamera import PiCamera 4 | from aip import AipFace 5 | import urllib.request 6 | import RPi.GPIO as GPIO 7 | import base64 8 | import time 9 | import cv2 10 | import pymysql.cursors 11 | import pymysql 12 | import sys 13 | import datetime 14 | import urllib3 15 | 16 | #requests设置移除SSL认证 17 | urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) 18 | 19 | #打开数据库连接 20 | #conn=MySQLdb.connect(host='localhost',user='root',passwd='123456',db='rapberry',port=3306) 21 | conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='123456', db='rapberry') 22 | 23 | #使用cursor()方法获取操作游标 24 | cur=conn.cursor() 25 | 26 | #获取当前时间 27 | dt=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") 28 | 29 | #百度人脸识别API账号信息 30 | APP_ID = '15777534' 31 | API_KEY = 'iRCGkO9cV0iZOC4tNM4pjsIR' 32 | SECRET_KEY ='WAaSwk2alCMc5fqefijAGOS9YEHLL4ga' 33 | 34 | client = AipFace(APP_ID, API_KEY, SECRET_KEY)#创建一个客户端用以访问百度云 35 | 36 | #图像编码方式 37 | IMAGE_TYPE='BASE64' 38 | #用户组 39 | GROUP = 'raspberry_pi' 40 | 41 | #对图片的格式进行转换 42 | def transimage(): 43 | print("---请将人脸对准摄像头---") 44 | time.sleep(3)#缓解相机的卡顿 45 | f = open('./dataset/faceimage.jpg','rb') 46 | img = base64.b64encode(f.read()) 47 | return img 48 | 49 | #上传到百度api进行人脸检测 50 | def go_api(image): 51 | result = client.search(str(image, 'utf-8'), IMAGE_TYPE, GROUP);#在百度云人脸库中寻找有没有匹配的人脸 52 | if result['error_msg'] == 'SUCCESS':#如果成功了 53 | name = result['result']['user_list'][0]['user_id']#获取名字 54 | score = result['result']['user_list'][0]['score']#获取相似度 55 | print("相似度%d!" %score) 56 | if score > 80:#如果相似度大于80 57 | print("欢迎%s !" % name) 58 | if name == 'linhaitao': 59 | print("欢迎林海涛") 60 | time.sleep(3) 61 | if name == 'mayun': 62 | print("欢迎马云") 63 | time.sleep(3) 64 | if name == "liyanhong": 65 | print("欢迎李彦宏") 66 | if name == "zhaoliying": 67 | print("欢迎赵丽颖") 68 | if name == "mahuateng": 69 | print("欢迎马化腾") 70 | if name == "huge": 71 | print("欢迎胡歌") 72 | else: 73 | print("对不起,我不认识你!我不能给你开门!!!") 74 | name = 'Unknow' 75 | return 0 76 | current_time = time.asctime(time.localtime(time.time()))#获取当前时间 77 | 78 | #写入mysql 79 | try: 80 | #执行sql语句 81 | cur.execute("insert into person(name,time) values('%s','%s')"%(name, dt)) 82 | #cur.close() 83 | #提交到数据库执行 84 | conn.commit() 85 | print("---写入数据库成功---") 86 | except: 87 | #发生错误时回滚 88 | conn.rollback() 89 | print("---写入数据库失败---") 90 | #finally: 91 | #关闭数据库链接 92 | #conn.close() 93 | return 1 94 | 95 | #主函数 96 | if __name__ == '__main__': 97 | while True: 98 | print('准备开始人脸识别... ... ...') 99 | if True: 100 | print("---人脸识别成功,开门---") 101 | time.sleep(2)#缓解相机的卡顿 102 | img = transimage()#转换照片格式 103 | res = go_api(img)#将转换了格式的图片上传到百度云 104 | if(res == 1):#是人脸库中的人 105 | print("---人脸识别成功,开门---") 106 | else: 107 | print("---人脸识别失败,关门---") 108 | print('稍等三秒进入下一个') 109 | time.sleep(1) 110 | 111 | 112 | --------------------------------------------------------------------------------