Learn practical skills, build real-world projects, and advance your career
import cv2
import matplotlib.pyplot as plt
import numpy as np
import os
import glob
import time
import jovian

Dataset Generator

id = int(input("Enter your ID : "))
cap = cv2.VideoCapture(0)
count = 1
classifier = cv2.CascadeClassifier('C:/Users/vsneh/Udemy-notebooks/DATA/haarcascades/haarcascade_frontalface_default.xml')

while(True):
    _,frames = cap.read()
    gray = cv2.cvtColor(frames,cv2.COLOR_BGR2GRAY)
    points = classifier.detectMultiScale(gray,1.3,3)
    for x,y,w,h in points:
        cv2.imwrite('C:/Users/vsneh/Udemy-notebooks/Y_DATA/{}.{}.jpg'.format(id,count),gray[y:y+h,x:x+w])
        count = count+1
        cv2.rectangle(frames,(x,y),(x+w,y+h),(255,255,255),2)
    cv2.imshow('img',frames)
    #print(count)
    time.sleep(.01)
    if(cv2.waitKey(1)==ord('q') or count>=300 ):
        break
cap.release()
cv2.destroyAllWindows()
Enter your ID : 57

Model Preparation, Trainning and Saving

import cv2,os
import numpy as np
from PIL import Image

recognizer = cv2.face.LBPHFaceRecognizer_create()
path = 'C:\\Users\\vsneh\\Udemy-notebooks\\Y_DATA'
def getImagesAndLabels(path):
    #get the path of all the files in the folder
    imagePaths=[os.path.join(path,f) for f in os.listdir(path)] 
    #create empth face list
    faceSamples=[]
    #create empty ID list
    Ids=[]
    #now looping through all the image paths and loading the Ids and the images
    for imagePath in imagePaths:

        # Updates in Code
        # ignore if the file does not have jpg extension :
        if(os.path.split(imagePath)[-1].split(".")[-1]!='jpg'):
            continue

        #loading the image and converting it to gray scale
        pilImage=Image.open(imagePath).convert('L')
        #Now we are converting the PIL image into numpy array
        imageNp=np.array(pilImage,'uint8')
        #getting the Id from the image
        Id=int(os.path.split(imagePath)[-1].split(".")[0].split('-')[0])
        faceSamples.append(imageNp)
        Ids.append(Id)
    return faceSamples,Ids

faces,Ids = getImagesAndLabels(path)
recognizer.train(faces, np.array(Ids))
recognizer.write('C:\\Users\\vsneh\\Udemy-notebooks\\Y_DATA\\trainner.yml')