简体   繁体   中英

How to check whether an image contains a face or not before saving it to the media directory?

I am working with Django Rest Framework to create a Face Recognition API. I have created a standalone application for Face Recognition using 'face_recognition' library in Python and OpenCV. Now I need to convert this standalone project to an API.

In model.py I have created a class named Person Which contains some fields for registering a person like name, email, password, and also an image. The person uploads an image and it gets saved to the media directory. I want to check whether the uploaded image contains a face or not. It should be saved in the media directory if and only if it contains only one face. Otherwise, there should be a message saying "The uploaded image does not contain a face or contains more than one face".

I am new to the Django Framework and APIs in general. Any help is greatly appreciated.

The codes are as follows:

Method to check for the existence of face:

import face_recognition


def check_face_exist(path, image_name):
    test_image = path + image_name
    image = face_recognition.load_image_file(test_image)
    face_locations = face_recognition.face_locations(image)
    if len(face_locations) <= 0:
        message = 'There is no face in the provided image, Please select another image.'

    elif len(face_locations) > 1:
        message = 'There are multiple faces in the provided image, Please select another image.'

    else:
        message = 'This is a perfect image.'

    return message


message = check_face_exist('Images/', 'two_persons.jpg')
print(message)

models.py

# Create your models here.
from django.db import models


# lets us explicitly set upload path and filename
def upload_to(instance, filename):
    return 'images/{filename}'.format(filename=filename)


class Person(models.Model):
    name = models.CharField(max_length=60, blank=False, null=False)
    image_url = models.ImageField(upload_to=upload_to, blank=True, null=True)

    def __str__(self):
        return self.name

serializers.py

from rest_framework import serializers
from .models import Person


class PersonSerializer(serializers.HyperlinkedModelSerializer):
    # image_url = serializers.ImageField(required=True)

    class Meta:
        model = Person
        fields = ('id', 'name', 'image_url')  # fields = ('id',) to use only one field

views.py

import face_recognition
from django.http import JsonResponse, HttpResponse
from rest_framework import viewsets
from .serializers import PersonSerializer
from .models import Person
from rest_framework import permissions
from rest_framework.parsers import MultiPartParser, FormParser
from django.conf import settings


class PersonViewSet(viewsets.ModelViewSet):
    queryset = Person.objects.all().order_by('id')
    serializer_class = PersonSerializer
    parser_classes = (MultiPartParser, FormParser)
    permission_classes = [
        permissions.IsAuthenticatedOrReadOnly]
    # recognition = recognize_face(settings.MEDIA_ROOT+'//images/', str(Person.image_url))


def getFacesUrl(request):
    # path = '/' + path.replace('-', '/')
    path = settings.MEDIA_ROOT+'//images/two_persons.jpg'
    image = face_recognition.load_image_file(path)
    face_locations = face_recognition.face_locations(image)
    face_landmarks_list = face_recognition.face_landmarks(image)
    list_of_face_encodings = face_recognition.face_encodings(image)
    # y1, x2, y2, x1 = face_locations
    # cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
    # cv2.imshow('Test', image)
    # c = cv2.waitKey(0)
    responseData = {
        'Faces': len(face_locations),
        'Face Locations': face_locations,
        'Face Landmarks': face_landmarks_list,
    }
    return JsonResponse(responseData)

How to pass the currently added image URL to the getFacesUrl method?

The checks which you want to implement should be placed in your frontend application which reads the image, the reason is simple you have already set up the things to play with the image, now if you want to have these checks in Django env then you will need to set up the whole things in backend.

I don't know about the approach you took, regarding the OpenCV, there is one article for you, https://www.digitalocean.com/community/tutorials/how-to-detect-and-extract-faces-from-an-image-with-opencv-and-python

You could use a face detection model to check whether each image contains only one face. Faster RCNN with ResNet backbone works very well for that task. Alternatively, there is also Yolov4 with DarkNet as a backbone.

The simplest approach would be to take a pre-trained Faster RCNN model from Keras. This blog explains an easy approach for that: https://www.sitepoint.com/keras-face-detection-recognition/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM