Last active
June 13, 2025 16:14
-
-
Save cptangry/389d8cbcac48eb0caafefdaa56f18efd to your computer and use it in GitHub Desktop.
face detection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import cv2 | |
| import sqlite3 | |
| import sys | |
| from datetime import datetime | |
| # Add the directory containing cascade.xml to system path if not already added | |
| sys.path.append('.') | |
| face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_default.xml') | |
| def main(): | |
| # Initialize database connection | |
| conn = sqlite3.connect('face_detection.db') | |
| cursor = conn.cursor() | |
| # Create table if it doesn't exist | |
| cursor.execute('''CREATE TABLE face_data ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| person_id TEXT NOT NULL, | |
| name TEXT NOT NULL, | |
| count INTEGER DEFAULT 0, | |
| timestamp DATETIME DEFAULT CURRENT_TIMESTAMP)''') | |
| # Initialize known_faces set to keep track of unique individuals detected | |
| known_faces = set() | |
| current_faces = [] | |
| # Start video capture from the first webcam | |
| cap = cv2.VideoCapture(0) | |
| try: | |
| while True: | |
| ret, frame = cap.read() | |
| if not ret: | |
| break | |
| # Convert frame to grayscale for face detection | |
| gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) | |
| faces = face_cascade.detectMultiScale(gray_frame, 1.3, 4) | |
| current_faces.clear() | |
| new_faces = [] | |
| # For each face found: | |
| for (x, y, w, h) in faces: | |
| # Check if the face's coordinates indicate it hasn't been seen before | |
| if ((x > 0 and x - w < min_x_diff or | |
| y > 0 and y - h < min_y_diff) and | |
| (x + w < max_x or y + h < max_y)): | |
| # Calculate face's position as a tuple in the frame | |
| face_position = (x, y, w, h) | |
| current_faces.append(face_position) | |
| # Remove faces that have been seen before from current_faces | |
| for face in faces: | |
| if any(any((f[0] - face[0] < 5 or f[1] - face[1] < 5) | |
| for f in known_faces) | |
| for face in current_faces): | |
| current_faces.remove(face) | |
| # Update the set of known faces with new faces detected | |
| known_faces.update(current_faces) | |
| print(f"Detected {len(known_faces)} unique faces") | |
| if len(known_faces) > 0: | |
| cursor.execute('''INSERT INTO face_data | |
| (person_id, name, count, timestamp) | |
| VALUES (?, ?, ?, ?)''', | |
| [name1, name2, len(known_faces), datetime.now()]) | |
| conn.commit() | |
| except Exception as e: | |
| print(f"An error occurred: {str(e)}") | |
| # Release resources | |
| cap.release() | |
| cursor.close() | |
| conn.close() | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment