Skip to content

Instantly share code, notes, and snippets.

@Daethyra
Created February 24, 2025 04:17
Show Gist options
  • Save Daethyra/62939a635c5a5c74249010a44e9e78fd to your computer and use it in GitHub Desktop.
Save Daethyra/62939a635c5a5c74249010a44e9e78fd to your computer and use it in GitHub Desktop.
Uses a webcam to help the user center their face and take a photo.
"""
Filename: facial_transformation.py
Description: Uses a webcam to help the user center their face and take a photo.
Author: Daethyra Carino
Date: 2025-02-23
Version: 0.1.0
License: MIT
Requires:
- package: opencv-python
- file: https://github.com/kipr/opencv/blob/master/data/haarcascades/haarcascade_frontalface_default.xml
"""
import os
import time
import cv2
# Initialize the face detector
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
# Open the webcam
cap = cv2.VideoCapture(0)
# Create a directory to save pictures
if not os.path.exists('pictures'):
os.makedirs('pictures')
# Initialize variables
face_centered = False
start_time = None
box_color = (0, 0, 255) # Red
while True:
ret, frame = cap.read()
if not ret:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
# Get frame dimensions
height, width = frame.shape[:2]
center_x = width // 2
center_y = height // 2 - height // 8 # Raise the center point
box_size = min(width, height) // 3
# Calculate bounding box coordinates
top_left = (center_x - box_size // 2, center_y - box_size // 2)
bottom_right = (center_x + box_size // 2, center_y + box_size // 2)
# Create a copy of the frame for display
display_frame = frame.copy()
# Draw bounding box on the display frame
cv2.rectangle(display_frame, top_left, bottom_right, box_color, 2)
for (x, y, w, h) in faces:
face_center_x = x + w // 2
face_center_y = y + h // 2
if (abs(face_center_x - center_x) < box_size // 4 and
abs(face_center_y - center_y) < box_size // 4):
box_color = (0, 255, 0) # Green
if not face_centered:
face_centered = True
start_time = time.time()
else:
box_color = (0, 0, 255) # Red
face_centered = False
start_time = None
cv2.imshow('Webcam', display_frame)
if face_centered and start_time and time.time() - start_time >= 3:
# Save the picture without the bounding box
timestamp = time.strftime("%Y%m%d-%H%M%S")
filename = f'pictures/capture_{timestamp}.jpg'
cv2.imwrite(filename, frame) # Save the original frame without the box
print(f"Picture saved as {filename}")
break
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment