ValueError: operands could not be broadcast together with shapes (1,0) (128,) on raspberry pi
- face_recognition version:
- Python version: 3.5.5
- Operating System: rapbian
Description
Adding second image for recognition on raspberry. Getting:
Traceback (most recent call last):
File "/home/pi/Рабочий стол/facerec_on_raspberry_pi.py", line 299, in <module>
match = face_recognition.compare_faces([Roman_face_encoding], face_encoding)
File "/usr/local/lib/python3.5/dist-packages/face_recognition/api.py", line 212, in compare_faces
return list(face_distance(known_face_encodings, face_encoding_to_check) <= tolerance)
File "/usr/local/lib/python3.5/dist-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 (1,0) (128,)
What I Did
All samples with face_recognition
import face_recognition
import picamera
import numpy as np
camera = picamera.PiCamera()
camera.resolution = (320, 240)
output = np.empty((240, 320, 3), dtype=np.uint8)
# Load a sample picture and learn how to recognize it.
print("Loading known face image(s)")
Aleksey_image = face_recognition.load_image_file("photo1.jpg")
Aleksey_face_encoding= face_recognition.face_encodings(Aleksey_image)[0]
Roman_image = face_recognition.load_image_file("photo2.jpg")
Roman_face_encoding = face_recognition.face_encodings(Roman_image)
if len(Roman_face_encoding) > 0:
Roman_face_encoding = Roman_face_encoding[0]
# Initialize some variables
face_locations = []
face_encodings = []
while True:
if code == c_code:
print("Capturing image.")
# Grab a single frame of video from the RPi camera as a numpy array
camera.capture(output, format="rgb")
# Find all the faces and face encodings in the current frame of video
face_locations = face_recognition.face_locations(output)
print("Found {} faces in image.".format(len(face_locations)))
face_encodings = face_recognition.face_encodings(output, face_locations)
# Loop over each face found in the frame to see if it's someone we know.
for face_encoding in face_encodings:
# See if the face is a match for the known face(s)
match = face_recognition.compare_faces([Roman_face_encoding], face_encoding)
name = "<Unknown Person>"
if match[0]:
name = "Roman"
match = face_recognition.compare_faces([Aleksey_face_encoding], face_encoding)
if match[0]:
name = "Aleksey"
print("I see someone named {}!".format(name))
Full file atached facerec_on_raspberry_pi.py.txt
In this:
Roman_image = face_recognition.load_image_file("photo2.jpg")
Roman_face_encoding = face_recognition.face_encodings(Roman_image)
Are you sure any faces were detected in that photo? It looks like Roman_face_encoding array is possibly empty and causing the error later.
@ageitgey I am getting this error , tried to resolve by looking some solution mentioned on web but could'nt make it work :
Traceback (most recent call last): File "face_rec_example.py", line 37, in results = face_recognition.compare_faces(known_faces, face_encoding, TOLERANCE) File "/home/shubham-sakha/venv/lib/python3.6/site-packages/face_recognition/api.py", line 226, in compare_faces return list(face_distance(known_face_encodings, face_encoding_to_check) <= tolerance) File "/home/shubham-sakha/venv/lib/python3.6/site-packages/face_recognition/api.py", line 75, in face_distance return np.linalg.norm(face_encodings - face_to_compare, axis=1)
**ValueError: operands could not be broadcast together with shapes (9,) (128, code is Code is followingg:- `import face_recognition import os import cv2
KNOWN_FACES_DIR = "known_faces" UNKNOWN_FACES_DIR = "unknown_faces" TOLERANCE = 0.6 FRAME_THICKNESS = 3 FONT_THICKNESS = 2 MODEL = "cnn" #hog for cpu, cnn works slow on cpu
print("Loading known faces")
known_faces = [] known_names = []
for name in os.listdir(KNOWN_FACES_DIR): for filename in os.listdir(f"{KNOWN_FACES_DIR}/{name}"): image = face_recognition.load_image_file(f"{KNOWN_FACES_DIR}/{name}/{filename}")
encoding = face_recognition.face_encodings(image)[0]
encoding = face_recognition.face_encodings(image) known_faces.append(encoding)
print(known_faces)
known_names.append(name) print(known_names)
print("processing unknown faces ")
for filename in os.listdir(UNKNOWN_FACES_DIR): print(filename) image = face_recognition.load_image_file(f"{UNKNOWN_FACES_DIR}/{filename}") locaations = face_recognition.face_locations(image, model=MODEL) encodings = face_recognition.face_encodings(image, locaations) image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
for face_encoding, face_location in zip(encodings, locaations): results = face_recognition.compare_faces(known_faces, face_encoding, TOLERANCE) print(results) match = None if True in results: match = known_names[results.index(True)] print(f"Match Found : {match}")
top_left = (face_location[3], face_location[0])
bottom_right = (face_location[1], face_location[2])
color = [0, 255, 0]
cv2.rectangle(image, top_left, bottom_right, color, FRAME_THICKNESS)
top_left = (face_location[3], face_location[2])
bottom_right = (face_location[1], face_location[2]+22)
cv2.rectangle(image, top_left, bottom_right, color, cv2.FILLED)
cv2.putText(image, match, (face_location[2]+15), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (200,200,200), FONT_THICKNESS)
cv2.imshow(filename, image) cv2.waitKey(0) cv2.destroyWindow(filename)`
This is not even your code this is from sentdex on Youtube stop lying
This is not even your code this is from sentdex on Youtube stop lying
@nikhilkharade
yes bro .It is from sentdex.After his video i tried to implement but got this error. Don't come to conclusion without knowing anything. nowhere i have mentioned this is my code.
i even posted this error on his youtube comment section. when i googled about this error i came to this page where several people are trying to resolve.
I have a quick solution for that
the problem is that you are trying to match your unknown encoded image with a list that contains encoded known image, that means you are comparing the encoded image with a list, not with an image.
One possible solution is to use a for loop that loops over all the encoded known-face image and compare it with your unknown encoded image:
So the code could be something like this:
for face_encoding, face_location in zip(encoding,locations):
print(len(known_face))
for i in range(0,len(known_face)): #loops through each encoded known_face
result=face_recognition.compare_faces(known_face[i],face_encoding,tolerance=0.6)
match=None
if True in result:
match=known_names[i]
print("Match found:",match)
top_left=(face_location[3],face_location[0])
bottom_right=(face_location[1],face_location[2])
color=[0,255,0]
cv2.rectangle(image,top_left,bottom_right,color,frame_tickness)
top_left=(face_location[3],face_location[2])
bottom_right=(face_location[1],face_location[2]+22)
cv2.rectangle(image,top_left,bottom_right,color,cv2.FILLED)
cv2.putText(image, match,(face_location[3]+10,face_location[2]+15),cv2.FONT_HERSHEY_COMPLEX,0.5,(200,200,200),font_thickness)
@B-0F @DataActivator
Hope it helps!
I was getting a similar error and I solved it with a little change in the code. The problem was actually in the part where I add a new image to the already known faces. Change (known_names.append in 5th line)
img = face_recognition.load_image_file(file_stream)
# Get face encodings for faces in the uploaded image
unknown_face_encodings = face_recognition.face_encodings(img)
if len(unknown_face_encodings) > 0:
known_faces.append(unknown_face_encodings)
known_names.append(file_name)
to
img = face_recognition.load_image_file(file_stream)
# Get face encodings for faces in the uploaded image
unknown_face_encodings = face_recognition.face_encodings(img)
if len(unknown_face_encodings) > 0:
known_faces.append(unknown_face_encodings[0])
known_names.append(file_name)
Hope this helps someone :)
I have a quick solution for that
the problem is that you are trying to match your unknown encoded image with a list that contains encoded known image, that means you are comparing the encoded image with a list, not with an image.
One possible solution is to use a for loop that loops over all the encoded known-face image and compare it with your unknown encoded image:
So the code could be something like this:
for face_encoding, face_location in zip(encoding,locations):
print(len(known_face)) for i in range(0,len(known_face)): #loops through each encoded known_face result=face_recognition.compare_faces(known_face[i],face_encoding,tolerance=0.6) match=None if True in result: match=known_names[i] print("Match found:",match) top_left=(face_location[3],face_location[0]) bottom_right=(face_location[1],face_location[2]) color=[0,255,0] cv2.rectangle(image,top_left,bottom_right,color,frame_tickness) top_left=(face_location[3],face_location[2]) bottom_right=(face_location[1],face_location[2]+22) cv2.rectangle(image,top_left,bottom_right,color,cv2.FILLED) cv2.putText(image, match,(face_location[3]+10,face_location[2]+15),cv2.FONT_HERSHEY_COMPLEX,0.5,(200,200,200),font_thickness)
THanks it helped
@dipanshi08 @iamsandeepprasad @meanOtaku
Hello Guys, I am getting same error as above , I hope you could help me on this!!!
Code =
def facedect(loc): cam = cv2.VideoCapture(0) #capture Image s, img = cam.read() #read Image File if s: #Seach file Image File BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(file))) MEDIA_ROOT = os.path.join(BASE_DIR, 'FaceBank')
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]
#Face Detection
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)
#comparing images Files
check = face_recognition.compare_faces(face_1_face_encoding, face_encodings ,tolerance=0.6)
print(check)
if check[0]:
return True
else:
return False
I have similar project and I am getting same error :(
-- coding: utf-8 --
""" Created on Thu Jun 24 14:55:56 2021
@author: ELİF """
import face_recognition from PIL import Image, ImageDraw
Load a sample picture and learn how to recognize it.
annem_image= face_recognition.load_image_file("C:/Users/EMRE/Desktop/codfacerecog-master/codfacerecog-master/recognize/images/annem1.jpg") annem_face_encoding = face_recognition.face_encodings(annem_image) [0]
babam_image= face_recognition.load_image_file("C:/Users/EMRE/Desktop/codfacerecog-master/codfacerecog-master/recognize/images/babam1.jpg") babam_face_encoding = face_recognition.face_encodings(babam_image) [0]
elif_image= face_recognition.load_image_file("C:/Users/EMRE/Desktop/codfacerecog-master/codfacerecog-master/recognize/images/elif1.png") elif_face_encoding = face_recognition.face_encodings(elif_image) [0],
Create arrays of known face encodings and their names
known_face_encodings = [ annem_face_encoding, babam_face_encoding, elif_face_encoding ] known_face_names = [ "ANNEM", "BABAM", "ELİF" ] image = face_recognition.load_image_file("C:/Users/EMRE/Desktop/codfacerecog-master/codfacerecog-master/recognize/images/family.jpg")
Find all the faces and face encodings in the unknown image
face_locations = face_recognition.face_locations(image) face_encodings = face_recognition.face_encodings(image, face_locations)
pil_image = Image.fromarray(image) draw = ImageDraw.Draw(pil_image)
Loop through each face found in the unknown image
for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings): # See if the face is a match for the known face(s) matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
name = "UNKNOWN"
if True in matches:
first_match_index = matches.index(True)
name = known_face_names[first_match_index]
# Draw a box around the face using the Pillow module
draw.rectangle(((left, top), (right, bottom)), outline=(48, 63, 159))
# Draw a label with a name below the face
text_width, text_height = draw.textsize(name)
draw.rectangle(((left, bottom - text_height - 10), (right, bottom)), fill=(48, 63, 159), outline=(48, 63, 159))
draw.text((left + 6, bottom - text_height - 5), name, fill=(255, 255, 255, 0))
Remove the drawing library from memory as per the Pillow docs
del draw
pil_image.show() pil_image
I GOT : return np.linalg.norm(face_encodings - face_to_compare, axis=1)
ValueError: operands could not be broadcast together with shapes (3,) (128,)
I was getting a similar error and I solved it with a little change in the code. The problem was actually in the part where I add a new image to the already known faces. Change (known_names.append in 5th line)
img = face_recognition.load_image_file(file_stream) # Get face encodings for faces in the uploaded image unknown_face_encodings = face_recognition.face_encodings(img) if len(unknown_face_encodings) > 0: known_faces.append(unknown_face_encodings) known_names.append(file_name)to
img = face_recognition.load_image_file(file_stream) # Get face encodings for faces in the uploaded image unknown_face_encodings = face_recognition.face_encodings(img) if len(unknown_face_encodings) > 0: known_faces.append(unknown_face_encodings[0]) known_names.append(file_name)Hope this helps someone :)
Then I get an
Exception has occurred: IndexError list index out of range