0% found this document useful (0 votes)
3 views

face recognition source code

The document outlines a face recognition voting system implemented in Python, detailing the project structure and source code for user registration, face encoding generation, voting logic, and result viewing. It includes instructions for installing necessary packages and provides sample outputs for each stage of the process, from registering a voter to displaying voting results. The system utilizes OpenCV and face_recognition libraries to capture and process facial images for secure voting.

Uploaded by

yasmeen23fathima
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

face recognition source code

The document outlines a face recognition voting system implemented in Python, detailing the project structure and source code for user registration, face encoding generation, voting logic, and result viewing. It includes instructions for installing necessary packages and provides sample outputs for each stage of the process, from registering a voter to displaying voting results. The system utilizes OpenCV and face_recognition libraries to capture and process facial images for secure voting.

Uploaded by

yasmeen23fathima
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

FACE RECOGNITION IN VOTING SYSTEM USING PYTHON

SOURCE CODE:
PROJECT STRUCTURE

face_voting_system

dataset # Stores registered user face images

db/votes.db # SQLite database

register.py # Register new voter

Vote.py # Voting logic with face recognition

Result.py # Admin view to see vote counts

train_encodings.py # Create face encodings from dataset

Requirements.txt

INSTALLING PACKAGES:

pip install opencv-python face_recognition numpy sqlite3

USER REGISTRATION (register.py)

import cv2 import os

name = input("Enter your name: ").strip() folder = f'dataset/{name}' os.makedirs(folder, exist_ok=True)

cap = cv2.VideoCapture(0)

print("Capturing face... Press 'q' to quit.")

count = 0

while True:

ret, frame = cap.read()


if not ret:

break cv2.imshow("Register - Press 's' to Save", frame)

k = cv2.waitKey(1)

if k % 256 == ord('s'):

img_path = f"{folder}/{name}_{count}.jpg"

cv2.imwrite(img_path, frame)

print(f"[INFO] Image saved: {img_path}")

count += 1 elif k % 256 == ord('q') or count >= 5:

break

cap.release()

cv2.destroyAllWindows()

GENERATE ENCODINGS (TRAIN_ENCODINGS.PY)

import face_recognition

import os

import pickle

encodings = []

names = []

for user_folder in os.listdir("dataset"):

user_path = os.path.join("dataset", user_folder)

for img_file in os.listdir(user_path):

img_path = os.path.join(user_path, img_file)

image = face_recognition.load_image_file(img_path)

face_locations = face_recognition.face_locations(image)
if face_locations:

face_encoding = face_recognition.face_encodings(image, face_locations)[0]

encodings.append(face_encoding)

names.append(user_folder)

data = {"encodings": encodings, "names": names}

with open("encodings.pkl", "wb") as f:

pickle.dump(data, f)

print("[INFO] Face encodings saved.")

VOTING SYSTEM (VOTE.PY)

import cv2

import face_recognition

import pickle

import sqlite3 from datetime

import datetime

with open("encodings.pkl", "rb") as f:

data = pickle.load(f)

conn = sqlite3.connect('db/votes.db')

cursor = conn.cursor()

cursor.execute("CREATE TABLE IF NOT EXISTS votes (name TEXT, time TEXT)")


conn.commit()

cap = cv2.VideoCapture(0)
print("[INFO] Scanning face...")

while True:

ret, frame = cap.read()

rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

boxes = face_recognition.face_locations(rgb)

encodings = face_recognition.face_encodings(rgb, boxes)

for encoding in encodings:


matches = face_recognition.compare_faces(data["encodings"],
encoding)
name = "Unknown"
if True in matches:
matchedIdx = matches.index(True)
name = data["names"][matchedIdx]

cursor.execute("SELECT * FROM votes WHERE name=?", (name,))


result = cursor.fetchone()
if result:
print(f"[WARN] {name} has already voted.")
else:
print(f"[SUCCESS] Vote recorded for {name}")
cursor.execute("INSERT INTO votes VALUES (?, ?)", (name,
datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
conn.commit()

cv2.imshow("Voting - Press 'q' to quit", frame)


if cv2.waitKey(1) & 0xFF == ord('q'):
break

cap.release()

cv2.destroyAllWindows()

conn.close()
VIEW RESULTS (RESULT.PY)

import sqlite3

conn = sqlite3.connect('db/votes.db')

cursor = conn.cursor()

cursor.execute("SELECT name, COUNT(*) as count FROM votes GROUP BY name")

results = cursor.fetchall()

print("=== Voting Results ===")

for name, count in results:

print(f"{name}: {count} vote(s)")

SAMPLE OUTPUT:

1. During Registration

Enter your name: Muhasina

Output:

• webcam opens and shows a live preview.


• press "S" to save face images (at least 5 recommended).
• Press "Q" to finish.

Console Output:

[INFO] Image saved: dataset/Muhasina/Muhasina_0.jpg

[INFO] Image saved: dataset/Muhasina/Muhasina_1.jpg


What Happens:

• Folder dataset/Muhasina/ is created.


• 5 images of your face are saved.

2.Generating Face Encodings (train_encodings.py)

[INFO] Face encodings saved.

What Happens:

• A file named encodings.pkl is created.


• It stores face embeddings and names.

3. Voting (vote.py)

Output Behavior:

• Webcam starts.
• It scans your face live.

If you are recognized and haven’t voted yet

[SUCCESS] Vote recorded for Alice.

If you already voted:

[WARN] Alice has already voted.

If you’re not recognized:

[INFO] Unknown person detected. Vote not counted.

GUI Window:

A live webcam feed with your face, showing a box if detected.


• Press Q to exit.

4. Viewing Results (result.py)

OUTPUT:

=== Voting Results ===

Alice: 1 vote(s)

Bob: 1 vote(s)

This pulls data from votes.db and counts the votes per person.

You might also like