Facial recognition

Hello comrades, hope you re doing greate as far as python coding is concerned.
Now I’m seeking some helps for the geneus on how I can solve the isue I’m facing in my odes.


import os
import base64
import cv2
import numpy as np
from django.shortcuts import render, redirect, get_object_or_404
from django.conf import settings
from django.contrib import messages
from .models import User
import face_recognition

def registration(request):
if request.method == ‘POST’:
# Get form data
firstname = request.POST.get(‘firstname’)
lastname = request.POST.get(‘lastname’)
email = request.POST.get(‘email’)
phone = request.POST.get(‘phone’)
image_data = request.POST.get(‘image_data’)
video_file = request.FILES.get(‘video’)

        # Retrieve user data from the database
        user = get_object_or_404(User, email=email, phone=phone, firstname=firstname, lastname=lastname)

        # Save the submitted picture
        picture_folder = os.path.join(settings.MEDIA_ROOT, 'Submitted_pictures')
        os.makedirs(picture_folder, exist_ok=True)
        submitted_image_path = os.path.join(picture_folder, f'{phone}_{lastname}_submitted_image.jpg')
        if os.path.isfile(submitted_image_path):
        with open(submitted_image_path, 'wb') as f:
        print(f"Submitted image saved at {submitted_image_path}")

        # Save the retrieved picture
        picture_folder = os.path.join(settings.MEDIA_ROOT, 'Retrieved_pictures')
        os.makedirs(picture_folder, exist_ok=True)
        retrieved_image_path = os.path.join(picture_folder, f'{firstname}_{lastname}_retrieved_image.jpg')
        if os.path.isfile(retrieved_image_path):
        with open(retrieved_image_path, 'wb') as f:
        print(f"Retrieved image saved at {retrieved_image_path}")

        # Path to the directory containing existing images
        existing_images_dir = os.path.join(settings.MEDIA_ROOT, 'Retrieved_pictures')
        existing_image_paths = [os.path.join(existing_images_dir, filename) for filename in os.listdir(existing_images_dir)]
        print(f"Existing image paths: {existing_image_paths}")

        # Calculate similarity between the images
        similarity = compare_images_content(submitted_image_path, existing_image_paths)
        print(f"Image similarity: {similarity}")

        if similarity >= 0.8:
            print('\nFace recognition successful. Images match!\n')
            messages.success(request, 'Face recognition successful. Images match!')

            # Save the submitted video
            print('\n Saving submitted video\n')
            video_folder = os.path.join(settings.MEDIA_ROOT, 'video')
            os.makedirs(video_folder, exist_ok=True)
            submitted_video_path = os.path.join(video_folder, f'{phone}_{lastname}_submitted_video.mp4')
            if os.path.isfile(submitted_video_path):
            with open(submitted_video_path, 'wb+') as f:
                for chunk in video_file.chunks():
            print(f"Submitted video saved at {submitted_video_path}")

                print('\nProcessing saved video\n')
                # Extract faces from the uploaded video
                faces_in_video = extract_faces_from_video(submitted_video_path)
                print(f"Extracted {len(faces_in_video)} faces from the video")

                # Compare the submitted image with faces extracted from the video
                if compare_faces_with_user_image(faces_in_video, submitted_image_path):
                    print('\nFace recognition successful. The submitted image matches a face in the video.\n')
                    messages.success(request, 'Face recognition successful. The submitted image matches a face in the video.')
                    print('\nFace recognition failed. The submitted image does not match any face in the video.\n')
                    messages.error(request, 'Face recognition failed. The submitted image does not match any face in the video.')
            except Exception as video_processing_error:
                print(f"Error during video processing: {video_processing_error}")
                messages.error(request, 'An error occurred during video processing.')
            messages.error(request, 'Face recognition failed. Images do not match.')

    except Exception as e:
        print(f"Exception occurred: {e}")
        messages.error(request, 'An error occurred during the process.')

    user_id = request.session.get('user_id')
    if user_id:
            user = User.objects.get(id=user_id)
            user_data = {
                'firstname': user.firstname,
                'lastname': user.lastname,
                'email': user.email,
                'phone': user.phone,
            return render(request, 'registrationPage.html', {'user_data': user_data})
        except User.DoesNotExist:
            messages.error(request, "User not found.")
            return redirect('login')
        messages.error(request, "No user session found.")
        return redirect('login')

return redirect('registration')

def is_high_quality(image):
height, width = image.shape[:2]
min_resolution = (200, 200) # Minimum resolution for a high-quality image
return width >= min_resolution[0] and height >= min_resolution[1]

def compare_images_content(submitted_picture_path, existing_picture_paths):
# Load and convert submitted picture
submitted_picture = cv2.imread(submitted_picture_path)
if submitted_picture is None:
print(“Submitted picture could not be loaded.”)
return 0.0

submitted_picture_rgb = cv2.cvtColor(submitted_picture, cv2.COLOR_BGR2RGB)

# Detect faces in the submitted picture
submitted_face_locations = face_recognition.face_locations(submitted_picture_rgb)
print(f"Submitted picture face locations: {submitted_face_locations}")

if not submitted_face_locations:
    print("No faces found in the submitted picture.")
    return 0.0

# Encode faces in the submitted picture
submitted_encodings = face_recognition.face_encodings(submitted_picture_rgb, submitted_face_locations)

if not submitted_encodings:
    print("Failed to encode faces in the submitted picture.")
    return 0.0

# Load and process existing pictures
existing_encodings = []
for picture_path in existing_picture_paths:
    existing_picture = cv2.imread(picture_path)
    if existing_picture is None:
        print(f"Existing picture at {picture_path} could not be loaded.")

    if not is_high_quality(existing_picture):
        print(f"Skipping low-quality existing picture: {picture_path}")

    existing_picture_rgb = cv2.cvtColor(existing_picture, cv2.COLOR_BGR2RGB)
    existing_face_locations = face_recognition.face_locations(existing_picture_rgb)
    print(f"Existing picture face locations: {existing_face_locations} for {picture_path}")

    if not existing_face_locations:
        print(f"No faces found in existing picture: {picture_path}")

    existing_encoding = face_recognition.face_encodings(existing_picture_rgb, existing_face_locations)

    if existing_encoding:
        existing_encodings.extend(existing_encoding)  # Collect all encodings
        print(f"Failed to encode faces in existing picture: {picture_path}")

if not existing_encodings:
    print("No faces found in any high-quality existing pictures.")
    return 0.0

# Compare face encodings
for existing_encoding in existing_encodings:
    results = face_recognition.compare_faces(submitted_encodings, existing_encoding)
    if True in results:
        return 1.0  # High similarity

return 0.0  # Low similarity

def extract_faces_from_video(video_file_path):
print(f"Attempting to open video file: {video_file_path}")
video_capture = cv2.VideoCapture(video_file_path)
if not video_capture.isOpened():
print(“Error: Video file could not be opened.”)

print("Video file opened successfully.")
faces = []
frame_count = 0
    while video_capture.isOpened():
        ret, frame = video_capture.read()
        if not ret:
            print(f"End of video reached or error encountered at frame {frame_count}.")
        frame_count += 1
        print(f"Processing frame {frame_count}")
        # Sample every 30th frame to reduce processing load
        if frame_count % 30 == 0:
            rgb_frame = frame[:, :, ::-1]
            face_locations = face_recognition.face_locations(rgb_frame)
            face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)
            print(f"Frame {frame_count}: Found {len(face_locations)} faces")
except Exception as e:
    print(f"Error extracting faces from video: {e}")
    print("Video capture released.")
print(f"Total faces extracted: {len(faces)}")
return faces

def compare_faces_with_user_image(faces, user_image_path):
user_image = face_recognition.load_image_file(user_image_path)
user_encodings = face_recognition.face_encodings(user_image)
if not user_encodings:
return False
user_encoding = user_encodings[0]
for face_encoding in faces:
match = face_recognition.compare_faces([user_encoding], face_encoding)[0]
if match:
return True
return False


the main concern of my project is as follows:

  1. to take user submitted picture and check its quality the raise error messge if it does not meet the specified quality level

  2. To save the submitted picture into the submitted picture folder after finding that it meets with the quality level specified

  3. To compare the submitted picture contents with other pictures saved in the retrieved pictures folder using face recognition library and raise error message if they do non of the matching picture.

  4. if there is a matching picture on 80% and above, to take the uploaded video and save it in the video folder.

  5. To read that video, extract faces within the video and check the matching face with that user submitted picture using face recogition library as well.

So, now the issue is that after comparing pictures and finding that there is a matching one, the system saves the video and processes it. However after processing the video the process terminates without showing any output whether there found a matching or mismatching.

Below is the output I can see on the terminl:

Submitted image saved at E:\DJANGO\FINAL YEAR PROJECTS\RwandaBasketballTarentBoost\rwandaBasketballTarentBoost\RwandaBasketballTarentBoost\media\Submitted_pictures\0788457401_MUGABE_submitted_image.jpg
Retrieved image saved at E:\DJANGO\FINAL YEAR PROJECTS\RwandaBasketballTarentBoost\rwandaBasketballTarentBoost\RwandaBasketballTarentBoost\media\Retrieved_pictures\Prince_MUGABE_retrieved_image.jpg
Existing image paths: [‘E:\DJANGO\FINAL YEAR PROJECTS\RwandaBasketballTarentBoost\rwandaBasketballTarentBoost\RwandaBasketballTarentBoost\media\Retrieved_pictures\MUGABE_Prince_retrieved_image.jpg’, ‘E:\DJANGO\FINAL YEAR PROJECTS\RwandaBasketballTarentBoost\rwandaBasketballTarentBoost\RwandaBasketballTarentBoost\media\Retrieved_pictures\Prince_MUGABE_retrieved_image.jpg’]
Submitted picture face locations: [(44, 211, 152, 103)]
Existing picture face locations: [(80, 196, 155, 121)] for E:\DJANGO\FINAL YEAR PROJECTS\RwandaBasketballTarentBoost\rwandaBasketballTarentBoost\RwandaBasketballTarentBoost\media\Retrieved_pictures\MUGABE_Prince_retrieved_image.jpg
Existing picture face locations: [(80, 175, 187, 67)] for E:\DJANGO\FINAL YEAR PROJECTS\RwandaBasketballTarentBoost\rwandaBasketballTarentBoost\RwandaBasketballTarentBoost\media\Retrieved_pictures\Prince_MUGABE_retrieved_image.jpg
Image similarity: 1.0

Face recognition successful. Images match!

Saving submitted video

Submitted video saved at E:\DJANGO\FINAL YEAR PROJECTS\RwandaBasketballTarentBoost\rwandaBasketballTarentBoost\RwandaBasketballTarentBoost\media\video\0788457401_MUGABE_submitted_video.mp4

Processing saved video

Attempting to open video file: E:\DJANGO\FINAL YEAR PROJECTS\RwandaBasketballTarentBoost\rwandaBasketballTarentBoost\RwandaBasketballTarentBoost\media\video\0788457401_MUGABE_submitted_video.mp4
Video file opened successfully.
Processing frame 1
Processing frame 2
Processing frame 3
Processing frame 4
Processing frame 5
Processing frame 6
Processing frame 7
Processing frame 8
Processing frame 9
Processing frame 10
Processing frame 11
Processing frame 12
Processing frame 13
Processing frame 14
Processing frame 15
Processing frame 16
Processing frame 17
Processing frame 18
Processing frame 19
Processing frame 20
Processing frame 21
Processing frame 22
Processing frame 23
Processing frame 24
Processing frame 25
Processing frame 26
Processing frame 27
Processing frame 28
Processing frame 29
Processing frame 30
PS E:\DJANGO\FINAL YEAR PROJECTS\RwandaBasketballTarentBoost\rwandaBasketballTarentBoost\RwandaBasketballTarentBoost>

any assistance from yours would be very hlpful.

Please start by reading the pinned thread and formatting the code properly, so that we can read it properly.