Django使用opencv2仅将脸部切入图片字段 [英] Django cut and put only the face in the picture field using opencv2

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

问题描述

我使用cv2对FaceCropped进行了编码,并且有效!
我想通过ProcessedImageField模型中的facecropped方法放置img.
反正有吗我想要的是在将图片上传到学生模型中时自动剪断脸并将其放入数据库中.

I coded FaceCropped using cv2 and it works!
I want to put img through facecropped method in ProcessedImageField model.
Is there anyway? What I want is to automatically cut the face and put it in the database when uploading pictures into student model.

裁剪的方法

import numpy as np
import cv2
import os
import glob

def FaceCropped(full_path, extra='face', show=False):
    face_cascade = cv2.CascadeClassifier('C:../haarcascade_frontalface_default.xml')
    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(path + '/' + extra + file, mode='w+b') as f:
                encoded_img.tofile(f)
    if show:
        cv2.imshow('Image view', cropped)
        cv2.waitKey(0)
        cv2.destroyAllWindows()

我的模型.py

class Student(models.Model):
    picture = ProcessedImageField(
        verbose_name = 'picture',
        upload_to = 'students/%Y/',
        processors=[ResizeToFill(300,300)],
        options={'quality':80},
        format='JPEG',
        null=True,
        blank=True,
        default='students/no-img.jpg',
    )
    name = models.CharField(max_length=255)

我的views.py

my views.py

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

    def post(self, request):
        form = self.form_class(request.POST, request.FILES)

        if form.is_valid():
            student = form.save(commit=False)
            student.created_by = request.user

            student.save()
            messages.info(request, student.name + ' addddd', extra_tags='info')
            if "save_add" in self.request.POST:
                return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
            return redirect('student_detail', pk=student.pk, school_year=student.school_year)

        return FormView.post(self, request)

推荐答案

有几种方法可以实现.

将作物图像保存到数据库中的一种方法是,您需要覆盖save方法.
请查看此文档.

One way to save crop Image into database is that you need to override the save method.
Have a look at this document.

在将数据保存到数据库之前,您可以对模型数据进行任何处理.您可以随意覆盖这些方法(和任何其他模型方法)来更改行为.

You can do whatever you want to process on model data before you save data into database. You’re free to override these methods (and any other model method) to alter behavior.

下面的代码来自Django文档.

The code below is from django document.

from django.db import models

class Blog(models.Model):
    name = models.CharField(max_length=100)
    tagline = models.TextField()

    def save(self, *args, **kwargs):
        do_something()
        super().save(*args, **kwargs)  # Call the "real" save() method.
        do_something_else()

继承Field类并覆盖清洁方法

我假设您正在使用 imagekit

from imagekit.models import ProcessedImageField

您可以继承 ProcessedImageField 并覆盖清除方法可确保清除中的所有数据.保存之前的图像处理可以采用干净的方法.

Clean method ensure that all data in field is cleaned. Image processing before saving can be in clean method.

下面的代码来自Django源代码.

The code below is from django source code.

def clean(self, value):
    """
    Validate the given value and return its "cleaned" value as an
    appropriate Python object. Raise ValidationError for any errors.
    """
    value = self.to_python(value)
    self.validate(value)
    self.run_validators(value)
    return value

覆盖表单清除方法

此问题说明了如何覆盖表格清洁方法.
清理方法将在保存方法之前运行.
这是保存之前更改数据的另一种常用方法.

Override Form clean method

This question explain how to override form clean method.
Clean method will run before save method.
This is another common way to change the data before saving.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆