将一个Numpy数组图像传递给ImageField()

时间:2019-02-18 17:33:04

标签: django python-3.x numpy

所以我到达这里是一个代码,用于检测图像中的人脸是否在我的编码中。所以我的问题是,如果面部不在编码中,该如何将字符串变量传递给OneToOneField()或可以为其设置默认值?以及如何链接以Numpy Array格式显示的图像,是的,我已经考虑过将其保存在MEDIA文件夹中,但是如何将其链接到ImageField()?

这是我的代码:

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)

1 个答案:

答案 0 :(得分:0)

要在ImageField中保存NumPy数组,我使用了Django的ContentFile类。

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)