|
| 1 | +import cv2 |
| 2 | +import mediapipe as mp |
| 3 | +import time |
| 4 | + |
| 5 | +def resize_image(img, max_width=1000, max_height=800): |
| 6 | + """Resizes the image while maintaining aspect ratio.""" |
| 7 | + height, width, _ = img.shape |
| 8 | + scale = min(max_width / width, max_height / height) |
| 9 | + return cv2.resize(img, None, fx=scale, fy=scale) |
| 10 | + |
| 11 | +def draw_face_detections(img, detections): |
| 12 | + """Draws bounding boxes around detected faces.""" |
| 13 | + if detections: |
| 14 | + for detection in detections: |
| 15 | + # Extract bounding box information |
| 16 | + bboxC = detection.location_data.relative_bounding_box |
| 17 | + ih, iw, _ = img.shape |
| 18 | + bbox = ( |
| 19 | + int(bboxC.xmin * iw), int(bboxC.ymin * ih), |
| 20 | + int(bboxC.width * iw), int(bboxC.height * ih) |
| 21 | + ) |
| 22 | + # Draw the bounding box |
| 23 | + cv2.rectangle(img, bbox, (17, 219, 13), 2) |
| 24 | + |
| 25 | +def main(video_path): |
| 26 | + # Initialize video capture |
| 27 | + cap = cv2.VideoCapture(video_path) |
| 28 | + if not cap.isOpened(): |
| 29 | + print("Error: Unable to open video file") |
| 30 | + return |
| 31 | + |
| 32 | + # Mediapipe Face Detection setup |
| 33 | + mpFaceDetection = mp.solutions.face_detection |
| 34 | + mpDraw = mp.solutions.drawing_utils |
| 35 | + faceDetection = mpFaceDetection.FaceDetection(0.75) |
| 36 | + |
| 37 | + pTime = 0 # Previous time for FPS calculation |
| 38 | + |
| 39 | + while True: |
| 40 | + success, img = cap.read() |
| 41 | + if not success: |
| 42 | + print("Error: Can't read the video frame.") |
| 43 | + break |
| 44 | + |
| 45 | + # Resize image for better performance |
| 46 | + img = resize_image(img) |
| 47 | + |
| 48 | + # Convert image to RGB for face detection |
| 49 | + imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) |
| 50 | + result = faceDetection.process(imgRGB) |
| 51 | + |
| 52 | + # Draw face detections |
| 53 | + draw_face_detections(img, result.detections) |
| 54 | + |
| 55 | + # FPS calculation |
| 56 | + cTime = time.time() |
| 57 | + fps = 1 / (cTime - pTime) |
| 58 | + pTime = cTime |
| 59 | + |
| 60 | + # Display FPS on the video |
| 61 | + cv2.putText(img, f"FPS: {int(fps)}", (20, 70), cv2.FONT_HERSHEY_PLAIN, 3, (0, 255, 0), 2) |
| 62 | + |
| 63 | + # Show the output image |
| 64 | + cv2.imshow("Face Detection", img) |
| 65 | + |
| 66 | + # Break the loop on 'q' key press |
| 67 | + if cv2.waitKey(10) & 0xFF == ord('q'): |
| 68 | + break |
| 69 | + |
| 70 | + # Release video capture and destroy all windows |
| 71 | + cap.release() |
| 72 | + cv2.destroyAllWindows() |
| 73 | + |
| 74 | +if __name__ == "__main__": |
| 75 | + video_path = 'path/to/your/video.mp4' # Update with the actual video path |
| 76 | + main(video_path) |
0 commit comments