You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django中将图片上传至数据库前获取face_encoding信息?

在Django上传图片前获取人脸编码(face_recognition实现)

1. 准备工作

先确保安装所需依赖:

pip install face_recognition

2. 调整模型(models.py)

给你的图片模型添加存储人脸编码的字段,用JSONField来存编码数组(因为face_recognition返回的是numpy数组,转成列表后可直接存入JSONField):

from django.db import models

class Image(models.Model):
    image = models.ImageField(upload_to='images/')
    # 用于存储人脸编码,允许为空(比如图片无检测到人脸的情况)
    face_encoding = models.JSONField(null=True, blank=True)

3. 调整表单(forms.py)

表单只需要暴露图片上传字段,人脸编码由后台自动处理:

from django import forms
from .models import Image

class ImageForm(forms.ModelForm):
    class Meta:
        model = Image
        fields = ['image']  # 仅展示图片上传控件

4. 修改视图函数

在保存图片到数据库前,先读取上传文件、检测人脸并获取编码:

import face_recognition
from django.http import HttpResponse
from django.template import loader
from .forms import ImageForm

def index(request):
    if request.method == 'POST':
        form = ImageForm(request.POST, request.FILES)
        if form.is_valid():
            # 创建模型实例但暂不写入数据库
            image_instance = form.save(commit=False)
            
            try:
                # 读取上传的图片文件
                img_file = request.FILES['image']
                img = face_recognition.load_image_file(img_file)
                
                # 获取图片中的人脸编码(取第一个检测到的人脸)
                face_encodings = face_recognition.face_encodings(img)
                
                if face_encodings:
                    # 将numpy数组转成普通列表,存入JSON字段
                    image_instance.face_encoding = face_encodings[0].tolist()
                    # 保存实例到数据库
                    image_instance.save()
                    return HttpResponse("图片上传成功,已提取人脸编码")
                else:
                    return HttpResponse("图片中未检测到人脸")
            except Exception as e:
                return HttpResponse(f"图片处理失败:{str(e)}")
        else:
            return HttpResponse("表单验证失败")
    else:
        context = {'form': ImageForm()}
        template = loader.get_template("core/index.html")
        return HttpResponse(template.render(context, request))

注意事项

  • 如果需要处理图片中的多个人脸,可以把face_encoding字段存储为列表的列表,比如image_instance.face_encoding = [enc.tolist() for enc in face_encodings]
  • 确保服务器环境满足face_recognition的运行要求:Linux/macOS需提前安装dlib依赖,Windows可直接通过pip安装预编译包
  • 可以根据业务需求,把“未检测到人脸”的情况改为拒绝上传,或者继续保存但留空face_encoding字段

内容的提问来源于stack exchange,提问作者ouadaoui amine

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 07:26:06