Search code examples
djangodjango-modelsdjango-formsface-recognition

How to add photo encodings to db with django using face_recognition api?


I try but it doesn't work... My model:

class Staff(models.Model):

    photo = models.FileField()
    encodings = models.TextField()

    def get_encodings(self):
        enc = face_recognition.face_encodings(self.photo)
        return enc

    def save(self, *args, **kwargs):
        self.encodings = self.get_encodings()
        super(Staff, self).save(*args, **kwargs)

The error which i have when try to add new object

__call__(): incompatible function arguments. The following argument types 
are supported:
1. (self: dlib.fhog_object_detector, image: array, upsample_num_times: 
int=0) -> dlib.rectangles

Invoked with: <dlib.fhog_object_detector object at 0x0000023D8CD9E570>, 
<FieldFile: photo_2018-12-05_23-09-20.jpg>, 1

Solution

  • You have to convert the file to an image file by using PIL library. face_recognition.face_encodings expect a numpy array as input

     import PIL.Image
    
    class Staff(models.Model):
    
        photo = models.FileField()
        encodings = models.TextField()
    
        def get_encodings(self):
            enc = face_recognition.face_encodings(self.read_image_from_file(self.photo))
            return enc
    
        def save(self, *args, **kwargs):
            self.encodings = self.get_encodings()
            super(Staff, self).save(*args, **kwargs)
    
       def read_image_from_file(file):
           return np.array(PIL.Image.open(file))
    

    Don't forget to use try and catch when you try to read/open the file/image. My code is just for demonstration, so you must extend it with the needed checks!