0

This is the first question Django cut and put only the face in the picture field using opencv2

I have some problems
First. It works even when I update it, so the picture gets weird.
Second. The image size is weird because 'ProcessedImageField' works first and 'FaceCropped' works later.

here we go my codes


class Student(models.Model):
    picture = ProcessedImageField(
        verbose_name = 'pictures',
        upload_to = 'students/%Y/',
        processors=[ResizeToFill(300,300)],
        options={'quality':80},
        format='JPEG',
        null=True,
        blank=True,
        default='students/no-img.jpg',
    )
    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        FaceCropped(self.picture.path)

def FaceCropped(full_path):
    base_dir = os.path.dirname(os.path.abspath(__file__))
    file_list = os.listdir('student')

    for i in file_list:
        if i == 'haarcascade_frontalface_default.xml':
            face_cascade_path = os.path.join(base_dir, i)

    face_cascade = cv2.CascadeClassifier(face_cascade_path)
    full_path = full_path
    path,file = os.path.split(full_path)

    ff = np.fromfile(full_path, np.uint8)
    img = cv2.imdecode(ff, cv2.IMREAD_UNCHANGED)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3,5)

    for (x,y,w,h) in faces:
        cropped = img[y - int(h/4):y + h + int(h/4), x - int(w/4):x + w + int(w/4)]
        result, encoded_img = cv2.imencode(full_path, cropped)
        if result:
            with open(full_path, mode='w+b') as f:
                encoded_img.tofile(f)
                break;

What i want to is When 'FaceCropped' works, only when i create a new model.
So that it doesn't work when i update the model.
plz help me up

大陸北方網友
  • 3,696
  • 3
  • 12
  • 37
chea
  • 101
  • 1
  • 11

1 Answers1

0

I notice that you already had an form_class class AddStudent in your view.py.

class StudentAdd(FormView):
    model = Student
    template_name = 'student/list_add.html'
    context_object_name = 'student'
    form_class = AddStudent

So, you could override your form_class clean method and make sure the FaceCropped function run before form.save().
The answers below this question should answer your question

Misster Hao
  • 92
  • 1
  • 1
  • 10