我有一个将图像上传到数据库的视图。
在上传到数据库之前我需要获取face_encoding。
有什么想法如何做到这一点吗?
这是我的观点:
def index(request):
if request.method=='POST':
form = ImageForm(request.POST,request.FILES)
if form.is_valid():
form.save()
return HttpResponse(type(ImageForm))
else:
return HttpResponse("error")
context={'form':ImageForm()}
template=loader.get_template("core/index.html")
return HttpResponse(template.render(context,request))
我想使用 face_recognition 库。
如果您打算使用face_recognition对人脸进行编码,那么您应该更新您的视图函数
import face_recognition
def index(request):
if request.method == 'POST':
form = ImageForm(request.POST, request.FILES)
if form.is_valid():
# Get uploaded image file
image_file = request.FILES['image_field_name']
# Read the image file
uploaded_image = face_recognition.load_image_file(image_file)
# Get face encodings
face_encodings = face_recognition.face_encodings(uploaded_image)
if len(face_encodings) > 0:
# Assuming you want to save only the first face encoding
first_face_encoding = face_encodings[0]
# Additional processing if needed
# Save the image to the database along with the face encoding
instance = form.save(commit=False)
instance.face_encoding = first_face_encoding.tostring() # Convert to string for saving in the database
instance.save()
return HttpResponse("Image uploaded successfully with face encoding.")
else:
return HttpResponse("No face found in the uploaded image.")
else:
return HttpResponse("Invalid form data.")
context = {'form': ImageForm()}
template = loader.get_template("core/index.html")
return HttpResponse(template.render(context, request))