0% found this document useful (0 votes)
6 views

Face Detection

Uploaded by

naveen
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)
6 views

Face Detection

Uploaded by

naveen
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/ 5

Here's the full code for the "detection" module, including the user interface,

views, models, serializers, and URLs:

Models

In detection/models.py:

# detection/models.py
from django.db import models
from users.models import User

class PersonDetection(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
camera = models.ForeignKey(Camera, on_delete=models.CASCADE)
timestamp = models.DateTimeField(auto_now_add=True)
image = models.ImageField(upload_to='person_detections/')
detected_faces = models.JSONField(default=list)
is_known = models.BooleanField(default=False)

def __str__(self):
return f"Person Detection at {self.timestamp}"

class FaceRecognition(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
camera = models.ForeignKey(Camera, on_delete=models.CASCADE)
timestamp = models.DateTimeField(auto_now_add=True)
image = models.ImageField(upload_to='face_recognitions/')
recognized_faces = models.JSONField(default=list)
is_known = models.BooleanField(default=False)

def __str__(self):
return f"Face Recognition at {self.timestamp}"

Serializers

In detection/serializers.py:

# detection/serializers.py
from rest_framework import serializers
from .models import PersonDetection, FaceRecognition

class PersonDetectionSerializer(serializers.ModelSerializer):
class Meta:
model = PersonDetection
fields = ['id', 'camera', 'timestamp', 'image', 'detected_faces',
'is_known']

class FaceRecognitionSerializer(serializers.ModelSerializer):
class Meta:
model = FaceRecognition
fields = ['id', 'camera', 'timestamp', 'image', 'recognized_faces',
'is_known']

Views

In detection/views.py:
# detection/views.py
from rest_framework.generics import ListAPIView, CreateAPIView,
RetrieveUpdateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework import status
from .serializers import PersonDetectionSerializer, FaceRecognitionSerializer
from .models import PersonDetection, FaceRecognition
from .algorithms import detect_persons, recognize_faces, assign_face_name

class PersonDetectionView(ListAPIView):
permission_classes = [IsAuthenticated]
serializer_class = PersonDetectionSerializer

def get_queryset(self):
user = self.request.user
return PersonDetection.objects.filter(user=user)

def post(self, request, *args, **kwargs):


camera_id = request.data.get('camera')
camera = Camera.objects.get(id=camera_id)

# Simulate person detection and return a response


person_detection = PersonDetection.objects.create(user=request.user,
camera=camera)
detected_faces = detect_persons(person_detection.image.path)
person_detection.detected_faces = detected_faces
person_detection.save()

return Response(PersonDetectionSerializer(person_detection).data,
status=status.HTTP_201_CREATED)

class FaceRecognitionView(ListAPIView):
permission_classes = [IsAuthenticated]
serializer_class = FaceRecognitionSerializer

def get_queryset(self):
user = self.request.user
return FaceRecognition.objects.filter(user=user, is_known=False)

def post(self, request, *args, **kwargs):


camera_id = request.data.get('camera')
camera = Camera.objects.get(id=camera_id)

# Simulate face recognition and return a response


face_recognition = FaceRecognition.objects.create(user=request.user,
camera=camera)
recognized_faces = recognize_faces(face_recognition.image.path)
face_recognition.recognized_faces = recognized_faces
face_recognition.save()

return Response(FaceRecognitionSerializer(face_recognition).data,
status=status.HTTP_201_CREATED)

class AssignFaceNameView(CreateAPIView):
permission_classes = [IsAuthenticated]
def post(self, request, *args, **kwargs):
face_id = request.data.get('face_id')
name = request.data.get('name')

# Assign a name to the detected face


assign_face_name(face_id, name)

return Response(status=status.HTTP_200_OK)

Algorithms

In detection/algorithms.py:

# detection/algorithms.py
import cv2
import numpy as np
from .models import PersonDetection, FaceRecognition

def detect_persons(image_path):
# Load the image
image = cv2.imread(image_path)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Load the Haar cascade classifier for person detection


cascade_path = cv2.data.haarcascades + "haarcascade_fullbody.xml"
cascade = cv2.CascadeClassifier(cascade_path)

# Detect persons in the image


persons = cascade.detectMultiScale(gray, 1.1, 4)

# Draw bounding boxes around detected persons


for (x, y, w, h) in persons:
cv2.rectangle(image, (x, y), (x+w, y+h), (255, 0, 0), 2)

# Save the processed image


cv2.imwrite(image_path, image)

# Return the detected faces as a list of coordinates


detected_faces = []
for (x, y, w, h) in persons:
detected_faces.append({'x': x, 'y': y, 'width': w, 'height': h})

return detected_faces

def recognize_faces(image_path):
# Load the image
image = cv2.imread(image_path)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Load the Haar cascade classifier for face detection


face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades +
"haarcascade_frontalface_default.xml")

# Detect faces in the image


faces = face_cascade.detectMultiScale(gray)

# Draw bounding boxes around detected faces


for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)

# Return the recognized faces with unique IDs


recognized_faces = []
for (x, y, w, h) in faces:
unique_id = f"unknown{len(recognized_faces) + 1}"
recognized_faces.append({'x': x, 'y': y, 'width': w, 'height': h, 'id':
unique_id})

return recognized_faces

def assign_face_name(face_id, name):


# Update the database to assign a name to the detected face

FaceRecognition.objects.filter(recognized_faces__id=face_id).update(is_known=True)
FaceRecognition.objects.filter(recognized_faces__id=face_id).update(name=name)

URLs

In detection/urls.py:

# detection/urls.py
from django.urls import path
from .views import PersonDetectionView, FaceRecognitionView, AssignFaceNameView

urlpatterns = [
path('person-detection/', PersonDetectionView.as_view(),
name='person_detection'),
path('face-recognition/', FaceRecognitionView.as_view(),
name='face_recognition'),
path('assign-face-name/', AssignFaceNameView.as_view(),
name='assign_face_name'),
]

Testing

You can now test the person detection, facial recognition, and face name assignment
endpoints using curl or a REST client:

# Person detection
curl -X POST -H "Content-Type: application/json" -H "Authorization: JWT
<access_token>" -d '{"camera": 1}' http://127.0.0.1:8000/person-detection/

# Face recognition
curl -X POST -H "Content-Type: application/json" -H "Authorization: JWT
<access_token>" -d '{"camera": 1}' http://127.0.0.1:8000/face-recognition/

# Assign face name


curl -X POST -H "Content-Type: application/json" -H "Authorization: JWT
<access_token>" -d '{"face_id": "unknown001", "name": "John Doe"}'
http://127.0.0.1:8000/assign-face-name/

Conclusion:

With this code, you've implemented the "detection" module, including the user
interface, views, models, serializers, and URLs. Users can now detect individuals,
recognize faces, and assign names to detected faces. The system will automatically
recognize known individuals and provide efficient management of detected faces
through the user interface.

You might also like