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