ValueError: 层序列从未被调用,因此没有定义的输入
我写了一个streamlit代码,用来检测一个人是否戴着口罩。如果没有戴口罩,就会显示他们的估计年龄和性别,这个功能是通过DeepFace库实现的。我使用了tensorflow来调用一个已经训练好的模型,叫做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的文档,但还是无法找到这个错误的可能原因。
请尽快帮我解决这个问题,我会非常感激的。
1 个回答
0
试着换个模型,我之前也遇到过这个错误,但我通过使用其他面部模型解决了这个问题,虽然在我的情况下我是用来验证面孔的。目前可用的模型有:
models = [
"VGG-Face",
"Facenet",
"Facenet512",
"OpenFace",
"DeepFace",
"DeepID",
"ArcFace",
"Dlib",
"SFace",
"GhostFaceNet",
]
如果在分析时没有模型选项,你可以先删除已经下载的权重,然后重新加载权重,或者你可以在deepface的分析功能中尝试使用你想要的自定义模型。