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 = [Link](0)
#
# # For an RTSP stream
# camera = [Link]("rtsp://your_ip_address:port/video")
#
# # For an HTTP stream (if supported by your camera)
# camera = [Link]("[Link]
# 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 = [Link](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([Link]())
current_date = [Link]().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 = [Link](file)
[Link](['Name', 'Timestamp']) # Write the header
for entry in entries:
[Link]([entry['name'], entry['timestamp']])
# Create the capture directory if it doesn't exist
if not [Link](capture_image_directory):
[Link](capture_image_directory)
def capture_unknown_face(frame):
current_time = [Link]()
image_filename = f"{capture_image_directory}{current_time}.jpg"
[Link](image_filename, frame)
print(f"Image of an unknown person saved as {image_filename}")
def mark_entry(name):
current_time = [Link]()
# 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': [Link]().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 = [Link]()
if not success:
break
frame = [Link](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 = [Link](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):
[Link](frame, (left, top), (right, bottom), (0, 0, 255), 2)
[Link](frame, (left, bottom - 35), (right, bottom), (0, 0, 255),
[Link])
font = cv2.FONT_HERSHEY_DUPLEX
[Link](frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255,
255), 1)
ret, buffer = [Link]('.jpg', frame, [int(cv2.IMWRITE_JPEG_QUALITY),
50])
frame = [Link]()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
@[Link]('/add_entry', methods=['POST'])
def add_entry():
name = [Link]('name')
image_path = [Link]('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 = [Link](csvfile)
[Link]({'Name': name, 'Image_Path': image_path})
return redirect('/')
@[Link]('/')
def index():
return render_template('[Link]', recognized_entries=recognized_entries)
@[Link]('/get_entries', methods=['GET'])
def get_entries():
# You may need to filter and format your entries as needed
return jsonify(recognized_entries)
@[Link]('/new')
def new():
return render_template('[Link]')
@[Link]('/video_feed')
def video_feed():
return Response(gen_frames(), mimetype='multipart/x-mixed-replace;
boundary=frame')
if _name_ == '_main_':
[Link](host='[Link]', debug=True, port=5000)