python - 操作数无法与形状一起广播 (128,) (0,) 错误

标签 python django face-recognition

我正在尝试实现面部识别登录系统,但出现错误“操作数无法与形状 (128,) (0,) 一起广播”,我不知道如何解决或如何解决它。这是我已经实现的 view.py 和 facedetector.py 以及我从我的服务器得到的错误:

错误

Traceback (most recent call last):
File "C:\django-projects\lib\site packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\django-projects\lib\site-packages\django\core\handlers\base.py", 
line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\django-projects\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\django-projects\aps\aps_site\authenticate\views.py", line 54, in login_user
if facedect(user.userprofile.head_shot.url):
File "C:\django-projects\aps\aps_site\authenticate\views.py", line 37, in facedect
check=face_recognition.compare_faces(face_1_face_encoding, face_encodings)
File "C:\django-projects\lib\site-packages\face_recognition\api.py", line 222, in compare_faces
return list(face_distance(known_face_encodings, face_encoding_to_check) <= tolerance)
File "C:\django-projects\lib\site-packages\face_recognition\api.py", line 72, in face_distance
return np.linalg.norm(face_encodings - face_to_compare, axis=1) 
ValueError: operands could not be broadcast together with shapes (128,) (0,)

View .py
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout, 
update_session_auth_hash
from django.contrib.auth.forms import UserCreationForm, UserChangeForm, PasswordChangeForm
from django.contrib import messages
from .forms import SignUpForm, EditProfileForm
from django.urls import path, include
import os
import face_recognition
import cv2 

# Create your views here.

def home(request):
    return render(request, 'authenticate/home.html', {})

def facedect(loc):
    cam = cv2.VideoCapture(0)   
    s, img = cam.read()
    if s:   

            BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
            MEDIA_ROOT =os.path.join(BASE_DIR,'aps_site')

            loc=(str(MEDIA_ROOT)+loc)
            face_1_image = face_recognition.load_image_file(loc)
            face_1_face_encoding = face_recognition.face_encodings(face_1_image)[0]

            #

            small_frame = cv2.resize(img, (0, 0), fx=0.25, fy=0.25)

            rgb_small_frame = small_frame[:, :, ::-1]

            face_locations = face_recognition.face_locations(rgb_small_frame)
            face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)

            check=face_recognition.compare_faces(face_1_face_encoding, face_encodings)


            print(check)
            if check[0]:
                    return True

            else :
                    return False    


def login_user(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(request, username=username,password=password)
    if user is not None:
        if facedect(user.userprofile.head_shot.url):
            login(request, user)
            messages.success(request,('You have successfully logged in!'))
        return redirect('home')
    else:
        messages.success(request, ('Error logging in!-Please try again'))
        return redirect('login')
else:
    return render(request, 'authenticate/login.html', {})

def logout_user(request):
    logout(request)
    messages.success(request, ('You have been logged out!'))
    return redirect('login')

def register_user(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data['username']
            password = form.cleaned_data['password1']
            user = authenticate(username = username, password = password)
            login(request, user)
            messages.success(request, ('You have registered...'))
            return redirect('home')
    else:
        form = SignUpForm()

    context = {'form' : form}
    return render(request, 'authenticate/register.html', context)

def edit_profile(request):
    if request.method == 'POST':
        form = EditProfileForm(request.POST, instance=request.user)
        if form.is_valid():
            form.save()
            messages.success(request, ('You have edited your profile...'))
            return redirect('home')
    else:
        form = EditProfileForm(instance=request.user) #

    context = {'form' : form}
    return render(request, 'authenticate/edit_profile.html', context)

def change_password(request):
    if request.method == 'POST':
        form = PasswordChangeForm(data=request.POST, user=request.user)
        if form.is_valid():
            form.save()
            update_session_auth_hash(request, form.user)
            messages.success(request, ('You have changed your password...'))
            return redirect('home')
    else:
        form = PasswordChangeForm(user=request.user) #

    context = {'form' : form}
    return render(request, 'authenticate/change_password.html', context)

人脸检测器.py
import os
from django.urls import path, include
import face_recognition
import cv2 
from PIL import Image #?


#initialize the camera
def facedect(loc):
    cam = cv2.VideoCapture(0)   # 0 -> index of camera
    s, img = cam.read()
    if s:   
            # frame captured without any errors
            cv2.namedWindow("image_test")
            cv2.imshow("image_test",img)
            #cv2.waitKey(0) # waits until a key is pressed
            cv2.destroyWindow("image_test")
            cv2.imwrite("captured-image.png",img) #to save the captured image to the directory file

            BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
            MEDIA_ROOT =os.path.join(BASE_DIR,'aps_site')

            print(MEDIA_ROOT,loc)
            loc=(str(MEDIA_ROOT)+loc)
            print(loc)
            print("C:\django-projects\aps\aps_site\aps_site\media\profile_images")
            face_1_image = face_recognition.load_image_file(loc)
            face_1_face_encoding = face_recognition.face_encodings(face_1_image)[0]

            small_frame = cv2.resize(img, (0, 0), fx=0.25, fy=0.25)

            rgb_small_frame = small_frame[:, :, ::-1]

            face_locations = face_recognition.face_locations(rgb_small_frame)
            face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)

            check=face_recognition.compare_faces(face_1_face_encoding, face_encodings)

            print(check)
            if check[0]:
                    return True

            else :
                    return False    

facedect('C:\media\profile_images')

最佳答案

face_recognition.compare_faces 的第一个参数函数应该是一个列表,如 stated in the documentation .更改您的 django-projects\aps\aps_site\authenticate\views.py第 37 行:

check=face_recognition.compare_faces([face_1_face_encoding], face_encodings)

解决异常的原因。

关于python - 操作数无法与形状一起广播 (128,) (0,) 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55621789/

相关文章:

python - 为什么人脸聚类算法不使用距离矩阵而不是聚类算法?

c++ - 人脸识别分类器

ios - iPhone5C 中未安装 Luxand SDK

python - 如何在 django 管理界面中更改默认字体?

django - 将 postgres 转储迁移到 RDS

Django:无法解析其余部分: '"{ %' from '“{%”

python - 在 Google App Engine 上运行 Python37 时出现问题

python 正则表达式的行为不符合我的预期

python - 解释 3D 数组在内存中的间距、宽度、高度、深度

python setup.py install 在 Alpine 图像上无法正常工作