python - 值错误 ("Tensor %s is not an element of this graph."% obj)

标签 python rest tensorflow keras computer-vision

首先,英语不是我的母语,所以请原谅,如果我表达得不好,请随时纠正我。

我正在制作一个情绪识别系统,该系统使用休息服务从客户端浏览器发送图像。

这是代码:

# hyper-parameters for bounding boxes shape
frame_window = 10
emotion_offsets = (20, 40)

# loading models
face_detection = load_detection_model(detection_model_path)
emotion_classifier = load_model(emotion_model_path, compile=False)
K.clear_session()

# getting input model shapes for inference
emotion_target_size = emotion_classifier.input_shape[1:3]

# starting lists for calculating modes
emotion_window = []

函数:

def detect_emotion(self, img):

    # Convert RGB to BGR
    bgr_image = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
    gray_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2GRAY)
    rgb_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2RGB)
    faces = detect_faces(face_detection, gray_image)

    for face_coordinates in faces:

        x1, x2, y1, y2 = apply_offsets(face_coordinates, emotion_offsets)
        gray_face = gray_image[y1:y2, x1:x2]
        try:
            gray_face = cv2.resize(gray_face, (emotion_target_size))
        except:
            continue

        gray_face = preprocess_input(gray_face, True)
        gray_face = np.expand_dims(gray_face, 0)
        gray_face = np.expand_dims(gray_face, -1)
        emotion_classifier._make_predict_function()

        emotion_prediction = emotion_classifier.predict(gray_face)

        emotion_probability = np.max(emotion_prediction)
        emotion_label_arg = np.argmax(emotion_prediction)
        emotion_text = emotion_labels[emotion_label_arg]
        emotion_window.append(emotion_text)

        if len(emotion_window) > frame_window:
            emotion_window.pop(0)
        try:
            emotion_mode = mode(emotion_window)
        except:
            continue

        if emotion_text == 'angry':
            color = emotion_probability * np.asarray((255, 0, 0))
        elif emotion_text == 'sad':
            color = emotion_probability * np.asarray((0, 0, 255))
        elif emotion_text == 'happy':
            color = emotion_probability * np.asarray((255, 255, 0))
        elif emotion_text == 'surprise':
            color = emotion_probability * np.asarray((0, 255, 255))
        else:
            color = emotion_probability * np.asarray((0, 255, 0))

        color = color.astype(int)
        color = color.tolist()

        draw_bounding_box(face_coordinates, rgb_image, color)
        draw_text(face_coordinates, rgb_image, emotion_mode,
                  color, 0, -45, 1, 1)

    img = Image.fromarray(rgb_image)

    return img


I'm facing this error when i run my code using waitress:

    File "c:\users\afgir\documents\pythonprojects\face_reco\venv\lib\site-packages\tensorflow\python\framework\ops.py", line 3569, in _as_graph_element_locked
    raise ValueError("Tensor %s is not an element of this graph." % obj) 
    ValueError: Tensor Tensor("predictions_1/Softmax:0", shape=(?, 7), dtype=float32) is not an element of this graph.

它加载图像并很好地完成所有处理,我很确定错误出现在 emotion_classifier.predict 行中,只是不知道如何修复它。

我已经尝试过 this question 中的两种解决方案但它们都不起作用。

我对 Tensorflow 非常陌生,所以我有点坚持这个。

最佳答案

我只是想了解您的真实环境,但我猜您可能会使用 Keras 和一些Keras 模型来预测情绪。

您的错误消息是由于以下行引起的:

K.clear_session()

来自文档:keras.backend.clear_session() 。 因此,您清除已创建的所有图形,然后尝试运行分类器的 predict(),这样会丢失所有上下文。
因此只需删除这一行即可。

本节是关于 Op 删除的一些代码:
在此任务中,您根本不需要使用tf.Graph()。您只需将 emotion_classifier.predict() 作为一个简单的 Python 方法外部调用,并且使用任何 tensorflow 图:

def detect_emotion(self, img):

    # Convert RGB to BGR
    bgr_image = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
    gray_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2GRAY)
    rgb_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2RGB)
    faces = detect_faces(face_detection, gray_image)

    for face_coordinates in faces:

        x1, x2, y1, y2 = apply_offsets(face_coordinates, emotion_offsets)
        gray_face = gray_image[y1:y2, x1:x2]
        try:
            gray_face = cv2.resize(gray_face, (emotion_target_size))
        except:
            continue

        gray_face = preprocess_input(gray_face, True)
        gray_face = np.expand_dims(gray_face, 0)
        gray_face = np.expand_dims(gray_face, -1)
        emotion_classifier._make_predict_function()

        emotion_prediction = emotion_classifier.predict(gray_face)

        emotion_probability = np.max(emotion_prediction)
        emotion_label_arg = np.argmax(emotion_prediction)
        emotion_text = emotion_labels[emotion_label_arg]
        emotion_window.append(emotion_text)

        if len(emotion_window) > frame_window:
            emotion_window.pop(0)
        try:
            emotion_mode = mode(emotion_window)
        except:
            continue

        if emotion_text == 'angry':
            color = emotion_probability * np.asarray((255, 0, 0))
        elif emotion_text == 'sad':
            color = emotion_probability * np.asarray((0, 0, 255))
        elif emotion_text == 'happy':
            color = emotion_probability * np.asarray((255, 255, 0))
        elif emotion_text == 'surprise':
            color = emotion_probability * np.asarray((0, 255, 255))
        else:
            color = emotion_probability * np.asarray((0, 255, 0))

        color = color.astype(int)
        color = color.tolist()

        draw_bounding_box(face_coordinates, rgb_image, color)
        draw_text(face_coordinates, rgb_image, emotion_mode,
                  color, 0, -45, 1, 1)

    img = Image.fromarray(rgb_image)

    return img

关于python - 值错误 ("Tensor %s is not an element of this graph."% obj),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53421233/

相关文章:

rest - OpenAPI 3 -- 属性在写入时是可选的,但在读取时是必需的

python - Tensorflow:尝试迁移学习时出错:无效的 JPEG 数据或裁剪窗口

python - 如何实现暂停(和更多)功能?

python - 无法为 python 3.9 安装 pip3

python - pygame中面向对象的圆形按钮?

当我们使用列表理解时,Python 会并行创建对象

rest - wso2esb - 来自 HTTP 请求的冗余 header

java - REST API 和多态性

python - 如何使用注意力机制在多层双向中操纵编码器状态

python - 在 Keras 功能 API 中合并两个模型