import cv2 import numpy as np Load the face detection model face_cascade = cv2.CascadeClassifier(`haarcascade_frontalface_default.xml`) Read an image image = cv2.imread(`image.jpg`) Convert the image to grayscale grayscale_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) Detect faces in the image faces = face_cascade.detectMultiScale(grayscale_image, 1.1, 5) Iterate over the detected faces for (x, y, w, h) in faces: # Draw a rectangle around the face cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2) Display the image cv2.imshow(`Image with faces detected`, image) cv2.waitKey(0) This code works by loading a facial detection model from the OpenCV library. It then converts the image to grayscale and applies the facial detection model to it. If any faces are detected in the image, a rectangle will be drawn around them. Here is a breakdown of some of the things the code does: The lines import cv2 and import numpy as np import the OpenCV and NumPy libraries. The line face_cascade = cv2.CascadeClassifier(`haarcascade_frontalface_default.xml`) loads the facial detection model from the file haarcascade_frontalface_default.xml . The line image = cv2.imread(`image.jpg`) reads an image from the file image.jpg . The line grayscale_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) converts the image to grayscale. The line faces = face_cascade.detectMultiScale(grayscale_image, 1.1, 5) applies the facial detection model to the image. The section for (x, y, w, h) in faces: loops through the list of detected faces. The line cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2) draws a rectangle around each face. The line cv2.imshow(`Image with faces detected`, image) displays the image with the rectangles around the faces. The line cv2.waitKey(0) pauses the program until the user presses a key. You can modify this code to change the size, color, or thickness of the rectangles. You can also add code to print additional information about the detected faces, such as the size and location of the face. Here is an example of how to modify the code to change the color of the rectangles: for (x, y, w, h) in faces: # Draw a rectangle around the face cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2)
©