main
dev2 siliconpin 2024-06-23 18:30:54 +00:00
parent 848295ae5f
commit af1000ca39
10 changed files with 68 additions and 528 deletions

2
.gitignore vendored
View File

@ -1,2 +1,4 @@
lib lib
lib64 lib64
uploads
students_data.pkl

123
app.py
View File

@ -1,77 +1,86 @@
from flask import Flask, request, jsonify, render_template, send_from_directory, make_response from flask import Flask, request, jsonify
from flask_cors import CORS
import face_recognition
import os import os
import numpy as np import face_recognition
import pickle import pickle
from werkzeug.utils import secure_filename
from time import time
app = Flask(__name__) app = Flask(__name__)
CORS(app) app.config['UPLOAD_FOLDER'] = 'uploads/'
#pip install Flask flask-cors face_recognition app.config['STUDENT_DATA_FILE'] = 'students_data.pkl'
# Directory to save student images and encodings if not os.path.exists(app.config['UPLOAD_FOLDER']):
STUDENT_IMAGES_DIR = 'student_images' os.makedirs(app.config['UPLOAD_FOLDER'])
STUDENT_ENCODINGS_FILE = 'student_encodings.pkl'
# Ensure the directory exists # Load or initialize student data
os.makedirs(STUDENT_IMAGES_DIR, exist_ok=True) if os.path.exists(app.config['STUDENT_DATA_FILE']):
with open(app.config['STUDENT_DATA_FILE'], 'rb') as f:
# Load existing encodings if available students_db = pickle.load(f)
if os.path.exists(STUDENT_ENCODINGS_FILE):
with open(STUDENT_ENCODINGS_FILE, 'rb') as f:
student_encodings = pickle.load(f)
else: else:
student_encodings = {} students_db = {}
@app.route('/upload', methods=['POST']) def save_student_data():
def upload_images(): with open(app.config['STUDENT_DATA_FILE'], 'wb') as f:
student_id = request.form.get('student_id') pickle.dump(students_db, f)
if 'images' not in request.files or not student_id:
return jsonify({"error": "No images or student ID provided"}), 400
images = request.files.getlist('images') @app.route('/upl', methods=['POST'])
encodings = [] def upload_image():
if 'face' not in request.files or 'student_id' not in request.form:
return jsonify({'error': 'Image or student_id not provided'}), 400
for image in images: image = request.files['face']
student_id = request.form['student_id']
image_path = os.path.join(STUDENT_IMAGES_DIR, f"{student_id}_{image.filename}") timestamp = int(time())
image.save(image_path) filename = secure_filename(f"{timestamp}.jpg")
student_folder = os.path.join(app.config['UPLOAD_FOLDER'], student_id)
if not os.path.exists(student_folder):
os.makedirs(student_folder)
filepath = os.path.join(student_folder, filename)
image.save(filepath)
# Load the image and get the face encodings # Load the image file into a numpy array
img = face_recognition.load_image_file(image_path) image_array = face_recognition.load_image_file(filepath)
img_encodings = face_recognition.face_encodings(img) # Get the face encoding for the image
face_encodings = face_recognition.face_encodings(image_array)
if img_encodings: if len(face_encodings) > 0:
encodings.append(img_encodings[0]) # Assuming the first face found in the image is the correct one
students_db[student_id] = face_encodings[0]
if encodings: save_student_data()
student_encodings[student_id] = np.mean(encodings, axis=0) return jsonify({'message': 'Image uploaded and student registered successfully', 'student_id': student_id}), 200
# Save the encodings to file
with open(STUDENT_ENCODINGS_FILE, 'wb') as f:
pickle.dump(student_encodings, f)
return jsonify({"message": "Images uploaded and processed successfully"}), 200
else: else:
return jsonify({"error": "No faces found in the uploaded images"}), 400 return jsonify({'error': 'No faces found in the image'}), 400
@app.route('/recognize', methods=['POST']) @app.route('/rec', methods=['POST'])
def recognize(): def recognize_image():
if 'image' not in request.files: if 'face' not in request.files:
return jsonify({"error": "No image provided"}), 400 return jsonify({'error': 'Image not provided'}), 400
image = request.files['image'] image = request.files['face']
img = face_recognition.load_image_file(image) # Load the uploaded image file into a numpy array
img_encodings = face_recognition.face_encodings(img) unknown_image = face_recognition.load_image_file(image)
# Get the face encodings for the uploaded image
unknown_encodings = face_recognition.face_encodings(unknown_image)
if img_encodings: if len(unknown_encodings) > 0:
img_encoding = img_encodings[0] unknown_encoding = unknown_encodings[0]
distances = {student_id: np.linalg.norm(encoding - img_encoding) for student_id, encoding in student_encodings.items()} best_match_id = None
student_id = min(distances, key=distances.get) best_match_score = None
return jsonify({"student_id": student_id}), 200 for student_id, known_encoding in students_db.items():
else: # Calculate the distance between the known encoding and the uploaded image encoding
return jsonify({"error": "No face found in the uploaded image"}), 400 distance = face_recognition.face_distance([known_encoding], unknown_encoding)[0]
# Convert distance to accuracy score (the closer the distance, the higher the accuracy)
accuracy_score = (1 - distance) * 100
if best_match_score is None or accuracy_score > best_match_score:
best_match_id = student_id
best_match_score = accuracy_score
if best_match_id:
return jsonify({'student_id': best_match_id, 'accuracy_score': best_match_score}), 200
return jsonify({'error': 'Student not recognized'}), 404
if __name__ == '__main__': if __name__ == '__main__':
app.run(debug=True, host="0.0.0.0", port=5005) app.run(debug=True, host="0.0.0.0", port=5005)

80
app2.py
View File

@ -1,80 +0,0 @@
from flask import Flask, request, jsonify, render_template, send_from_directory, make_response
from flask_restful import Api, Resource
import os
import face_recognition
from werkzeug.utils import secure_filename
from PIL import Image
import numpy as np
app = Flask(__name__)
api = Api(app)
UPLOAD_FOLDER = 'upload'
if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
# Helper function to save image
def save_image(image, roll_number):
roll_number_folder = os.path.join(app.config['UPLOAD_FOLDER'], roll_number)
if not os.path.exists(roll_number_folder):
os.makedirs(roll_number_folder)
image_count = len(os.listdir(roll_number_folder)) + 1
image_path = os.path.join(roll_number_folder, f"{image_count}.jpg")
image.save(image_path)
return image_path
# Helper function to load known faces
def load_known_faces():
known_faces = []
known_roll_numbers = []
for roll_number in os.listdir(app.config['UPLOAD_FOLDER']):
roll_number_folder = os.path.join(app.config['UPLOAD_FOLDER'], roll_number)
for filename in os.listdir(roll_number_folder):
image_path = os.path.join(roll_number_folder, filename)
image = face_recognition.load_image_file(image_path)
encodings = face_recognition.face_encodings(image)
if encodings:
known_faces.append(encodings[0])
known_roll_numbers.append(roll_number)
return known_faces, known_roll_numbers
class UploadImage(Resource):
def post(self):
roll_number = request.form['roll_number']
if 'image' not in request.files:
return jsonify({"error": "No image provided"}), 400
image = request.files['image']
filename = secure_filename(image.filename)
image = Image.open(image)
image_path = save_image(image, roll_number)
return jsonify({"message": f"Image saved as {image_path}"}), 200
class RecognizeStudent(Resource):
def post(self):
if 'image' not in request.files:
return jsonify({"error": "No image provided"}), 400
image = request.files['image']
filename = secure_filename(image.filename)
image = face_recognition.load_image_file(image)
unknown_encodings = face_recognition.face_encodings(image)
if not unknown_encodings:
return jsonify({"error": "No faces found in the image"}), 400
unknown_encoding = unknown_encodings[0]
known_faces, known_roll_numbers = load_known_faces()
results = face_recognition.compare_faces(known_faces, unknown_encoding)
if True in results:
matched_index = results.index(True)
roll_number = known_roll_numbers[matched_index]
return jsonify({"roll_number": roll_number}), 200
else:
return jsonify({"error": "No matching student found"}), 404
api.add_resource(UploadImage, '/upload')
api.add_resource(RecognizeStudent, '/recognize')
if __name__ == '__main__':
app.run(debug=True, host="0.0.0.0", port=5005)

84
app3.py
View File

@ -1,84 +0,0 @@
from flask import Flask, request, jsonify, render_template, send_from_directory, make_response
from flask_restful import Api, Resource
import os
import face_recognition
from werkzeug.utils import secure_filename
from PIL import Image
import numpy as np
app = Flask(__name__)
api = Api(app)
UPLOAD_FOLDER = 'upload'
if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
# Helper function to save image
def save_image(image, roll_number):
roll_number_folder = os.path.join(app.config['UPLOAD_FOLDER'], roll_number)
if not os.path.exists(roll_number_folder):
os.makedirs(roll_number_folder)
image_count = len(os.listdir(roll_number_folder)) + 1
image_path = os.path.join(roll_number_folder, f"{image_count}.jpg")
image.save(image_path)
return image_path
# Helper function to load known faces
def load_known_faces():
known_faces = []
known_roll_numbers = []
for roll_number in os.listdir(app.config['UPLOAD_FOLDER']):
roll_number_folder = os.path.join(app.config['UPLOAD_FOLDER'], roll_number)
for filename in os.listdir(roll_number_folder):
image_path = os.path.join(roll_number_folder, filename)
image = face_recognition.load_image_file(image_path)
encodings = face_recognition.face_encodings(image)
if encodings:
known_faces.append(encodings[0])
known_roll_numbers.append(roll_number)
return known_faces, known_roll_numbers
@app.route('/')
def index():
return render_template('./upload.html')
class UploadImage(Resource):
def post(self):
roll_number = request.form['roll_number']
if 'image' not in request.files:
return jsonify({"error": "No image provided"}), 400
image = request.files['image']
filename = secure_filename(image.filename)
image = Image.open(image)
image_path = save_image(image, roll_number)
return jsonify({"message": f"Image saved as {image_path}"}), 200
class RecognizeStudent(Resource):
def post(self):
if 'image' not in request.files:
return jsonify({"error": "No image provided"}), 400
image = request.files['image']
filename = secure_filename(image.filename)
image = face_recognition.load_image_file(image)
unknown_encodings = face_recognition.face_encodings(image)
if not unknown_encodings:
return jsonify({"error": "No faces found in the image"}), 400
unknown_encoding = unknown_encodings[0]
known_faces, known_roll_numbers = load_known_faces()
results = face_recognition.compare_faces(known_faces, unknown_encoding)
if True in results:
matched_index = results.index(True)
roll_number = known_roll_numbers[matched_index]
return jsonify({"roll_number": roll_number}), 200
else:
return jsonify({"error": "No matching student found"}), 404
api.add_resource(UploadImage, '/upload')
api.add_resource(RecognizeStudent, '/recognize')
if __name__ == '__main__':
app.run(debug=True, host="0.0.0.0", port=5005)

93
app4.py
View File

@ -1,93 +0,0 @@
import os
from flask import Flask, request, jsonify
import face_recognition
import pickle
from PIL import Image
import numpy as np
app = Flask(__name__)
UPLOAD_FOLDER = 'student_roll/uploads/'
FACE_DATA_FOLDER = 'student_roll/face_data/'
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
os.makedirs(FACE_DATA_FOLDER, exist_ok=True)
def convert_image_to_8bit_rgb(image_path):
with Image.open(image_path) as img:
if img.mode != 'RGB':
img = img.convert('RGB')
img = img.convert('RGB') # Ensure conversion to 8-bit per channel
img_array = np.array(img)
return img_array
@app.route('/upload', methods=['POST'])
def upload_image():
if 'image' not in request.files:
return jsonify({"error": "No image part in the request"}), 400
file = request.files['image']
if file.filename == '':
return jsonify({"error": "No selected file"}), 400
student_roll = request.form.get('student_roll')
if not student_roll:
return jsonify({"error": "Student roll number is required"}), 400
file_path = os.path.join(UPLOAD_FOLDER, f"{student_roll}.jpg")
file.save(file_path)
try:
# Convert image to 8-bit RGB if necessary
image = convert_image_to_8bit_rgb(file_path)
face_encodings = face_recognition.face_encodings(image)
if not face_encodings:
return jsonify({"error": "No face found in the image"}), 400
face_data_path = os.path.join(FACE_DATA_FOLDER, f"{student_roll}.pkl")
with open(face_data_path, 'wb') as f:
pickle.dump(face_encodings[0], f)
return jsonify({"message": "Image and face data uploaded successfully"}), 200
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/recognize_student', methods=['POST'])
def recognize_student():
if 'image' not in request.files:
return jsonify({"error": "No image part in the request"}), 400
file = request.files['image']
if file.filename == '':
return jsonify({"error": "No selected file"}), 400
file_path = os.path.join(UPLOAD_FOLDER, "temp.jpg")
file.save(file_path)
try:
# Convert image to 8-bit RGB if necessary
image = convert_image_to_8bit_rgb(file_path)
face_encodings = face_recognition.face_encodings(image)
if not face_encodings:
return jsonify({"error": "No face found in the image"}), 400
uploaded_face_encoding = face_encodings[0]
# Load all stored face data
for face_data_file in os.listdir(FACE_DATA_FOLDER):
with open(os.path.join(FACE_DATA_FOLDER, face_data_file), 'rb') as f:
known_face_encoding = pickle.load(f)
matches = face_recognition.compare_faces([known_face_encoding], uploaded_face_encoding)
if matches[0]:
student_roll = os.path.splitext(face_data_file)[0]
return jsonify({"student_roll": student_roll}), 200
return jsonify({"error": "No matching student found"}), 404
except Exception as e:
return jsonify({"error": str(e)}), 500
if __name__ == '__main__':
app.run(debug=True, host="0.0.0.0", port=5005)

81
app5.py
View File

@ -1,81 +0,0 @@
from flask import Flask, request, jsonify
import os
import face_recognition
import pickle
from werkzeug.utils import secure_filename
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads/'
app.config['STUDENT_DATA_FILE'] = 'students_data.pkl'
if not os.path.exists(app.config['UPLOAD_FOLDER']):
os.makedirs(app.config['UPLOAD_FOLDER'])
# Load or initialize student data
if os.path.exists(app.config['STUDENT_DATA_FILE']):
with open(app.config['STUDENT_DATA_FILE'], 'rb') as f:
students_db = pickle.load(f)
else:
students_db = {}
def save_student_data():
with open(app.config['STUDENT_DATA_FILE'], 'wb') as f:
pickle.dump(students_db, f)
@app.route('/upload', methods=['POST'])
def upload_image():
if 'image' not in request.files or 'student_id' not in request.form:
return jsonify({'error': 'Image or student_id not provided'}), 400
image = request.files['image']
student_id = request.form['student_id']
filename = secure_filename(f"{student_id}_{image.filename}")
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
image.save(filepath)
# Load the image file into a numpy array
image = face_recognition.load_image_file(filepath)
# Get the face encoding for the image
face_encodings = face_recognition.face_encodings(image)
if len(face_encodings) > 0:
# Assuming the first face found in the image is the correct one
students_db[student_id] = face_encodings[0]
save_student_data()
return jsonify({'message': 'Image uploaded and student registered successfully', 'student_id': student_id}), 200
else:
return jsonify({'error': 'No faces found in the image'}), 400
@app.route('/recognize_image', methods=['POST'])
def recognize_image():
if 'image' not in request.files:
return jsonify({'error': 'Image not provided'}), 400
image = request.files['image']
# Load the uploaded image file into a numpy array
unknown_image = face_recognition.load_image_file(image)
# Get the face encodings for the uploaded image
unknown_encodings = face_recognition.face_encodings(unknown_image)
if len(unknown_encodings) > 0:
unknown_encoding = unknown_encodings[0]
best_match_id = None
best_match_score = None
for student_id, known_encoding in students_db.items():
# Calculate the distance between the known encoding and the uploaded image encoding
distance = face_recognition.face_distance([known_encoding], unknown_encoding)[0]
# Convert distance to accuracy score (the closer the distance, the higher the accuracy)
accuracy_score = (1 - distance) * 100
if best_match_score is None or accuracy_score > best_match_score:
best_match_id = student_id
best_match_score = accuracy_score
if best_match_id:
return jsonify({'student_id': best_match_id, 'accuracy_score': best_match_score}), 200
return jsonify({'error': 'Student not recognized'}), 404
if __name__ == '__main__':
app.run(debug=True, host="0.0.0.0", port=5005)

86
app6.py
View File

@ -1,86 +0,0 @@
from flask import Flask, request, jsonify
import os
import face_recognition
import pickle
from werkzeug.utils import secure_filename
from time import time
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads/'
app.config['STUDENT_DATA_FILE'] = 'students_data.pkl'
if not os.path.exists(app.config['UPLOAD_FOLDER']):
os.makedirs(app.config['UPLOAD_FOLDER'])
# Load or initialize student data
if os.path.exists(app.config['STUDENT_DATA_FILE']):
with open(app.config['STUDENT_DATA_FILE'], 'rb') as f:
students_db = pickle.load(f)
else:
students_db = {}
def save_student_data():
with open(app.config['STUDENT_DATA_FILE'], 'wb') as f:
pickle.dump(students_db, f)
@app.route('/upl', methods=['POST'])
def upload_image():
if 'face' not in request.files or 'student_id' not in request.form:
return jsonify({'error': 'Image or student_id not provided'}), 400
image = request.files['face']
student_id = request.form['student_id']
timestamp = int(time())
filename = secure_filename(f"{timestamp}.jpg")
student_folder = os.path.join(app.config['UPLOAD_FOLDER'], student_id)
if not os.path.exists(student_folder):
os.makedirs(student_folder)
filepath = os.path.join(student_folder, filename)
image.save(filepath)
# Load the image file into a numpy array
image_array = face_recognition.load_image_file(filepath)
# Get the face encoding for the image
face_encodings = face_recognition.face_encodings(image_array)
if len(face_encodings) > 0:
# Assuming the first face found in the image is the correct one
students_db[student_id] = face_encodings[0]
save_student_data()
return jsonify({'message': 'Image uploaded and student registered successfully', 'student_id': student_id}), 200
else:
return jsonify({'error': 'No faces found in the image'}), 400
@app.route('/rec', methods=['POST'])
def recognize_image():
if 'image' not in request.files:
return jsonify({'error': 'Image not provided'}), 400
image = request.files['image']
# Load the uploaded image file into a numpy array
unknown_image = face_recognition.load_image_file(image)
# Get the face encodings for the uploaded image
unknown_encodings = face_recognition.face_encodings(unknown_image)
if len(unknown_encodings) > 0:
unknown_encoding = unknown_encodings[0]
best_match_id = None
best_match_score = None
for student_id, known_encoding in students_db.items():
# Calculate the distance between the known encoding and the uploaded image encoding
distance = face_recognition.face_distance([known_encoding], unknown_encoding)[0]
# Convert distance to accuracy score (the closer the distance, the higher the accuracy)
accuracy_score = (1 - distance) * 100
if best_match_score is None or accuracy_score > best_match_score:
best_match_id = student_id
best_match_score = accuracy_score
if best_match_id:
return jsonify({'student_id': best_match_id, 'accuracy_score': best_match_score}), 200
return jsonify({'error': 'Student not recognized'}), 404
if __name__ == '__main__':
app.run(debug=True, host="0.0.0.0", port=5005)

Binary file not shown.

View File

@ -1,18 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>Upload Student Image</title>
</head>
<body>
<h1>Upload Student Image</h1>
<form action="/upload" method="post" enctype="multipart/form-data">
<label for="roll_number">Roll Number:</label>
<input type="text" id="roll_number" name="roll_number" required>
<br><br>
<label for="image">Select image:</label>
<input type="file" id="image" name="image" accept="image/*" required>
<br><br>
<input type="submit" value="Upload">
</form>
</body>
</html>

View File

@ -1,29 +0,0 @@
from flask import Flask, render_template, request, jsonify, make_response
import os
app = Flask(__name__)
UPLOAD_FOLDER = 'uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
@app.route('/')
def upload_form():
return render_template('upload.html')
@app.route('/upload', methods=['POST'])
def upload_file():
folder_number = request.form['roll_number']
images = request.files.getlist('images[]')
folder_path = os.path.join(app.config['UPLOAD_FOLDER'], folder_number)
os.makedirs(folder_path, exist_ok=True)
for image in images:
if image.filename == '':
continue
filename = image.filename
image.save(os.path.join(folder_path, filename))
return make_response(jsonify('success'), 200)
if __name__ == '__main__':
app.run(debug=True, host="0.0.0.0", port=5005)