0

I am trying to run a code for recognition of faces directly from the web cam but I am facing the following errors.

C:\Users\user\python.exe C:/Users/user/PycharmProjects/FaceRecognition/Attendance.py
Traceback (most recent call last):
  File "C:/Users/user/PycharmProjects/FaceRecognition/Attendance.py", line 3, in <module>
    import face_recognition
  File "C:\Users\user\AppData\Roaming\Python\Python38\site-packages\face_recognition\__init__.py", line 7, in <module>
    from .api import load_image_file, face_locations, batch_face_locations, face_landmarks, face_encodings, compare_faces, face_distance
  File "C:\Users\user\AppData\Roaming\Python\Python38\site-packages\face_recognition\api.py", line 17, in <module>
    face_detector = dlib.get_frontal_face_detector()
AttributeError: module 'dlib' has no attribute 'get_frontal_face_detector'`

I have downloaded the face recognition library and I also have the dlib dependency in the same folder as the project folder yet I am facing this issue.

This is my entire code

import cv2 
import numpy as np 
import face_recognition 
import os 
from datetime import datetime


# from PIL import ImageGrab

path = 'ImagesAttendance' images = [] classNames = [] myList = os.listdir(path) print(myList) for cl in myList:
    curImg = cv2.imread(f'{path}/{cl}')
    images.append(curImg)
    classNames.append(os.path.splitext(cl)[0]) print(classNames)


def findEncodings(images):
    encodeList = []


    for img in images:
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        encode = face_recognition.face_encodings(img)[0]
        encodeList.append(encode)
    return encodeList


def markAttendance(name):
    with open('Attendance.csv', 'r+') as f:
        myDataList = f.readlines()
        nameList = []
        for line in myDataList:
            entry = line.split(',')
            nameList.append(entry[0])
            if name not in nameList:
                now = datetime.now()
                dtString = now.strftime('%H:%M:%S')
                f.writelines(f'n{name},{dtString}')

#### FOR CAPTURING SCREEN RATHER THAN WEBCAM
# def captureScreen(bbox=(300,300,690+300,530+300)):
#     capScr = np.array(ImageGrab.grab(bbox))
#     capScr = cv2.cvtColor(capScr, cv2.COLOR_RGB2BGR)
#     return capScr

encodeListKnown = findEncodings(images) print('Encoding Complete')

cap = cv2.VideoCapture(0)

while True:
    success, img = cap.read()
# img = captureScreen()
    imgS = cv2.resize(img, (0, 0), None, 0.25, 0.25)
    imgS = cv2.cvtColor(imgS, cv2.COLOR_BGR2RGB)

    facesCurFrame = face_recognition.face_locations(imgS)
    encodesCurFrame = face_recognition.face_encodings(imgS, facesCurFrame)

    for encodeFace, faceLoc in zip(encodesCurFrame, facesCurFrame):
        matches = face_recognition.compare_faces(encodeListKnown, encodeFace)
        faceDis = face_recognition.face_distance(encodeListKnown, encodeFace)
        # print(faceDis)
        matchIndex = np.argmin(faceDis)

        if matches[matchIndex]:
            name = classNames[matchIndex].upper()
            # print(name)
            y1, x2, y2, x1 = faceLoc
            y1, x2, y2, x1 = y1 * 4, x2 * 4, y2 * 4, x1 * 4
            cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
            cv2.rectangle(img, (x1, y2 - 35), (x2, y2), (0, 255, 0), cv2.FILLED)
            cv2.putText(img, name, (x1 + 6, y2 - 6), cv2.FONT_HERSHEY_COMPLEX, 1, (255, 255, 255), 2)
            markAttendance(name)

cv2.imshow('Webcam', img) cv2.waitKey(1)
mck
  • 40,932
  • 13
  • 35
  • 50

2 Answers2

0

Dlib is an amazing library but its installation is costly. I recommended you to use deepface. It wraps dlib but it comes with several cutting edge facial detectors. They are all based on tensorflow except dlib. That's why, installing and running those detectors will be easier than core dlib.

img_path = "img1.jpg"
backends = ['opencv', 'ssd', 'mtcnn', 'dlib', 'retinaface']
img = DeepFace.detectFace(img_path, detector_backend = backend[2])
johncasey
  • 1,250
  • 8
  • 14
0

What i did after this error, and many others before, is the following: first I installed Visual Studio and enabled Desktop development with C++ (if the following steps don't work, is possible that you are missing a checkbox, I use VS 2022 and I checked the followings checkboxes1 checkboxes2 *I use it in Spanish but it shouldn't be difficult to follow it.

Then followed steps 1 to 3 from https://stackoverflow.com/a/49538054/14945612 (Download and Installation of CMake).

Finally using Python 3.9 (didn't work for me using 3.10 nor 3.11) I installed the followings packages versions (it didn't work for me with newer ones):

pip install "cmake==3.21.4"

pip install -v "dlib==19.22.1"

pip install "face-recognition==1.3.0"

Check that you install them in your correct environment/interpreter. In my case I created a new conda environment with Python 3.9 and then use this new environment as my PyCharm Interpreter. That way I downgrade my Python.

Cheers!

Daniel
  • 1
  • 1
  • Visual Studio is your own preference for IDE. But the OP asked nothing about IDE, and there is no reason to start any answer by "install MY favorite IDE" when it is just about a given library. Otherwise, I could also answer by the good old "flame war", "erase Windows, install linux, then install python and your library". – chrslg Feb 08 '23 at 22:15
  • You are right, OP didn't ask about his favorite IDE, VS isn't even my favorite one or the one I use. I just used it as a C++ compiler so I was able to download successfully and use the asked library correctly (my experience). I'll edit my answer to change the tone and make it clear it was my experience how I was able to fix the problem, it's just an advice. Cheers. – Daniel Feb 10 '23 at 00:19