<jupyter_start><jupyter_text>Imports<jupyter_code>import keras
import cv2
import os
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt<jupyter_output><empty_output><jupyter_text>Datagen Declaration<jupyter_code>datagen = keras.preprocessing.image.ImageDataGenerator(
    rotation_range=30,
    width_shift_range=0.0,
    height_shift_range=0.0,
    horizontal_flip=True,
    vertical_flip=True,
    rescale=None,
    preprocessing_function=None
)<jupyter_output><empty_output><jupyter_text>Setting user using Video<jupyter_code>def mark_video_user():
    cam = cv2.VideoCapture(0)
    cam.set(3, 640)
    cam.set(4, 480)
    face_detector = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')

    face_id = input('\n Assign an ID number and press enter ')
    print("\n  Look the camera and wait ...")

    ex = -1
    while(True):
        ret, img = cam.read()
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        faces = face_detector.detectMultiScale(gray, 1.3, 5)

        for (x,y,w,h) in faces:

            cv2.rectangle(img, (x,y), (x+w,y+h), (255,0,0), 2)     
            cv2.imshow('image', img)
            im = np.expand_dims(np.expand_dims(gray[y:y+h,x:x+w], 0), 3)
            datagen.fit(im)

            if ex!=1:
                for x, val in zip(datagen.flow(im, save_to_dir='project/dataset/', save_prefix="User_" + str(face_id), save_format='jpg'),range(100)):
                    ex = 1

        k = cv2.waitKey(100) & 0xff
        if k == 27:
            break
    #     if ex == 1:
    #         break
    print("\n Exiting Program and cleanup stuff")
    cam.release()
    cv2.destroyAllWindows()<jupyter_output><empty_output><jupyter_text>Setting user using image<jupyter_code>def mark_images_user(f):
    ex = -1
    img = cv2.resize(cv2.imread(f), (640, 480))
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_detector.detectMultiScale(gray, 1.3, 5)
    for (x,y,w,h) in faces:
        cv2.rectangle(img, (x,y), (x+w,y+h), (255,0,0), 2)     
        plt.imshow(gray[y:y+h,x:x+w])
        plt.show()
        face_id = input('\n Assign an ID number and press enter ')
        im = np.expand_dims(np.expand_dims(gray[y:y+h,x:x+w], 0), 3)
        datagen.fit(im)
        for x, val in zip(datagen.flow(im, save_to_dir='project/dataset/', save_prefix="User_" + str(face_id), save_format='jpg'),range(100)):
            ex = 1<jupyter_output><empty_output><jupyter_text>Setting Users<jupyter_code>mark_video_user()
# im_files = ['rp.jpg', 'rdj.jpg', 'cast.jpg']
# for i in im_files:
#     mark_images_user(i)<jupyter_output><empty_output><jupyter_text>Training on dataset prepared<jupyter_code>path = 'project/dataset'
recognizer = cv2.face.LBPHFaceRecognizer_create()
detector = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
def getImagesAndLabels(path):
    imagePaths = [os.path.join(path,f) for f in os.listdir(path)]     
    faceSamples=[]
    ids = []
    for imagePath in imagePaths:
        PIL_img = Image.open(imagePath).convert('L')
        img_numpy = np.array(PIL_img,'uint8')
        id = int(os.path.split(imagePath)[-1].split("_")[1])
        faces = detector.detectMultiScale(img_numpy)
        for (x,y,w,h) in faces:
            faceSamples.append(img_numpy[y:y+h,x:x+w])
            ids.append(id)
    return faceSamples,ids
print ("\n Training faces. It will take a few seconds. please Wait ...")
faces,ids = getImagesAndLabels(path)
recognizer.train(faces, np.array(ids))
recognizer.write('project/trainer/trainer.yml') 
print("\n  {0} faces trained. Exiting Program".format(len(np.unique(ids))))<jupyter_output>Training faces. It will take a few seconds. please Wait ...

  2 faces trained. Exiting Program<jupyter_text>Recognition<jupyter_code>recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read('project/trainer/trainer.yml')
faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
font = cv2.FONT_HERSHEY_SIMPLEX

id = 0
names = ['none','Tushar', 'rdj'] 

cam = cv2.VideoCapture(0)
cam.set(3, 640)
cam.set(4, 480)

minW = 0.1*cam.get(3)
minH = 0.1*cam.get(4)
while True:
    ret, img =cam.read()
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    
    faces = faceCascade.detectMultiScale(gray, scaleFactor = 1.2, minNeighbors = 5, minSize = (int(minW), int(minH)),)
    for(x,y,w,h) in faces:
        cv2.rectangle(img, (x,y), (x+w,y+h), (0,255,0), 2)
        id, confidence = recognizer.predict(gray[y:y+h,x:x+w])
        
        if (confidence < 100):
            id = names[id]
            confidence = "  {0}%".format(round(confidence))
        else:
            id = "unknown"
            confidence = "  {0}%".format(round(confidence))
        
        cv2.putText(img, str(id), (x+5,y-5), font, 1, (255,255,255), 2)
        cv2.putText(img, str(confidence), (x+5,y+h-5), font, 1, (255,255,0), 1)  
    
    cv2.imshow('camera',img) 
    k = cv2.waitKey(10) & 0xff
    if k == 27:
        break

print("\n [INFO] Exiting Program and cleanup stuff")
cam.release()
cv2.destroyAllWindows()
cam.release()
cv2.destroyAllWindows()<jupyter_output><empty_output><jupyter_text>IGNORE<jupyter_code>!pip uninstall opencv-contrib-python
!pip install opencv-contrib-python
# Path for face image database
path = 'project/dataset'
recognizer = cv2.face.LBPHFaceRecognizer_create()
detector = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
# function to get the images and label data
def getImagesAndLabels(path):
    imagePaths = [os.path.join(path,f) for f in os.listdir(path)]     
    faceSamples=[]
    ids = []
    for imagePath in imagePaths:
        PIL_img = Image.open(imagePath).convert('L') # grayscale
        img_numpy = np.array(PIL_img,'uint8')
        id = int(os.path.split(imagePath)[-1].split("_")[1])
        faces = detector.detectMultiScale(img_numpy)
        for (x,y,w,h) in faces:
            faceSamples.append(img_numpy[y:y+h,x:x+w])
            ids.append(id)
    return faceSamples,ids
print ("\n Training faces. It will take a few seconds. please Wait ...")
faces,ids = getImagesAndLabels(path)
recognizer.train(faces, np.array(ids))
# Save the model into trainer/trainer.yml
recognizer.write('project/trainer/trainer.yml') 
# Print the numer of faces trained and end program
print("\n  {0} faces trained. Exiting Program".format(len(np.unique(ids))))
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read('project/trainer/trainer.yml')
#cascadePath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
font = cv2.FONT_HERSHEY_SIMPLEX

#iniciate id counter
id = 0
# names related to ids: example ==> Marcelo: id=1,  etc
names = ['none','Tushar', 'RP', 'RDJ'] 

# Initialize and start realtime video capture
cam = cv2.VideoCapture(1)
cam.set(3, 640) # set video widht
cam.set(4, 480) # set video height

# Define min window size to be recognized as a face
minW = 0.1*cam.get(3)
minH = 0.1*cam.get(4)
while True:
    ret, img =cam.read()
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    
    faces = faceCascade.detectMultiScale( 
        gray,
        scaleFactor = 1.2,
        minNeighbors = 5,
        minSize = (int(minW), int(minH)),
       )
    for(x,y,w,h) in faces:
        cv2.rectangle(img, (x,y), (x+w,y+h), (0,255,0), 2)
        id, confidence = recognizer.predict(gray[y:y+h,x:x+w])
        
        # If confidence is less them 100 ==> "0" : perfect match 
        if (confidence < 100):
            id = names[id]
            confidence = "  {0}%".format(round(100 - confidence))
        else:
            id = "unknown"
            confidence = "  {0}%".format(round(100 - confidence))
        
        cv2.putText(
                    img, 
                    str(id), 
                    (x+5,y-5), 
                    font, 
                    1, 
                    (255,255,255), 
                    2
                   )
        cv2.putText(
                    img, 
                    str(confidence), 
                    (x+5,y+h-5), 
                    font, 
                    1, 
                    (255,255,0), 
                    1
                   )  
    
    cv2.imshow('camera',img) 
    k = cv2.waitKey(10) & 0xff # Press 'ESC' for exiting video
    if k == 27:
        break

# Do a bit of cleanup
print("\n [INFO] Exiting Program and cleanup stuff")
cam.release()
cv2.destroyAllWindows()
cam = cv2.VideoCapture(0)
cam.set(3, 640) # set video width
cam.set(4, 480) # set video height
face_detector = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
# For each person, enter one numeric face id
face_id = input('\n Assign an ID number and press enter ')
print("\n  Look the camera and wait ...")
# Initialize individual sampling face count
count = 0
while(True):
    ret, img = cam.read()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_detector.detectMultiScale(gray, 1.3, 5)
    for (x,y,w,h) in faces:
        cv2.rectangle(img, (x,y), (x+w,y+h), (255,0,0), 2)     
        count += 1
        # Save the captured image into the datasets folder
        cv2.imwrite("project/dataset/User." + str(face_id) + '.' +  
                    str(count) + ".jpg", gray[y:y+h,x:x+w])
        cv2.imshow('image', img)
    k = cv2.waitKey(100) & 0xff # Press 'ESC' for exiting video
    if k == 27:
        break
    elif count >= 30: # Take 30 face sample and stop video
         break
# Do a bit of cleanup
print("\n Exiting Program and cleanup stuff")
cam.release()
cv2.destroyAllWindows()
datagen = keras.preprocessing.image.ImageDataGenerator(
    featurewise_center=False,
    samplewise_center=False,
    featurewise_std_normalization=False,
    samplewise_std_normalization=False,
    zca_whitening=False,
    zca_epsilon=1e-06,
    rotation_range=30,
    width_shift_range=0.0,
    height_shift_range=0.0,
    brightness_range=None,
    shear_range=0.0,
    zoom_range=0.0,
    channel_shift_range=0.0,
    fill_mode="nearest",
    cval=0.0,
    horizontal_flip=True,
    vertical_flip=True,
    rescale=0.5,
    preprocessing_function=None,
    data_format=None,
    validation_split=0.0,
    dtype=None,
)
datagen.fit(np.expand_dims(cv2.imread("1.jpg"), axis=0))
for x, val in zip(datagen.flow(np.expand_dims(cv2.imread("1.jpg"), axis=0),
        save_to_dir='project/dataset/',
         save_prefix='aug',
        save_format='png'),range(30)):
    pass
img = cv2.resize(cv2.imread("rp.jpg"), (640, 480))
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_detector.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
    face_id = input('\n Assign an ID number and press enter ')
    cv2.rectangle(img, (x,y), (x+w,y+h), (255,0,0), 2)     
    count += 1
    im = np.expand_dims(np.expand_dims(gray[y:y+h,x:x+w], 0), 3)
    datagen.fit(im)
    for x, val in zip(datagen.flow(im, save_to_dir='project/dataset/', save_prefix="User_" + str(face_id), save_format='jpg'),range(30)):
        ex = 1
img = cv2.resize(cv2.imread("rdj.jpg"), (640, 480))
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_detector.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
    face_id = input('\n Assign an ID number and press enter ')
    cv2.rectangle(img, (x,y), (x+w,y+h), (255,0,0), 2)     
    count += 1
    im = np.expand_dims(np.expand_dims(gray[y:y+h,x:x+w], 0), 3)
    datagen.fit(im)
    for x, val in zip(datagen.flow(im, save_to_dir='project/dataset/', save_prefix="User_" + str(face_id), save_format='jpg'),range(30)):
        ex = 1<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.14353001627130257, 'fraction_numerical': 0.032114412948531304, 'mean_word_length': 3.043628808864266, 'pattern_counts': {'":': 0, '<': 34, '<?xml version=': 0, '>': 35, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 7}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '8', 'dir': 'jupyter-structured-clean-dedup', 'id': '260370', 'license': 'MIT', 'n_tokens_mistral': 4517, 'n_tokens_neox': 4255, 'n_words': 844, 'path': 'Face Detection and Recognition/Face Detection and Recognition.ipynb', 'repo_name': 'tusharsaxena250/AIML_Course', 'size': '11677'}