我收到错误:
UnboundLocalError: local variable 'locs' referenced before assignment
我在其他帖子中读到,解决这个问题的方法是在定义函数后使用global locs
。然而,有两个def()
函数中出现了locs =
。我尝试在其中一个def函数下插入global locs
并运行,还运行了在两个函数中都定义了global locs
的代码,但在每种情况下都会收到相同的错误。
追溯:
Traceback (most recent call last):
File "model2.py", line 107, in <module>
main()
File "model2.py", line 94, in main
if not locs:
UnboundLocalError: local variable 'locs' referenced before assignment
相关代码:
def extract_features(img_path):
# global locs #tried it here and got the same error
X_img = face_recognition.load_image_file(img_path)
locs = face_locations(X_img, number_of_times_to_upsample = N_UPSCLAE)
if len(locs) == 0:
return None, None
face_encodings = face_recognition.face_encodings(X_img, known_face_locations=locs)
return face_encodings, locs
def predict_one_image(img_path, clf, labels):
#global locs #tried it here with same error
face_encodings, locs = extract_features(img_path)
if not face_encodings:
return None, None
pred = pd.DataFrame(clf.predict_proba(face_encodings),
columns = labels)
pred = pred.loc[:, COLS]
return pred, locs
print("classifying images in {}".format(input_dir))
for fname in tqdm(os.listdir(input_dir)):
img_path = os.path.join(input_dir, fname)
try:
pred, locs = predict_one_image(img_path, clf, labels)
except:
print("Skipping {}".format(img_path))
if not locs:
continue
locs =
pd.DataFrame(locs, columns = ['top', 'right', 'bottom', 'left'])
df = pd.concat([pred, locs], axis=1)
if __name__ == "__main__":
main()
我是不是把global locs
插错地方了?
问题不在于global
/local
变量,也不在于函数。
这仅仅是因为try/except
块:
try:
pred, locs = predict_one_image(img_path, clf, labels)
except:
print("Skipping {}".format(img_path))
if not locs:
continue
让我们假设predict_one_image
确实引发了一个异常。这意味着pred
和locs
都不会被定义。之后,except
块简单地打印,并且if not locs
将失败。
有两种简单的方法可以解决这个问题。将locs
初始化为None
,以防调用失败:
try:
locs = None
pred, locs = predict_one_image(img_path, clf, labels)
except:
print("Skipping {}".format(img_path))
if not locs:
continue
或者,如果没有定义locs
(正如我从代码中理解的那样(,仅仅因为您想要continue
,就将continue
语句放在except
:中
try:
pred, locs = predict_one_image(img_path, clf, labels)
except:
print("Skipping {}".format(img_path))
continue