ValueError:层顺序从未被调用,因此没有定义的输入

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

我编写了这个精简代码来检测一个人是否戴着口罩,如果没有,则使用 DeepFace 库显示他们的估计年龄和性别。我使用张量流来使用预训练模型 MobileNet v2 并使用 ImageNet 数据集的权重。我正在使用 OpenCV 从网络摄像头捕获实时视频源,并使用 DeepFace 对它返回的帧进行分析。但我在 DeepFace.analyze() 函数中遇到 ValueError 这是代码:

import streamlit as st
import cv2
import numpy as np
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing.image import img_to_array
from tensorflow.keras.applications.mobilenet_v2 import preprocess_input
from deepface import DeepFace

# Load the trained mask detection model
model = load_model("mask_detection_model.h5")

# Load the pre-trained face detection model
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')

# Create a function for real-time mask detection
def detect_mask(frame):
    # Preprocess the frame
    resized_frame = cv2.resize(frame, (128, 128))
    resized_frame = img_to_array(resized_frame)
    resized_frame = preprocess_input(resized_frame)
    resized_frame = np.expand_dims(resized_frame, axis=0)

    # Perform prediction
    predictions = model.predict(resized_frame)
    return predictions

# Streamlit web app
st.title("Real-time Face Mask Detection")

# Open the webcam
cap = cv2.VideoCapture(0)

if not cap.isOpened():
    st.error("Error: Could not open webcam.")

else:
    stframe = st.empty()
    while True:
        ret, frame = cap.read()
        if not ret:
            st.error("Error: Unable to capture frame.")
            break
        
        # Perform mask detection
        predictions = detect_mask(frame)
        label = "Mask" if np.argmax(predictions) == 1 else "No Mask"
        color = (0, 255, 0) if label == "Mask" else (0, 0, 255)

        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(100, 100))
        
        # Display the frame with the label
        for (x, y, w, h) in faces:
            face = frame[y:y + h, x:x + w]

            # Perform mask detection
            predictions = detect_mask(frame)
            label = "Mask" if np.argmax(predictions) == 1 else "No Mask"
            color = (0, 255, 0) if label == "Mask" else (0, 0, 255)

            # If no mask is detected, estimate age and gender
            if label == "No Mask":
                results = DeepFace.analyze(img_path = frame[y:y+h, x:x+w], actions=['age', 'gender'], enforce_detection=False)  #<-- Getting error at this line
                results = results[0]
                age = results['age']
                gender = results['dominant_gender']
                # print(results)
                # print(type(results[0]))

                # Display age and gender estimation
                cv2.putText(frame, f'Age: {age:.1f} years', (x, y - 60), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)
                cv2.putText(frame, f'Gender: {gender}', (x, y - 40), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)

            # Display mask detection result
            cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2)
            cv2.putText(frame, label, (x,y-10), cv2.FONT_HERSHEY_SIMPLEX, 1, color, 2)
        
        # Convert the frame to RGB for Streamlit
        frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        
        # Display the frame using Streamlit
        stframe.image(frame_rgb, channels="RGB", use_column_width=True)
        
        cv2.waitKey(1)

    cap.release()
    cv2.destroyAllWindows()

这是我运行时的错误

streamlit run app.py

File "D:\Machine Learning Projects\Face Mask Detection\.venv\Lib\site-packages\streamlit\runtime\scriptrunner\script_runner.py", line 542, in _run_script
    exec(code, module.__dict__)
File "D:\Machine Learning Projects\Face Mask Detection\app.py", line 63, in <module>
    results = DeepFace.analyze(img_path = frame[y:y+h, x:x+w], actions=['age', 'gender'], enforce_detection=False)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Machine Learning Projects\Face Mask Detection\.venv\Lib\site-packages\deepface\DeepFace.py", line 222, in analyze
    return demography.analyze(
           ^^^^^^^^^^^^^^^^^^^
File "D:\Machine Learning Projects\Face Mask Detection\.venv\Lib\site-packages\deepface\modules\demography.py", line 157, in analyze
    apparent_age = modeling.build_model("Age").predict(img_content)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Machine Learning Projects\Face Mask Detection\.venv\Lib\site-packages\deepface\modules\modeling.py", line 46, in build_model
    model_obj[model_name] = model()
                            ^^^^^^^
File "D:\Machine Learning Projects\Face Mask Detection\.venv\Lib\site-packages\deepface\extendedmodels\Age.py", line 32, in __init__
    self.model = load_model()
                 ^^^^^^^^^^^^
File "D:\Machine Learning Projects\Face Mask Detection\.venv\Lib\site-packages\deepface\extendedmodels\Age.py", line 61, in load_model
    age_model = Model(inputs=model.input, outputs=base_model_output)
                             ^^^^^^^^^^^
File "D:\Machine Learning Projects\Face Mask Detection\.venv\Lib\site-packages\keras\src\ops\operation.py", line 216, in input
    return self._get_node_attribute_at_index(0, "input_tensors", "input")
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Machine Learning Projects\Face Mask Detection\.venv\Lib\site-packages\keras\src\ops\operation.py", line 247, in _get_node_attribute_at_index
    raise ValueError(
ValueError: The layer sequential has never been called and thus has no defined input.

我已经阅读了 DeepFace 的文档,但无法找出导致此错误的可能原因。

请尽快帮忙,我将不胜感激。

python tensorflow keras streamlit deepface
1个回答
0
投票

尝试更改您使用的模型,我也遇到了这个错误,但通过使用除默认模型之外的其他脸部模型来缓解它,尽管在我的情况下我正在验证脸部,目前可用的模型是:

models = [
    "VGG-Face", 
    "Facenet", 
    "Facenet512", 
    "OpenFace", 
    "DeepFace", 
    "DeepID", 
    "ArcFace", 
    "Dlib", 
    "SFace",
    "GhostFaceNet",
    ]

如果模型选项在分析时不可用,您可以通过首先删除已下载的权重来重新加载权重,或者您可以使用 deepface 中的分析功能来使用您想要的自定义模型

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