├── README.md ├── haarcascade_frontalface_alt.xml ├── haarcascade_frontalface_default.xml ├── recognizer.py ├── recognizer_by_name.py └── train_model.py /README.md: -------------------------------------------------------------------------------- 1 | # Face-Recognizer-Using-LBPH-Recognizer 2 | 3 | This is a Desktop Application on Face Recognition Using LBPH Recognizer. 4 | 5 | Follow this video to understand the functionality of this code: 6 | https://www.youtube.com/watch?v=VTcMFtaIhag&lc=UgxbVdKzSQlvsEw9QLN4AaABAg 7 | -------------------------------------------------------------------------------- /recognizer.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | 4 | #pip install opencv-contrib-python 5 | 6 | recognizer = cv2.face.LBPHFaceRecognizer_create() 7 | recognizer.read('model/trained_model2.yml') 8 | cascadePath = "haarcascade_frontalface_default.xml" 9 | faceCascade = cv2.CascadeClassifier(cascadePath) 10 | font = cv2.FONT_HERSHEY_SIMPLEX 11 | 12 | cam = cv2.VideoCapture(0) 13 | while True: 14 | ret, im =cam.read() 15 | gray=cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) 16 | faces=faceCascade.detectMultiScale(gray, 1.2,5) 17 | 18 | for(x,y,w,h) in faces: 19 | Id, conf = recognizer.predict(gray[y:y+h,x:x+w]) 20 | 21 | cv2.rectangle(im, (x, y), (x + w, y + h), (0, 260, 0), 7) 22 | cv2.putText(im, str(Id), (x,y-40),font, 2, (255,255,255), 3) 23 | 24 | cv2.imshow('im',im) 25 | if cv2.waitKey(10) & 0xFF==ord('q'): 26 | break 27 | cam.release() 28 | cv2.destroyAllWindows() -------------------------------------------------------------------------------- /recognizer_by_name.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | 4 | recognizer = cv2.face.LBPHFaceRecognizer_create() 5 | recognizer.read('model/trained_model2.yml') 6 | cascadePath = "haarcascade_frontalface_default.xml" 7 | faceCascade = cv2.CascadeClassifier(cascadePath) 8 | font = cv2.FONT_HERSHEY_SIMPLEX 9 | id = 0 10 | 11 | # add the list of names of your dataset here 12 | names = ['None','Aarohi','Piford','Sorav'] 13 | 14 | 15 | cam = cv2.VideoCapture(0) 16 | 17 | while True: 18 | ret, img =cam.read() 19 | #img = cv2.flip(img, -1) # Flip vertically 20 | gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) 21 | 22 | faces = faceCascade.detectMultiScale( 23 | gray, 24 | scaleFactor = 1.2, 25 | minNeighbors = 5 26 | ) 27 | for(x,y,w,h) in faces: 28 | cv2.rectangle(img, (x,y), (x+w,y+h), (0,255,0), 2) 29 | id, confidence = recognizer.predict(gray[y:y+h,x:x+w]) 30 | 31 | # If confidence is less them 100 ==> "0" : perfect match 32 | if (confidence < 100): 33 | id = names[id] 34 | confidence = " {0}%".format(round(100 - confidence)) 35 | else: 36 | id = "unknown" 37 | confidence = " {0}%".format(round(100 - confidence)) 38 | 39 | cv2.putText( 40 | img, 41 | str(id), 42 | (x+5,y-5), 43 | font, 44 | 1, 45 | (255,255,255), 46 | 2 47 | ) 48 | 49 | 50 | cv2.imshow('camera',img) 51 | k = cv2.waitKey(10) & 0xff # Press 'ESC' for exiting video 52 | if k == 27: 53 | break 54 | # Do a bit of cleanup 55 | print("\n [INFO] Exiting Program and cleanup stuff") 56 | cam.release() 57 | cv2.destroyAllWindows() 58 | -------------------------------------------------------------------------------- /train_model.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | from tkinter import * 3 | import cv2 4 | import csv 5 | import os 6 | import numpy as np 7 | from PIL import Image,ImageTk 8 | import pandas as pd 9 | import datetime 10 | import time 11 | 12 | #####Window is our Main frame of system 13 | window = tk.Tk() 14 | window.title("Face Recognition- Piford Technologies, IT Park, Mohali") 15 | window.geometry('1280x720') 16 | window.configure() 17 | 18 | 19 | ###For take images for datasets 20 | def take_img(): 21 | 22 | cam = cv2.VideoCapture(0) 23 | detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') 24 | ID = txt.get() 25 | Name = txt2.get() 26 | sampleNum = 0 27 | while (True): 28 | ret, img = cam.read() 29 | gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 30 | faces = detector.detectMultiScale(gray, 1.3, 5) 31 | 32 | for (x, y, w, h) in faces: 33 | cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2) 34 | # incrementing sample number 35 | sampleNum = sampleNum + 1 36 | # saving the captured face in the dataset folder 37 | cv2.imwrite("dataset/ " + Name + "." + ID + '.' + str(sampleNum) + ".jpg", 38 | gray[y:y + h, x:x + w]) 39 | cv2.imshow('Frame', img) 40 | # wait for 100 miliseconds 41 | if cv2.waitKey(1) & 0xFF == ord('q'): 42 | break 43 | # break if the sample number is morethan 100 44 | elif sampleNum > 200: 45 | break 46 | cam.release() 47 | cv2.destroyAllWindows() 48 | 49 | res = "Images Saved : " + ID + " Name : " + Name 50 | Notification.configure(text=res, bg="SpringGreen3", width=50, font=('times', 18, 'bold')) 51 | Notification.place(x=250, y=400) 52 | 53 | 54 | 55 | ###For train the model 56 | def trainimg(): 57 | recognizer = cv2.face.LBPHFaceRecognizer_create() 58 | global detector 59 | detector = cv2.CascadeClassifier("haarcascade_frontalface_default.xml") 60 | try: 61 | global faces,Id 62 | faces, Id = getImagesAndLabels("dataset") 63 | except Exception as e: 64 | l='please make "dataset" folder & put Images' 65 | Notification.configure(text=l, bg="SpringGreen3", width=50, font=('times', 18, 'bold')) 66 | Notification.place(x=350, y=400) 67 | 68 | recognizer.train(faces, np.array(Id)) 69 | try: 70 | recognizer.save("model/trained_model2.yml") 71 | except Exception as e: 72 | q='Please make "model" folder' 73 | Notification.configure(text=q, bg="SpringGreen3", width=50, font=('times', 18, 'bold')) 74 | Notification.place(x=350, y=400) 75 | 76 | res = "Model Trained" # +",".join(str(f) for f in Id) 77 | Notification.configure(text=res, bg="SpringGreen3", width=50, font=('times', 18, 'bold')) 78 | Notification.place(x=250, y=400) 79 | 80 | 81 | 82 | def getImagesAndLabels(path): 83 | imagePaths = [os.path.join(path, f) for f in os.listdir(path)] 84 | # create empth face list 85 | faceSamples = [] 86 | # create empty ID list 87 | Ids = [] 88 | # now looping through all the image paths and loading the Ids and the images 89 | for imagePath in imagePaths: 90 | # loading the image and converting it to gray scale 91 | pilImage = Image.open(imagePath).convert('L') 92 | # Now we are converting the PIL image into numpy array 93 | imageNp = np.array(pilImage, 'uint8') 94 | # getting the Id from the image 95 | 96 | Id = int(os.path.split(imagePath)[-1].split(".")[1]) 97 | # extract the face from the training image sample 98 | faces = detector.detectMultiScale(imageNp) 99 | # If a face is there then append that in the list as well as Id of it 100 | for (x, y, w, h) in faces: 101 | faceSamples.append(imageNp[y:y + h, x:x + w]) 102 | Ids.append(Id) 103 | return faceSamples, Ids 104 | 105 | 106 | window.grid_rowconfigure(0, weight=1) 107 | window.grid_columnconfigure(0, weight=1) 108 | 109 | 110 | def on_closing(): 111 | from tkinter import messagebox 112 | if messagebox.askokcancel("Quit", "Do you want to quit?"): 113 | window.destroy() 114 | window.protocol("WM_DELETE_WINDOW", on_closing) 115 | 116 | 117 | 118 | Notification = tk.Label(window, text="All things good", bg="Green", fg="white", width=15, height=3) 119 | 120 | lbl = tk.Label(window, text="Enter id", width=20, height=2, fg="black", font=('times', 20, 'italic bold ')) 121 | lbl.place(x=200, y=200) 122 | 123 | def testVal(inStr,acttyp): 124 | if acttyp == '1': #insert 125 | if not inStr.isdigit(): 126 | return False 127 | return True 128 | 129 | 130 | message = tk.Label(window, text="Piford Technologies-Face-Recognition", bg="cyan", fg="black", width=50, 131 | height=3, font=('times', 30, 'italic bold ')) 132 | 133 | message.place(x=80, y=20) 134 | 135 | txt = tk.Entry(window, validate="key", width=20, fg="red") 136 | txt['validatecommand'] = (txt.register(testVal),'%P','%d') 137 | txt.place(x=550, y=210) 138 | 139 | lbl2 = tk.Label(window, text="Enter Name", width=20, fg="black", height=2, font=('times', 20, 'italic bold ')) 140 | lbl2.place(x=200, y=300) 141 | 142 | txt2 = tk.Entry(window, width=20, fg="red") 143 | txt2.place(x=550, y=310) 144 | 145 | takeImg = tk.Button(window, text="Take Images",command=take_img,fg="black", bg="green" ,width=20 ,height=3, activebackground = "Red" ,font=('times', 20, 'italic bold ')) 146 | takeImg.place(x=200, y=500) 147 | 148 | trainImg = tk.Button(window, text="Train Images",fg="black",command=trainimg ,bg="green" ,width=20 ,height=3, activebackground = "Red",font=('times', 20, 'italic bold ')) 149 | trainImg.place(x=590, y=500) 150 | 151 | window.mainloop() --------------------------------------------------------------------------------