import cv2 # Load the cascade classifier for face detection face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') # Read the image file img = cv2.imread('face.jpg') # Convert the image to grayscale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Detect faces in the grayscale image faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5) # Draw bounding boxes around the detected faces for (x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2) # Display the output image cv2.imshow('Output', img) cv2.waitKey(0)
import dlib import cv2 # Load the shape predictor for detecting facial landmarks predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat') # Read the image file img = cv2.imread('face.jpg') # Convert the image to grayscale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Detect the face in the grayscale image detector = dlib.get_frontal_face_detector() faces = detector(gray, 0) # Get the facial landmarks for each face for face in faces: landmarks = predictor(gray, face) # Draw the facial landmarks on the image for n in range(68): x = landmarks.part(n).x y = landmarks.part(n).y cv2.circle(img, (x, y), 2, (0, 255, 0), -1) # Display the output image cv2.imshow('Output', img) cv2.waitKey(0)This code uses the dlib library to detect facial landmarks on a detected face. The `shape_predictor` method loads a pre-trained model for predicting the locations of 68 landmarks on a face. The `get_frontal_face_detector` method is used to detect the face in the image, and the `predictor` method is used to predict the location of the facial landmarks. The `circle` method is used to draw circles at the predicted landmark locations. In summary, both OpenCV and dlib are popular Python libraries used for detecting and extracting parts of a human face, such as the face itself or facial landmarks.