|
| 1 | +import os |
| 2 | +import cv2 |
| 3 | +import dlib |
| 4 | +from imutils import face_utils |
| 5 | +import colorlog |
| 6 | + |
| 7 | +# Configure colorlog for logging messages with colors |
| 8 | +logger = colorlog.getLogger() |
| 9 | +# Change to INFO if needed |
| 10 | +logger.setLevel(colorlog.DEBUG) |
| 11 | + |
| 12 | +handler = colorlog.StreamHandler() |
| 13 | +formatter = colorlog.ColoredFormatter( |
| 14 | + "%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s", |
| 15 | + datefmt=None, |
| 16 | + reset=True, |
| 17 | + log_colors={ |
| 18 | + "DEBUG": "cyan", |
| 19 | + "INFO": "green", |
| 20 | + "WARNING": "yellow", |
| 21 | + "ERROR": "red", |
| 22 | + "CRITICAL": "red", |
| 23 | + }, |
| 24 | +) |
| 25 | +handler.setFormatter(formatter) |
| 26 | +logger.addHandler(handler) |
| 27 | + |
| 28 | +# Load the detector and predictor |
| 29 | +detector = dlib.get_frontal_face_detector() |
| 30 | +predictor = dlib.shape_predictor("sp68fl.dat") |
| 31 | + |
| 32 | + |
| 33 | +def detect_and_draw_landmarks(image, loop): |
| 34 | + colorlog.debug(f"Starting loop {loop}...") |
| 35 | + gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) |
| 36 | + colorlog.debug("Converted image to grayscale") |
| 37 | + rects = detector(gray, 1) |
| 38 | + colorlog.debug(f"Detected {len(rects)} faces") |
| 39 | + |
| 40 | + try: |
| 41 | + for i, rect in enumerate(rects): |
| 42 | + colorlog.debug(f"Processing face {i + 1}") |
| 43 | + shape = predictor(gray, rect) |
| 44 | + shape = face_utils.shape_to_np(shape) |
| 45 | + colorlog.debug("Extracted facial landmarks") |
| 46 | + |
| 47 | + # Calculate the size of the face region as a proxy for certainty |
| 48 | + face_size = max(rect.width(), rect.height()) |
| 49 | + colorlog.debug(f"Face size: {face_size}") |
| 50 | + |
| 51 | + # Arbitrary threshold for high certainty |
| 52 | + if face_size > 300: |
| 53 | + # Green for high certainty |
| 54 | + color = (0, 255, 0) |
| 55 | + colorlog.debug("High certainty with plotting") |
| 56 | + # Arbitrary threshold for medium certainty |
| 57 | + elif 180 < face_size <= 300: |
| 58 | + # Yellow for medium certainty |
| 59 | + color = (0, 255, 255) |
| 60 | + colorlog.debug("Medium certainty with plotting") |
| 61 | + else: |
| 62 | + # Red for low certainty |
| 63 | + color = (0, 0, 255) |
| 64 | + colorlog.debug("Low certainty with plotting") |
| 65 | + |
| 66 | + # Extract facial landmarks |
| 67 | + colorlog.debug("Extracting facial landmarks") |
| 68 | + left_eye = shape[36:42] |
| 69 | + right_eye = shape[42:48] |
| 70 | + nose = shape[30:36] |
| 71 | + mouth = shape[48:68] |
| 72 | + |
| 73 | + # Draw dots on facial landmarks for display |
| 74 | + colorlog.debug("Plotting dots onto facial landmarks") |
| 75 | + for point in left_eye: |
| 76 | + cv2.circle(image, tuple(point), 2, color, -1) |
| 77 | + for point in right_eye: |
| 78 | + cv2.circle(image, tuple(point), 2, color, -1) |
| 79 | + for point in nose: |
| 80 | + cv2.circle(image, tuple(point), 2, color, -1) |
| 81 | + for point in mouth: |
| 82 | + cv2.circle(image, tuple(point), 2, color, -1) |
| 83 | + except Exception as err: |
| 84 | + colorlog.error(f"Error processing face: {err}") |
| 85 | + |
| 86 | + colorlog.debug(f"Finished detection and plotting - LOOP {loop}") |
| 87 | + return image.copy() |
| 88 | + |
| 89 | + |
| 90 | +def capture(): |
| 91 | + loop = 0 |
| 92 | + colorlog.info("Starting video capture...") |
| 93 | + try: |
| 94 | + while True: |
| 95 | + loop += 1 |
| 96 | + ret, frame = cap.read() |
| 97 | + if not ret: |
| 98 | + colorlog.error("Can't receive frame (stream end?). Exiting ...") |
| 99 | + break |
| 100 | + |
| 101 | + # Create a copy of the frame for displaying with dots |
| 102 | + display_frame = detect_and_draw_landmarks(frame.copy(), loop) |
| 103 | + |
| 104 | + # Display the frame with dots |
| 105 | + cv2.imshow("Face Detection", display_frame) |
| 106 | + |
| 107 | + key = cv2.waitKey(1) & 0xFF |
| 108 | + colorlog.info("Press 'c' to save the image.") |
| 109 | + if key == ord("c"): # Press 'c' to continue/save the image |
| 110 | + files = os.listdir("known_faces") |
| 111 | + number = sum( |
| 112 | + [1 for f in files if os.path.isfile(os.path.join("known_faces", f))] |
| 113 | + ) |
| 114 | + # Save the original frame without modifications |
| 115 | + cv2.imwrite(f"known_faces/face_{number}.jpg", frame) |
| 116 | + colorlog.info("Image saved.") |
| 117 | + |
| 118 | + break |
| 119 | + |
| 120 | + # Add debug print statements for easy debugging |
| 121 | + colorlog.info("Video capture completed.") |
| 122 | + colorlog.debug(f"Loop number: {loop}") |
| 123 | + colorlog.debug(f"Key pressed: {chr(key)}") |
| 124 | + except Exception as e: |
| 125 | + colorlog.error(f"An error occurred: {e}") |
| 126 | + |
| 127 | + |
| 128 | +# Initialize the camera |
| 129 | +try: |
| 130 | + if not os.path.exists("known_faces"): |
| 131 | + os.makedirs("known_faces") |
| 132 | + cap = cv2.VideoCapture(0) |
| 133 | + capture() |
| 134 | + cap.release() |
| 135 | + cv2.destroyAllWindows() |
| 136 | + colorlog.info("Program completed.") |
| 137 | +except Exception as e: |
| 138 | + colorlog.error(f"An error occurred: {e}") |
0 commit comments