To connect facial recognition to a Python database, you’ll need to follow several steps:
pip install opencv-python
Additionally, you might want to use a face recognition library like “face_recognition” to simplify the recognition process. Install it with:Copy codepip install face_recognition
Here’s a simplified code example using OpenCV and face_recognition for face recognition and SQLite for database interactions:
pythonCopy codeimport cv2
import face_recognition
import sqlite3
# Initialize the database connection
conn = sqlite3.connect('face_recognition.db')
cursor = conn.cursor()
# Load known face encodings from the database
cursor.execute("SELECT name, encoding FROM faces")
known_face_encodings = {row[0]: eval(row[1]) for row in cursor.fetchall()}
# Initialize the webcam or camera
video_capture = cv2.VideoCapture(0)
while True:
ret, frame = video_capture.read()
# Find all face locations in the frame
face_locations = face_recognition.face_locations(frame)
face_encodings = face_recognition.face_encodings(frame, face_locations)
for face_encoding in face_encodings:
# Compare the current face encoding with known faces
matches = face_recognition.compare_faces(list(known_face_encodings.values()), face_encoding)
name = "Unknown"
if True in matches:
matched_face = list(known_face_encodings.keys())[matches.index(True)]
name = matched_face
# Display the result
cv2.putText(frame, name, (50, 50), cv2.FONT_HERSHEY_PLAIN, 1, (0, 255, 0), 2)
# Display the frame
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Release the video capture and close the database connection
video_capture.release()
cv2.destroyAllWindows()
conn.close()
Please note that this is a simplified example, and in a production environment, you should consider security, scalability, and performance optimizations, depending on your specific use case and database system.