How to Detect Faces With Python, Really Easy!

In this article, we will learn how to detect features like eyes, nose and mouth on a face in Python. After this post, you will be able to create effects and filters similar to what you see on Snapchat and Instagram.

Face detection (also called face detection) is an artificial intelligence (AI)-based computer technology used to locate and identify human faces in digital images. Face detection technology; It is a technology that is widely used in the health, military and security fields. Facial recognition has evolved from basic computer vision techniques to advances in machine learning, to increasingly complex artificial neural networks and related technologies.

How to Detect Faces in Python

Our face has various recognizable features, such as eyes, mouth, nose, lips, etc. When we use the algorithm DLib to define these properties, we actually get a map of the dots surrounding each feature. So what is this DLib? DLib is an advanced machine learning library used to solve complex real-world problems. This library is built using C++ programming language, also works in C/C++, Python, and Java languages.

This map consists of 67 points (also called landmarks) and can define the following features:

Points map
  • Jaw Points: 0-16
  • Right Eyebrow Points: 17-21
  • Left Eyebrow Points: 22-26
  • Nose Points: 27-35
  • Right Eye Point: 36-41
  • Left Eye Points: 42-47
  • Mouth Points: 48-60
  • Lip Points: 61-67

Installing Required Modules

For how to make face detection in Python, we first need to load this Module by writing the following to the terminal:

pip instal opencv-python, dlib

You may get some errors while installing the Module dlib on some operating systems. One of these errors is a mistake CMake. To handle this, we need to install the Module CMake before loading the Module dlib .

pip instal cmake

After loading the required Modules, we can include these Modules in our project.

impor cv2
impor dlib

[su_box title=”Baca Juga” style=”noise” box_color=”#a3e2fd” title_color=”#000000″]

[/su_box]

How to Create a Face Detection App in Python

We upload our photos using the OpenCv Module.

img = cv2.imread ("photo.png")

# Menunjukkan foto ke layar
cv2.imshow (winname = "Wajah", mat = img)

# Anda harus menekan tombol untuk menutup foto
cv2.waitKey (penundaan = 0)

# Menutup semua jendela.
cv2.destroyAllWindows ()

Pretty simple, right? We upload photos and print them on the screen using the method .imshow . If you run this code, you will see a photo named Face .

python-with-face detection
Photo named Face

Now we will do face detection using function get_frontal_face_detector() from the library Dlib . However, this function only works on grayscale photos, so by using the library OpenCv we change the photo to gray.

The get_frontal_face_detector() returns a function called “detector” which is necessary for us to use facial information. Each face is an object containing points that the image can find.

impor cv2
impor dlib

detektor = dlib.get_frontal_face_detector ()

img = cv2.imread ("photo.png")

# Mengubah gambar menjadi skala abu-abu.
abu-abu = cv2.cvtColor (src = img, kode = cv2.COLOR_BGR2GRAY)

# Kami menggunakan fungsi detektor untuk mendeteksi wajah.
wajah = detektor (abu-abu)

untuk wajah di wajah:
    x1 = face.left ()
    y1 = face.top ()
    x2 = wajah.right ()
    y2 = face.bottom ()

    # Kami menggambar persegi panjang
    cv2. rectangle (img = img, pt1 = (x1, y1), pt2 = (x2, y2), color = (0,255,0), tebal = 4)

#show gambar
cv2.imshow (winname = "Wajah", mat = img)

cv2.waitKey (penundaan = 0)

cv2.destroyAllWindows ()

The code above takes all the faces in the image and creates a rectangle on each face.

Face detected photo
Face detected photo

In the next step, we will explore some facial features, as we mentioned earlier. We will use the DLib module for this again. Function shape_predictor() which offered by this library does all this magic work for us. However, we need a trained model for it to work.

There are many models on the internet for this, you can download the model I used for this project.

impor cv2
impor dlib

detektor = dlib.get_frontal_face_detector ()

predictor = dlib.shape.predictor ("shape_predictor_68_face_landmarks.dat")

img = cv2.imread ("photo.png")

abu-abu = cv2.cvtColor (src = img, kode = cv2.COLOR_BGR2GRAY)

wajah = detektor (abu-abu)

untuk wajah di wajah:
    x1 = face.left ()
    y1 = face.top ()
    x2 = wajah.right ()
    y2 = face.bottom ()
    landmark = prediktor (gambar = abu-abu, box = wajah)
    x = landmark. bagian (27) .x
    y = landmark. bagian (27) .y

   cv2.circle (img = img, center = (x, y), radius = 5, color = (0,255,0), thick = -1)

cv2.imshow (winname = "Wajah", mat = img)
cv2.waitKey (penundaan = 0)
cv2.destroyAllWindows ()

We make improvements to the same code every time, this time we use the predictor by different . What interests us here is why we use the number 27?

The predictor function here will return an object containing all 68 points that correspond to the face diagram at the beginning of the post. Notice that the 27 dots exactly coincide between the eyes. If everything is working correctly, you will see a green dot between the eyes on the face.

Green spot between eyes
Green spot between eyes

Now let’s show all the points, not one point.

impor cv2
impor dlib

detektor = dlib.get_frontal_face_detector ()

predictor = dlib.shape.predictor ("shape_predictor_68_face_landmarks.dat")

img = cv2.imread ("photo.png")

abu-abu = cv2.cvtColor (src = img, kode = cv2.COLOR_BGR2GRAY)

wajah = detektor (abu-abu)

untuk wajah di wajah:
    x1 = face.left ()
    y1 = face.top ()
    x2 = wajah.right ()
    y2 = face.bottom ()
    landmark = prediktor (gambar = abu-abu, box = wajah)
    untuk n dalam rentang (0,68):
        x = landmark. bagian (n) .x
        y = landmark. bagian (n) .y

   cv2.circle (img = img, center = (x, y), radius = 5, color = (0,255,0), thick = -1)

cv2.imshow (winname = "Wajah", mat = img)
cv2.waitKey (penundaan = 0)
cv2.destroyAllWindows ()

And we get results like this.

The next and final stage is the most interesting part! We will connect our webcam and perform real-time face detection.

impor cv2
impor dlib

detektor = dlib.get_frontal_face_detector ()
predictor = dlib.shape_predictor ("shape_predictor_68_face_landmarks.dat")

cap = cv2.VideoCapture (0)
sementara Benar:
  _, frame = cap.read() 

  gray = cv2.cvtColor(src=frame, code=cv2.COLOR_BGR2GRAY) 
  faces = detector(gray) 
  for face in faces: 
      x1 = face.left() 
      y1 = face.top() 
      x2 = face.right() 
      y2 = face.bottom() 
      landmarks = predictor(image=gray, box=face) 
      for n in range(0,68): 
          x = landmarks.part(n).x 
          y = landmarks.part(n).y 
         cv2.circle(img=frame, center=(x,y), radius=2, color=(0,255,0),thickness=-1)
   cv2.imshow(winname="Face",mat=frame) 
   if cv2.waitKey(delay=1)== 27: 
            break
cap.release ()
cv2.destroyAllWindows ()

Using the code above, you can activate your computer’s camera and perform real-time face detection in Python. The result should be as follows:

how face detection works using Python module

[su_box title=”Baca Juga” style=”noise” box_color=”#a3e2fd” title_color=”#000000″]

[/su_box]

As we can see, this is how face detection works using the Python module. The OpenCV and DLib libraries are very powerful libraries that facilitate working with machine learning and computer vision.

[su_note]Don’t forget to like Facebook Caraqu if you want to get notifications quickly.[/su_note]