|
| 1 | +import cv2 |
| 2 | +from face_recognition.api import face_encodings |
| 3 | +import numpy as np |
| 4 | +import face_recognition |
| 5 | +import os |
| 6 | +from datetime import datetime |
| 7 | + |
| 8 | +path= 'images' |
| 9 | + |
| 10 | +images=[] |
| 11 | + |
| 12 | +personName=[] |
| 13 | + |
| 14 | +myList=os.listdir(path) |
| 15 | + |
| 16 | +print(myList) |
| 17 | + |
| 18 | +for cu_img in myList: |
| 19 | + current_Img=cv2.imread(f'{path}/{cu_img}') |
| 20 | + images.append(current_Img) |
| 21 | + personName.append(os.path.splitext(cu_img)[0]) |
| 22 | + |
| 23 | +print(personName) |
| 24 | + |
| 25 | + |
| 26 | +def faceEncodings(images): |
| 27 | + encodeList=[] |
| 28 | + |
| 29 | + for img in images: |
| 30 | + img=cv2.cvtColor(img,cv2.COLOR_BGR2RGB) |
| 31 | + encode=face_recognition.face_encodings(img)[0] |
| 32 | + encodeList.append(encode) |
| 33 | + |
| 34 | + return encodeList |
| 35 | + |
| 36 | +encodeListKnown = (faceEncodings(images)) |
| 37 | + |
| 38 | +print("All Encoding Complete!!!!!") |
| 39 | + |
| 40 | + |
| 41 | +def attendance(name): |
| 42 | + with open('Attendance.csv','r+') as f: |
| 43 | + myDataList = f.readlines() |
| 44 | + nameList = [] |
| 45 | + for line in myDataList: |
| 46 | + entry = line.split(',') |
| 47 | + nameList.append(entry[0]) |
| 48 | + |
| 49 | + if name not in nameList: |
| 50 | + time_now = datetime.now() |
| 51 | + tStr = time_now.strftime('%H:%M:%S') |
| 52 | + dStr = time_now.strftime('%d/%m/%Y') |
| 53 | + f.writelines(f'{name},{tStr},{dStr}') |
| 54 | + |
| 55 | + |
| 56 | +cap= cv2.VideoCapture(0) |
| 57 | + |
| 58 | +while True: |
| 59 | + |
| 60 | + ret,frame = cap.read() |
| 61 | + faces = cv2.resize(frame,(0,0),None,0.25,0.25) |
| 62 | + faces= cv2.cvtColor(faces,cv2.COLOR_BGR2RGB) |
| 63 | + |
| 64 | + |
| 65 | + facesCurrentFrame = face_recognition.face_locations(faces) |
| 66 | + encodesCurrentFrame = face_recognition.face_encodings(faces,facesCurrentFrame) |
| 67 | + |
| 68 | + |
| 69 | + for encodeFace,faceLoc in zip(encodesCurrentFrame, facesCurrentFrame): |
| 70 | + matches = face_recognition.compare_faces(encodeListKnown,encodeFace) |
| 71 | + faceDis = face_recognition.face_distance(encodeListKnown,encodeFace) |
| 72 | + |
| 73 | + matchIndex = np.argmin(faceDis) |
| 74 | + |
| 75 | + if matches[matchIndex]: |
| 76 | + name = personName[matchIndex].upper() |
| 77 | + # print(name) |
| 78 | + y1,x2,y2,x1 = faceLoc |
| 79 | + |
| 80 | + y1,x2,y2,x1 = y1*4,x2*4,y2*4,x1*4 |
| 81 | + cv2.rectangle(frame,(x1,y1),(x2,y2),(0,255,0),2) |
| 82 | + cv2.rectangle(frame,(x1,y2-35),(x2,y2),(0,255,0),cv2.FILLED) |
| 83 | + cv2.putText(frame,name,(x1+6, y2-6), cv2.FONT_HERSHEY_COMPLEX,1,(255,0,0), 1) |
| 84 | + attendance(name) |
| 85 | + cv2.imshow("Camera", frame) |
| 86 | + |
| 87 | + if cv2.waitKey(10) == 13: |
| 88 | + break |
| 89 | + |
| 90 | +cap.release() |
| 91 | + |
| 92 | +cv2.destroyAllWindows() |
0 commit comments