本文介绍了Django使用opencv剪切并仅将脸部放置在图片字段中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是第一个问题 Django仅剪切并放置了使用opencv2在图片字段中修改人脸

我遇到一些问题
第一的.即使我更新它也可以,所以图片变得很奇怪.
第二.图像大小很奇怪,因为"ProcessedImageField"首先起作用,而"FaceCropped"随后起作用.

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;

我要的是仅当我创建新模型时,"FaceCropped"工作时.
因此,当我更新模型时,它不起作用.
请帮我

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

推荐答案

我注意到您在view.py中已经有一个form_class类 AddStudent .

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

因此,您可以覆盖form_class的clean方法,并确保 FaceCropped 函数在 form.save()之前运行.此问题下面的答案应回答您的问题

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

这篇关于Django使用opencv剪切并仅将脸部放置在图片字段中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 04:38
查看更多