Hi, I’m using Django 5.0, and I wrote the following code to get the facial recognition from the device camera and compare it with the stored image. This part behaves well, but the code never performs the redirect and freezes. Please how could I improve my code and fix this problem?
import os
import cv2
import threading
import face_recognition
from queue import Queue
from django.shortcuts import render, redirect
from django.http import StreamingHttpResponse
from django.views.decorators import gzip
from .forms import FormKYC
from .models import KYCData
def user_profile(request, pk):
kyc = KYCData.objects.get(id=pk)
context = {
'kyc': kyc
}
return render(request, 'kycapp/user_profile.html', context=context)
@gzip.gzip_page
def camera_view(request, pk):
try:
cam = VideoCamera()
response = StreamingHttpResponse(gen(cam, pk), content_type="multipart/x-mixed-replace;boundary=frame")
return response
except:
pass
return render(request, 'kycapp/camera.html')
class VideoCamera(object):
def __init__(self):
self.video = cv2.VideoCapture(0)
(self.grabbed, self.frame) = self.video.read()
self.queue = Queue() # Queue to communicate between threads
self.thread = threading.Thread(target=self.update, args=())
self.thread.daemon = True
self.thread.start()
def stop(self):
self.video.release()
self.queue.put(None)
self.thread.join()
def get_frame(self):
image = self.frame
_, jpeg = cv2.imencode('.jpg', image)
return jpeg.tobytes()
def update(self):
while True:
if not self.thread.is_alive(): # Break the loop if the thread is not alive
break
(self.grabbed, self.frame) = self.video.read()
base_path = "[path_of]"
def gen(camera, pk):
face_cascade = cv2.CascadeClassifier(base_path)
kyc_data = KYCData.objects.get(id=pk)
image_doc = kyc_data.images.document_image.file
reference_image = cv2.imread(str(image_doc))
reference_face_encoding = face_recognition.face_encodings(reference_image)[0]
match_found = False
while match_found == False:
frame = camera.get_frame()
gray = cv2.cvtColor(camera.frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5)
for (x, y, w, h) in faces:
cv2.rectangle(camera.frame, (x, y), (x + w, y + h), (255, 0, 0), 2)
face_encodings = face_recognition.face_encodings(camera.frame)
if len(face_encodings) > 0:
for face_encoding in face_encodings:
match = face_recognition.compare_faces([reference_face_encoding], face_encoding)
if match[0]:
kyc_data.camera_validation = True
kyc_data.save()
match_found = True
camera.stop()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
return redirect('profile', pk=pk)