Operands could not be broadcast together with shapes (128,) (0,) error

旧城冷巷雨未停 提交于 2020-01-15 07:36:14

问题


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:

errors

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

回答1:


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)

To solve the cause of the exception.



来源:https://stackoverflow.com/questions/55621789/operands-could-not-be-broadcast-together-with-shapes-128-0-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!