upload image and encode face with opencv and face_recognition

86 views
Skip to first unread message

Mr Salar

unread,
Dec 23, 2023, 8:46:22 PM12/23/23
to Django users
hi
I want to take the photo file selected in the form using opencv and encode the face using face_recognition in Django before my information is saved in the database. But I can't get the photo file from cleaned data. please Help me

my views.py
from django.shortcuts import render, redirect
from django.views import View
from .models import ImageEncode
from .forms import CreateEncodeImage
from django.contrib import messages
import cv2, os
import face_recognition
from django.conf import settings

class AddCustomFaceView(View):
form_class = CreateEncodeImage
path = os.path.join(settings.BASE_DIR, 'face_lib/')

def get(self, request, *args, **kwargs):
form = self.form_class
return render(request, 'home/custom-face.html', {'form': form})

def post(self, request, *args, **kwargs):
form = self.form_class(request.POST, request.FILES)
if form.is_valid():
new_face = form.save(commit=False)

img_name = form.cleaned_data['imgname']
img_add = form.cleaned_data['imgaddress']

img_face = cv2.imread(f'{img_add}')
img_face = cv2.cvtColor(img_face, cv2.COLOR_RGB2BGR)
face_loc = face_recognition.face_locations(img_face)
y1, x2, y2, x1 = face_loc
y1, x2, y2, x1 = y1, x2, y2, x1
image_frame = img_face[y1:y2, x1:x2]
encode = face_recognition.face_encodings(img_face)

if encode:
new_face.imgencode = encode[0]
new_face.imgname = img_name
new_face.imgaddress = form.cleaned_data('imgaddress')
new_face.save()
cv2.imwrite(self.path + img_name, image_frame)
messages.success(request, 'New Custom Face Saved', 'success')
else:
messages.warning(request, 'could not save this face', 'success')
return redirect('home:face_custom')
return redirect('home:list_img')
else:
messages.warning(request, 'not valid data', 'warning')
return redirect('home:face_custom')

my forms.py
from django import forms
from .models import ImageEncode

class CreateEncodeImage(forms.ModelForm):
class Meta:
model = ImageEncode
fields = ('imgname', 'imgaddress',)

my models.py
import numpy as np
from django.db import models
from ndarraydjango.fields import NDArrayField

class ImageEncode(models.Model):
imgencode = NDArrayField(shape=(32, 4), dtype=np.float64)
imgname = models.CharField(max_length=100, null=False)
imgaddress = models.ImageField(upload_to='face_lib/', null=False)
created = models.DateTimeField(auto_now_add=True)
Reply all
Reply to author
Forward
0 new messages