NameError: name 'capture' is not defined

问题描述 投票:0回答:5

我正在编写一些人脸识别代码。我正在尝试将我拥有的 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)
python opencv jupyter-notebook anaconda random-forest
5个回答
0
投票

从 main 函数中删除以下代码并将其放在 while 循环之后的第一行。

capture = cv2.VideoCapture(0)
    if capture.isOpened() is False:
        print("Camera Error, please check your camera @_@")
        exit()

0
投票

capture
变量只定义在
main()
函数的范围内。 为了在您的
if __name__ == "__main__":
块中调用它,您需要从
main()
函数返回它。


0
投票

主要问题是由于这组代码引起的

capture = cv2.VideoCapture(0)
    if capture.isOpened() is False:
        print("Camera Error, please check your camera @_@")
        exit()

将其放在 while 代码之后。


0
投票

虽然我对 OpenCV 有点陌生,但您发布的代码似乎给出了一个基本的 NameError。这个错误有点不言自明,因为它几乎只意味着你引用的对象不存在。

查看您的代码,您似乎在定义它之前使用了“相机”,因此使编译器感到困惑:

capture = cv2.VideoCapture(0)
    if capture.isOpened() is False:
        print("Camera Error, please check your camera @_@")
        exit()

我建议将它放在 main 中的“while True”循环下,因为它似乎只在那里可用。如果您希望它保留在当前位置,您也可以尝试使用 global


0
投票

错误意味着 Civit Ai 或文件所在的位置, 路径已更改\已被阻止\或服务器已关闭\文件已被删除。

© www.soinside.com 2019 - 2024. All rights reserved.