我正在编写一些用于人脸识别的代码。我正在尝试将我拥有的 csv 文件合并到一个程序将读取的文件中,一旦它的准确度级别至少为 0.8 或更高,它将扫描我的脸并确定我的表情。运行程序时,它不断抱怨变量“捕获”。我曾尝试更改名称,但无济于事。我不确定确切的问题是什么,有人可以帮助我朝正确的方向发展吗?
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("D:\Ezequiel Soler\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))
# 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()
# initial values
if __name__ == "__main__":
main()
while True:
# 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'):
capture.release()
cv2.destroyAllWindows()
break
# display the frame
cv2.imshow("Expression Prediction", frame)
# release the memory
capture.release()
cv2.destroyAllWindows()
exit(0)
答案 0 :(得分:0)
从主函数中删除以下代码并将其放在 while 循环之后的第一行。
capture = cv2.VideoCapture(0)
if capture.isOpened() is False:
print("Camera Error, please check your camera @_@")
exit()
答案 1 :(得分:0)
capture
变量仅在 main()
函数的范围内定义。
为了在您的 if __name__ == "__main__":
块中调用它,您需要从 main()
函数中返回它。
答案 2 :(得分:0)
主要问题是由于这组代码
capture = cv2.VideoCapture(0)
if capture.isOpened() is False:
print("Camera Error, please check your camera @_@")
exit()
将其放在 while 代码之后。
答案 3 :(得分:0)
尽管我对 OpenCV 有点陌生,但您发布的代码似乎给出了基本的 NameError。该错误在某种程度上是不言自明的,因为它几乎仅意味着您所引用的对象不存在。
查看您的代码,您似乎在定义之前使用了“相机”,因此混淆了编译器:
capture = cv2.VideoCapture(0)
if capture.isOpened() is False:
print("Camera Error, please check your camera @_@")
exit()
我建议将它放在 main 中的“while True”循环下,因为它似乎只在那里可用。如果您希望它保持在当前位置,您也可以尝试使用 global。