Haarcascade 2.02 KB
Newer Older
1
import cv2
2 3
import dlib
import numpy as np
4

5
# Create the haar cascade
6
detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
7 8 9 10

# create the landmark predictor
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")

11 12
cap = cv2.VideoCapture(0)

Arne Gerdes's avatar
Arne Gerdes committed
13
while True:
14 15

    # Read the Video
Arne Gerdes's avatar
Arne Gerdes committed
16
    ret, img = cap.read()
Arne Gerdes's avatar
Arne Gerdes committed
17 18

    # convert the video to gray scale
Arne Gerdes's avatar
Arne Gerdes committed
19
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
20

Arne Gerdes's avatar
Arne Gerdes committed
21 22 23 24
    # Contrast Limited Adaptive Histogram Equalization
    clahe = cv2.createCLAHE(clipLimit=4.0, tileGridSize=(8, 8))
    clahe_image = clahe.apply(gray)

25 26
    # Detect faces in the video
    faces = detector.detectMultiScale(
Arne Gerdes's avatar
Arne Gerdes committed
27
        clahe_image,
28 29 30 31 32 33
        scaleFactor=1.05,
        minNeighbors=5,
        minSize=(100, 100),
    )

    # Draw a rectangle around the faces
Arne Gerdes's avatar
Arne Gerdes committed
34
    for (x, y, w, h) in faces:
Arne Gerdes's avatar
Arne Gerdes committed
35
        cv2.rectangle(clahe_image, (x, y), (x + w, y + h), (255, 0, 0), 2)
36 37 38 39 40 41

        # Converting the OpenCV rectangle coordinates to Dlib rectangle
        dlib_rect = dlib.rectangle(int(x), int(y), int(x + w), int(y + h))

        # use that rectangle as the bounding box to detect the face landmarks,
        # and extract out the coordinates of the landmarks so OpenCV can use them
Arne Gerdes's avatar
Arne Gerdes committed
42
        detected_landmarks = predictor(clahe_image, dlib_rect).parts()
43 44 45 46 47 48 49
        landmarks = np.matrix([[p.x, p.y] for p in detected_landmarks])

        # enumerate through the landmark coordinates and mark them on the image
        for idx, point in enumerate(landmarks):
            pos = (point[0, 0], point[0, 1])

            # annotate the positions
Arne Gerdes's avatar
Arne Gerdes committed
50
            cv2.putText(clahe_image, str(idx), pos,
51 52 53 54 55
                        fontFace=cv2.FONT_HERSHEY_SIMPLEX,
                        fontScale=0.4,
                        color=(0, 0, 255))

            # draw points on the landmark positions
Arne Gerdes's avatar
Arne Gerdes committed
56
            cv2.circle(clahe_image, pos, 3, color=(0, 255, 255))
57 58

    # draw the annotated image on an OpenCV window
Arne Gerdes's avatar
Arne Gerdes committed
59
    cv2.imshow('Window', clahe_image)
60

Arne Gerdes's avatar
Arne Gerdes committed
61 62
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
63 64 65

cap.release()
cv2.destroyAllWindows()