0% found this document useful (0 votes)
4 views4 pages

Code

This document outlines a Flask application that utilizes OpenCV and face recognition to identify known faces from a camera feed. It captures unknown faces, saves recognized entries to a CSV file, and allows users to add new known faces through a web interface. The application includes features for video streaming, entry logging, and managing known face data from a CSV file.

Uploaded by

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

Code

This document outlines a Flask application that utilizes OpenCV and face recognition to identify known faces from a camera feed. It captures unknown faces, saves recognized entries to a CSV file, and allows users to add new known faces through a web interface. The application includes features for video streaming, entry logging, and managing known face data from a CSV file.

Uploaded by

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

import os

from datetime import datetime


import csv
from urllib import request

from flask import Flask, render_template, Response, jsonify, url_for, request,


redirect

import cv2
import time
import face_recognition

from main import save_to_csv

app = Flask(_name_)
camera = cv2.VideoCapture(0)
#
# # For an RTSP stream
# camera = cv2.VideoCapture("rtsp://your_ip_address:port/video")
#
# # For an HTTP stream (if supported by your camera)
# camera = cv2.VideoCapture("http://your_ip_address:port/video")

# Create a list of known face data as tuples: (name, file_path)


known_faces = []
# Load known faces from the CSV file with 'latin-1' encoding
with open('Data/known_faces.csv', newline='', encoding='latin-1') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
name = row['Name']
image_path = row['Image_Path']
known_faces.append((name, image_path))

# Initialize empty lists to store face encodings and names


known_face_encodings = []
known_face_names = []

# Load known faces and encodings using a loop


for name, file_path in known_faces:
image = face_recognition.load_image_file(file_path)
encoding = face_recognition.face_encodings(image)[0]

known_face_encodings.append(encoding)
known_face_names.append(name)

# Initialize a list to store recognized entries


recognized_entries = []

# Define a cooldown period in seconds


cooldown_period = 60 # Adjust this value as needed

# Dictionary to store the last entry timestamp for each recognized face
last_entry_timestamps = {}

# Define the directory where you want to save the CSV files
csv_directory = 'CSV_FILES/'
capture_image_directory = 'captured_Unknown_images/'
# ...

# Function to save recognized entries to a CSV file


def save_to_csv(entries):
# Create the CSV filename with the current date and timestamp
current_timestamp = int(time.time())
current_date = datetime.now().strftime('%Y-%m-%d')
csv_file =
f'{csv_directory}recognized_entries_{current_date}_{current_timestamp}.csv'

# Write the entries to the CSV file


with open(csv_file, mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Name', 'Timestamp']) # Write the header
for entry in entries:
writer.writerow([entry['name'], entry['timestamp']])

# Create the capture directory if it doesn't exist


if not os.path.exists(capture_image_directory):
os.makedirs(capture_image_directory)

def capture_unknown_face(frame):
current_time = time.time()
image_filename = f"{capture_image_directory}{current_time}.jpg"
cv2.imwrite(image_filename, frame)
print(f"Image of an unknown person saved as {image_filename}")

def mark_entry(name):
current_time = time.time()

# Check if this face has an entry timestamp and if enough time has passed
if name in last_entry_timestamps and current_time - last_entry_timestamps[name]
< cooldown_period:
print(f"Face {name} was recognized too soon. Skipping entry.")
return

# Add a new entry to the recognized_entries list


recognized_entries.append({
'name': name,
'timestamp': datetime.now().strftime("%d/%m/%y %I:%M %p"), # You can
replace this with the actual timestamp
})

# Update the last entry timestamp for this face


last_entry_timestamps[name] = current_time

# Save recognized_entries to the CSV file


save_to_csv(recognized_entries)

print(recognized_entries)

def gen_frames():
while True:
success, frame = camera.read()
if not success:
break

frame = cv2.resize(frame, (640, 480))


# Face detection and recognition
faces = face_recognition.face_locations(frame)
face_encodings = face_recognition.face_encodings(frame, faces)

face_names = []
for face_encoding in face_encodings:
# Use a threshold to recognize known faces
matches = face_recognition.compare_faces(known_face_encodings,
face_encoding, tolerance=0.6)
name = "Unknown"

if True in matches:
first_match_index = matches.index(True)
name = known_face_names[first_match_index]

# Mark the entry when a face is recognized


mark_entry(name)
else:
capture_unknown_face(frame)

face_names.append(name)

# Drawing rectangles and labels


for (top, right, bottom, left), name in zip(faces, face_names):
cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255),
cv2.FILLED)
font = cv2.FONT_HERSHEY_DUPLEX
cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255,
255), 1)

ret, buffer = cv2.imencode('.jpg', frame, [int(cv2.IMWRITE_JPEG_QUALITY),


50])
frame = buffer.tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')

@app.route('/add_entry', methods=['POST'])
def add_entry():
name = request.form.get('name')
image_path = request.form.get('image_path')

# Validate and add the new entry to the list of known_faces


if name and image_path:
known_faces.append((name, image_path))

# Update known_face_encodings and known_face_names


image = face_recognition.load_image_file(image_path)
encoding = face_recognition.face_encodings(image)[0]
known_face_encodings.append(encoding)
known_face_names.append(name)

# Save the updated known_faces list to the CSV file


with open('Data/known_faces.csv', mode='a', newline='', encoding='latin-1')
as csvfile:
writer = csv.writer(csvfile)
writer.writerow({'Name': name, 'Image_Path': image_path})

return redirect('/')

@app.route('/')
def index():
return render_template('index.html', recognized_entries=recognized_entries)

@app.route('/get_entries', methods=['GET'])
def get_entries():
# You may need to filter and format your entries as needed
return jsonify(recognized_entries)

@app.route('/new')
def new():
return render_template('new.html')

@app.route('/video_feed')
def video_feed():
return Response(gen_frames(), mimetype='multipart/x-mixed-replace;
boundary=frame')

if _name_ == '_main_':
app.run(host='0.0.0.0', debug=True, port=5000)

You might also like