Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

python - Django cut and put only the face in the picture field using opencv

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

question from:https://stackoverflow.com/questions/65950681/django-cut-and-put-only-the-face-in-the-picture-field-using-opencv

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...