Packages to install :
- pip install opencv-python.
- pip install mediapipe.
Program :
# Face Detection using mediapipe with python
import cv2
import mediapipe as mp
import time
# Creating objects for detecting face
mpFaceDetection = mp.solutions.face_detection
mpDraw = mp.solutions.drawing_utils
faceDetection = mpFaceDetection.FaceDetection()
# Capturing video from the web cam
video = cv2.VideoCapture(0)
currentTime = 0
previousTime = 0
while True:
success, img = video.read()
# Converting BGR image to RGB image
RGBimg = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# Getting landmark points and storing in multiHandLandmarks variable
result = faceDetection.process(RGBimg)
# This 'if' block will run when it's having the face landmark points
if result.detections:
for index, detection in enumerate(result.detections):
score = detection.score[0] * 100
boundingBox = detection.location_data.relative_bounding_box
imgh, imgw, imgc = img.shape
x, y, w, h = int(boundingBox.xmin * imgw), int(boundingBox.ymin * imgh), int(boundingBox.width * imgw), int(boundingBox.height * imgh)
# creating rectangle box around the face
cv2.rectangle(img, (x, y, w, h), (0, 255, 0), 2)
cv2.putText(img, f"{int(score)}%", (x, y-15), cv2.FONT_HERSHEY_PLAIN, 2,(0, 255, 0), 2)
# calculating frames per second
currentTime = time.time()
fps = 1 / (currentTime - previousTime)
previousTime = currentTime
imgShape = img.shape[0:2]
# This will show the fps value on screen
cv2.putText(img, f"FPS: {int(fps)}", ((imgShape[1]-imgShape[1])+20, imgShape[0] - 50), cv2.FONT_HERSHEY_PLAIN, 2, (0, 0, 0), 2)
cv2.imshow("Face Detection", img)
key = cv2.waitKey(1)
if key == 13:
exit()
Comments