What wrong with this code I am getting This Error
Traceback (most recent call last):
File “C:\Users\logic\Desktop\ML\Untitled Folder\face_recognization.py”, line 90, in
out=knn(trainset,face_section.flatten())
File “C:\Users\logic\Desktop\ML\Untitled Folder\face_recognization.py”, line 21, in knn
d=dist(query_x,x[i])
File “C:\Users\logic\Desktop\ML\Untitled Folder\face_recognization.py”, line 9, in dist
return np.sqrt(sum((x1-x2)**2))
ValueError: operands could not be broadc
*********************************************************************************** Code is Here
import numpy as np
import cv2
import os
########## KNN Algorithm for Face Recognization
def dist(x1,x2):
return np.sqrt(sum((x1-x2)**2))
def knn(x,query_x,k=5):
vals=[]
m=x.shape[0]
for i in range(m):
ix=x[i,:-1]
iy=x[i,-1]
d=dist(query_x,x[i])
vals.append([d,iy])
dk=sorted(dist,key=lambda x:x[0][:k])
# Retrieve the labels
labels=np.array(dk)[:,-1]
# Get Fequency fro Each Labels
out=np.unique(labels,return_counts=True)
index=np.argmax(out[1])
return out[0][index]
########################################################
init Camera
cap=cv2.VideoCapture(0)
face_cascade=cv2.CascadeClassifier(‘haarcascade_frontalface_alt.xml’)
skip=0
data_path=’./data/’
face_data=[]
labels=[]
class_id=0 # labels for the gien files
names={} # Mapping Betwwn Ids and Name
for fx in os.listdir(data_path):
if fx.endswith(’.npy’):
names[class_id]=fx[:-4]
print(""+fx)
data_item=np.load(data_path+fx)
face_data.append(data_item)
# Create the labels for the CLass
target =class_id*np.ones((data_item.shape[0],))
class_id+=1
labels.append(target)
face_data=np.concatenate(face_data,axis=0)
face_labels=np.concatenate(labels,axis=0).reshape((-1,1))
print(face_data.shape)
print(face_labels.shape)
trainset=np.concatenate((face_data,face_labels),axis=1)
while True:
ret,frame=cap.read()
if ret==False:
continue
print(frame)
faces=face_cascade.detectMultiScale(frame,1.3,5)
print (faces)
for face in faces:
print("LOop")
x,y,w,h=face
offset=10
face_section=frame[y-offset:y+offset+h,x-offset:x+offset+w]
face_section=cv2.resize(face_section,(100,100))
out=knn(trainset,face_section.flatten())
print(out)
# Display Name
pred=names[int(out)]
print(pred)
cv2.putText(frame,pred,(x,y-10),cv2.FONT_HERSHEY_SIMPLEX,1,(255,0,0),2,cv2.LINE_AA)
cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,255),2)
cv2.imshow("Faces",frame)
key_pressed=cv2.waitKey(1) & 0xff
if key_pressed==ord('q'): # ord return the ASCII value
break
cap.release()
cv2.destroyAllWindows()