本文介绍了操作数不能与形状(128,)(0,)错误一起广播的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现面部识别登录系统,但出现错误无法将操作数与形状(128,)(0,)一起广播",并且我不知道该如何解决.这是我已执行的view.py和facedetector.py以及从服务器获取的错误:

I am trying to implement a facial recognition login system but I have an error "Operands could not be broadcast together with shapes (128,) (0,)" and I have no idea what or how can I solve it. Here are my view.py and facedetector.py that have been implemented and the error that I get from my server:

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,)

views.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)

facedetector.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函数的第一个参数应为 .将您的django-projects\aps\aps_site\authenticate\views.py第37行更改为:

The first argument for face_recognition.compare_faces function should be a list as stated in the documentation. Change your django-projects\aps\aps_site\authenticate\views.py line 37 to:

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

解决异常的原因.

这篇关于操作数不能与形状(128,)(0,)错误一起广播的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-10 23:31