Python 试图将视频导入我的cv2人脸情感识别代码时出现“获取名称未定义”错误

Python 试图将视频导入我的cv2人脸情感识别代码时出现“获取名称未定义”错误,python,opencv,Python,Opencv,我正在尝试使用opencv制作一个人脸情感识别项目。我能够用我的网络摄像头使用和预测情绪(代码:cv2.VideoCapture(0))。但出于演示目的,我想将网络摄像头更改为特定的mp4视频。但是我犯了一个错误。这是我的密码: path = "haarcascade_frontalface_default.xml" font_scale = 1.5 font = cv2.FONT_HERSHEY_PLAIN #set the rectangle background to

我正在尝试使用opencv制作一个人脸情感识别项目。我能够用我的网络摄像头使用和预测情绪(代码:cv2.VideoCapture(0))。但出于演示目的,我想将网络摄像头更改为特定的mp4视频。但是我犯了一个错误。这是我的密码:

path = "haarcascade_frontalface_default.xml"
font_scale = 1.5
font = cv2.FONT_HERSHEY_PLAIN

#set the rectangle background to white
rectangle_bgr = (255, 255, 255)
# make a black image
img = np.zeros((500, 500))
#set some text
text = "VİDGA Projesi"
#get the width and height of the text box
(text_width, text_height) = cv2.getTextSize(text, font, fontScale=font_scale, thickness=1)[0]
#set the text start position
text_offset_x = 10
text_offset_y = img.shape[0] - 25
#make the coords of the box with a small padding of two pixels
box_coords = ((text_offset_x, text_offset_y), (text_offset_x + text_width + 2, text_offset_y - text_height -2))
cv2.rectangle(img, box_coords[0], box_coords[1], rectangle_bgr, cv2.FILLED)
cv2.putText(img, text, (text_offset_x, text_offset_y), font, fontScale=font_scale, color= (0,0,0), thickness=1)

cap = cv2.VideoCapture("sample.mp4")
#Check if the webcam is opened correctly
#if not cap.isOpened():
    #cap = cv2.VideoCapture(0)
if not cap.isOpened():
    raise IOError("Cannot open video")
    
while True:
    ret, frame = cap.read()
    #eye_Cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml')
    faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
    
    if ret == True:
    
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        #print(faceCascade.empty())
        faces = faceCascade.detectMultiScale(gray,1.1,4)
        for x,y,w,h in faces:
            print("Alındı.")
            roi_gray = gray[y:y+h, x:x+w]
            roi_color = frame[y:y+h, x:x+w]
            cv2.rectangle(frame, (x,y), (x+w, y+h), (255, 0, 0), 2)
            facess = faceCascade.detectMultiScale(roi_gray)
            if len(facess) == 0:
                print("Face not detected")
            else: 
                for(ex,ey,ew,eh) in facess:
                    face_roi = roi_color[ey: ey+eh, ex: ex+ew] ##cropping the face
                
    graytemp = cv2.cvtColor(face_roi, cv2.COLOR_BGR2GRAY)
    final_image = cv2.resize(graytemp, (48,48))
    final_image = np.expand_dims(final_image, axis =0) #add third dimension
    final_image = np.expand_dims(final_image, axis =0) #add fourth dimension
    final_image = final_image/255.0 # normalization
    dataa = torch.from_numpy(final_image)
    dataa = dataa.type(torch.FloatTensor)
    dataa = dataa.to(device)
    outputs = net(dataa)
    Pred = F.softmax(outputs, dim=1)
    Predictions = torch.argmax(Pred).item()
    print(Predictions)
这就是我得到的错误:

    ---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-5-d57dc2ffd8f1> in <module>
     48                     face_roi = roi_color[ey: ey+eh, ex: ex+ew] ##cropping the face
     49 
---> 50     graytemp = cv2.cvtColor(face_roi, cv2.COLOR_BGR2GRAY)
     51     final_image = cv2.resize(graytemp, (48,48))
     52     final_image = np.expand_dims(final_image, axis =0) #add third dimension

NameError: name 'face_roi' is not defined
---------------------------------------------------------------------------
NameError回溯(最近一次呼叫上次)
在里面
48面部roi=roi颜色[ey:ey+eh,ex:ex+ew]##裁剪面部
49
--->50 graytemp=cv2.CVT颜色(面部\u roi,cv2.COLOR\u BGR2GRAY)
51最终图像=cv2。调整大小(灰度,(48,48))
52最终图像=np。展开尺寸(最终图像,轴=0)#添加三维
名称错误:未定义名称“face\u roi”

当我将cv2.VideoCapture(“sample.mp4”)更改为cv2.VideoCapture(0)时,一切都像一个符咒一样工作。请帮助我:)

如果ret==True块中的
else
块中只定义了
face\u roi
变量。如果成功检测到一次
face\u roi
,则一切正常,因为即使在未能重新定义变量的循环中,也会更早地定义变量

只需将
while
循环的最后一部分缩进
else
块(以及
else
块内的
for
循环):


你为什么不用deepface?运行以下代码段,它将处理所有问题

#!pip install deepface
from deepface import DeepFace
DeepFace.stream()

请注意,在此之前,
face\u roi
仅在最里面的
else
中分配。如果
ret
不是真的,那么您将始终遇到该错误好的,这就是错误的原因?但是你能帮我修复它吗?嗯,“修复”是指在执行代码的这一部分时,始终确保你有面子。所以要么是一个默认值,要么将代码移到另一个值中
#!pip install deepface
from deepface import DeepFace
DeepFace.stream()