0

So i got here is a code that detect if the face in the image is in my encodings. So my problem is what if the face is not in the Encodings can i pass a string variable to a OneToOneField() or can i set a default value to it? and also how can i link the image it is in a Numpy Array format yeah i already think about just saving it inside my MEDIA folder but how can i link it to ImageField()?

Here's my code:

models.py

def log_image_path(instance, filename):
extention = filename.split('.')[-1]
return os.path.join(settings.LOGS_ROOT, f"{uuid.uuid4()}.{extention}")

class MonitorLog(models.Model):
student_info = models.OneToOneField(Student, on_delete=models.CASCADE)
log_image    = models.ImageField(upload_to=log_image_path) 
log_time     = models.DateTimeField(default=timezone.now)

tasks.py

def identify_face(arr):
master_encodings = pickle.loads(open(settings.TRAINING_FILE_DIR, 'rb').read())

arr   = np.asarray(arr)
rgb   = arr[:,:,::-1]
faces = face_recognition.face_locations(rgb, model='hog')
enc   = face_recognition.face_encodings(rgb, faces)

main_enc = [encs for encs in enc]

for encoding in main_enc:
    matches = face_recognition.compare_faces(master_encodings['encodings'], encoding)
    name = 'Unknown'

    if True in matches:
        encIds = [encIndex for (encIndex, value) in enumerate(matches) if value]
        counts = {}
        for num in encIds:
            name = master_encodings['student_number'][num]
            counts[name] = counts.get(name, 0) + 1

        name = max(counts, key=counts.get)

if name != "Unknown":
    stud_ins = models.Student.objects.get(student_number=name)
  • Why not use a `FileField` instead of `ImageField`. You should set your `OneToOneField` to allow for `null=True` so if there's no match, you don't need to set it to anything (it'll just be `None`). – dirkgroten Feb 18 '19 at 18:53
  • Possible duplicate of [Saving a Numpy array as an image](https://stackoverflow.com/questions/902761/saving-a-numpy-array-as-an-image) – dirkgroten Feb 18 '19 at 19:03
  • I've just done a quite a pragmatic solution. I saved it with cv2 then get the file path then gave it to ImageField(). One question tho is it efficient or is there a more better solution? – Carl Dennis Alingalan Feb 20 '19 at 02:56

1 Answers1

0

To save a NumPy array in ImageField, I used Django's ContentFile class.

import cv2
from django.core.files.base import ContentFile

def some_function(array):
    frame_jpg = cv2.imencode('.jpg', array)
    file = ContentFile(frame_jpg)

    # Get the required model instance

    instance.photo.save('myphoto.jpg', file, save=True)