我正在编写一些用于人脸识别的代码。我正在尝试将我拥有的 csv 文件合并到一个程序将读取的文件中,一旦它的准确度级别至少为 0.8 或更高,它将扫描我的脸并确定我的表情。运行程序时,它会抱怨变量“sc”。在我遇到变量“捕获”问题之前,但我能够解决这个问题,现在我遇到了这个新错误,而且我不习惯使用随机森林,所以有人可以帮我吗?
import os
import pandas as pd
from os import path
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
import variable_record
import cv2
import face_recognition
import numpy
os.chdir("../csv_files/")
def file_combination():
extension = 'csv'
all_filenames = [i for i in glob.glob('*.{}'.format(extension))]
combined_csv = pd.concat([pd.read_csv(f) for f in all_filenames])
combined_csv.to_csv("combined_csv.csv", index=False, encoding='utf-8')
print("Combination is finished")
def create_file():
print("Prepare for csv files combination...")
# check whether the combined file is existed
is_existed = path.exists("combined_csv.csv")
# ask user whether he/she want to renew the file if the file is already existed
if is_existed:
renew = input("The file is already existed, do you renew the file? (Y/N) ")
if renew.upper() == 'Y':
os.remove("combined_csv.csv")
file_combination()
else:
print("Program is ended.")
exit(0)
else:
file_combination()
print("--------------------------------------------")
def main():
create_file()
# import dataset
dataSet = pd.read_csv("combined_csv.csv")
# preparing data for training
X = dataSet.iloc[:, 0:7].values
y = dataSet.iloc[:, 7].values
# divide data into training data and test data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
# scaling features
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
# train the data
classifier = RandomForestClassifier(n_estimators=50)
classifier.fit(X_train, y_train)
y_pred = classifier.predict(X_test)
print("Accuracy: ", accuracy_score(y_test, y_pred))
if __name__ == "__main__":
main()
while True:
# turn on the webcam and check the status
capture = cv2.VideoCapture(0)
if capture.isOpened() is False:
print("Camera Error, please check your camera @_@")
exit()
# change the BGR frame to gray frame
ret, frame = capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# use face_recognition library to locate the landmarks
face_marks = face_recognition.face_landmarks(gray, None, "large")
if face_marks.__len__() != 0:
# calculate EAR, MAR, PUC, and MOE
L_EAR = variable_record.cal_EAR(face_marks[0]["left_eye"])
R_EAR = variable_record.cal_EAR(face_marks[0]["right_eye"])
MAR = variable_record.cal_MAR(face_marks[0]["top_lip"], face_marks[0]["bottom_lip"])
PUC = variable_record.cal_PUC(face_marks[0]["left_eye"])
EBA = variable_record.cal_EBA(face_marks[0]["right_eyebrow"])
CAR = variable_record.cal_CAR(face_marks[0]["chin"])
MOE = MAR / L_EAR
predict_data = numpy.array([[L_EAR, R_EAR, MAR, PUC, MOE, EBA, CAR]])
predict_data = sc.transform(predict_data)
expression = classifier.predict(predict_data)
# transfer expression value to english
if expression == 1:
expression = "Neutral"
elif expression == 2:
expression = "Happiness"
elif expression == 3:
expression = "Sadness"
elif expression == 4:
expression = "Fear"
elif expression == 5:
expression = "Angry"
elif expression == 6:
expression = "Surprise"
else:
expression = "Other"
print(expression)
# rectangle the face
face_point = face_recognition.face_locations(gray)
for pts in face_point:
cv2.rectangle(frame, (pts[3], pts[0]), (pts[1], pts[2]), (0, 255, 0), 2)
# show the result on the frame
cv2.putText(frame, expression, (pts[3], pts[0]), cv2.FONT_HERSHEY_DUPLEX, 1.0, (0, 255, 0), 1)
# press q to exit the loop
if cv2.waitKey(1) & 0xff == ord('q'):
break
# display the frame
cv2.imshow("Expression Prediction", frame)
# release the memory
capture.release()
cv2.destroyAllWindows()
exit(0)
答案 0 :(得分:1)
正如评论中所指出的,当您调用转换时 sc 超出了范围。 您可以删除 main mentod 并将所有逻辑放在外面,或者从 main 函数返回 sc。
像这样:
...
y_pred = classifier.predict(X_test)
print("Accuracy: ", accuracy_score(y_test, y_pred))
return sc
if __name__ == "__main__":
sc = main()
....