Offset Not defined Error

import cv2
import numpy as np
import os
import math

def distance(v1,v2):
return math.sqrt(((v1-v2)**2).sum())

def KNN(train,test,k=5):
dist=[]
for i in range(train.shape[0]):
#get vector and label
ix = train[i,:-1]
iy = train[i,-1]
d = distance(test,ix)
dist.append([d,iy])

# Sort based on distance and get top k
dk = sorted(dist, key = lambda x:x[0])[:k]
labels = np.array(dk)[:-1]

#get frequency of each element
output = np.unique(labels,return_counts=True)

#Getting max frequency and corresponding label
index = np.argmax(output[1])
return output[0][index]

#Initialise Camera
cap = cv2.VideoCapture(0)

#Face Detection
face_cascade = cv2.CascadeClassifier(‘haarcascade_frontalface_alt.xml’)

skip = 0
dataset_path = ‘D:/Java_Projects/Machine Learning/’
face_data = []
labels = []

class_id = 0 #label for given file
names = {} # mapping between id and name

for fx in os.listdir(dataset_path):
if fx.endswith(’.npy’):
names[class_id]=fx[:-4]
print(“loaded” + fx)
data_item = np.load(dataset_path+fx)
face_data.append(data_item)

    target = class_id*np.ones((data_item.shape[0],))
    class_id +=1
    labels.append(target)

face_dataset = np.concatenate(face_data,axis = 0)
face_labels = np.concatenate(labels,axis = 0).reshape((-1,1))

print(face_dataset.shape)
print(face_labels.shape)

trainset = np.concatenate((face_dataset,face_labels),axis=1)
print(trainset.shape)

while True:
ret,frame = cap.read()
if ret == False :
continue

faces = face_cascade.detectMultiScale(frame,1.3,5)

for face in faces:
    x,y,w,h = face

    #Region of Interest
    face_section = frame[y-offset:y+h+offset,x-offset:x+w+offset]
    #face_section = cv2.resize(face_section,(100,100))

    #Predict Label
    out = KNN(trainset,face_section.flatten())

    #Display name on screen and rectangle
    pred_name = names[int(out)]
    cv2.putText(frame,pred_name,(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("frame",frame)

key = cv2.waitKey(1) &0xFF
if key == ord('q'):
    break

cap.release()
cv2.destroyAllWindows()

Sir,
Using the above code, I am getting an error in the following line face_section = frame[y-offset:y+h+offset,x-offset:x+w+offset].
The error is :NameError: name ‘offset’ is not defined.

Please Advise

Hi @rehan123mahajan_da9155725078172c

You haven’t defined the variable offset in your code try setting offset variable in your code as shown in the following snippet of code

Hope this might helps :slight_smile:

1 Like

The offset issue is solved.
Now a new error has shown up on the same code stating.

File “D:/Java_Projects/Machine Learning/face classifier.py”, line 80, in
out = KNN(trainset,face_section.flatten())
File “D:/Java_Projects/Machine Learning/face classifier.py”, line 15, in KNN
d = distance(test,ix)
File “D:/Java_Projects/Machine Learning/face classifier.py”, line 7, in distance
return np.sqrt(((v1-v2)**2).sum())
ValueError: operands could not be broadcast together with shapes (139968,) (30000,)

Hi @rehan123mahajan_da9155725078172c

Un-comment this statement. The error your are facing is due the difference between the shape of vectors as one of the vector is of shape (139968) and another vector of shape (30000). You can’t subtract a vector of (139968) from a vector of shape (30000).

Hope this might helps :slight_smile:

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.