AttributeError: '_thread._local' object has no attribute 'value'

使用flask部署kears代码的时候, 正常情况下代码能够运行, 但是加上flask部署后报错
AttributeError: ‘_thread._local’ object has no attribute ‘value’

解决方法:
重新安装keras和tensorflow

pip install tensorflow ==1.14 

pip install keras==2.2.5 

重新安装完tensorflow 和keras之后运行出现另外一个报错:
Tensor Tensor(“dense_2/Softmax:0”, shape=(?, 192), dtype=float32) is not an element of this graph

解决方法:
加上几行代码

import tensorflow as tf
graph = tf.get_default_graph()
 
global graph
with graph.as_default():

例如将下面的代码:

import base64
import  cv2
from Slient_liveness_detect import *
from flask import Flask
from flask import request
import json
import tensorflow as tf
import os
import numpy as np
# 实例化,可视为固定格式
app = Flask(__name__)

silence_detect = SilenceDetect()

@app.route('/silent_detect', methods = ['POST'])
def silent_detect():
    ret = {}
    try :
        data = request.get_data()
        json_data = json.loads(data.decode("utf-8"))
        # print(json_data)
    except Exception as e1 :
        print("json is not correct!")
        ret["code"] = 1
        ret["result"] = None
        ret["info"] = "json is not correct!"
        return json.dumps(ret,ensure_ascii=False)

    try:
        img_base64 = json_data.get("silent_img")
        if img_base64.startswith("data:image"):
            img_base64 = img_base64.split(',')[1]
        img_b64decode = base64.b64decode(img_base64)  # base64解码
        img_array = np.fromstring(img_b64decode, np.uint8)  # 转换np序列
        img = cv2.imdecode(img_array, cv2.COLOR_BGR2RGB)  # 转换Opencv格式
    except Exception as e2:
        print("picture is not correct!")
        ret["code"] = 1
        ret["result"] = None
        ret["info"] = "picture is not correct!"

        return json.dumps(ret,ensure_ascii=False)

    try:
        img_result = silence_detect.main(img)
        # print("result", img_result)
        img_encode = cv2.imencode('.jpg', img_result)[1]
        image_code = str(base64.b64encode(img_encode))[2:-1]
        ret["code"] = 0
        ret["result"] = str(image_code)
        ret["info"] = "progress is  correct!"
    except Exception as e2:
        print("progress is not correct!")
        ret["code"] = 1
        ret["result"] = None
        ret["info"] = "progress is not correct!"

    return json.dumps(ret, ensure_ascii=False)


if __name__ == '__main__':
    # app.run(host, port, debug, options)
    # 默认值:host="127.0.0.1", port=5000, debug=False
    app.run(host="0.0.0.0", port=5500, debug=False, use_reloader=False)

修改成:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/4/15 5:25 下午
# @Author  : sarah feng
# @File    : app.py
# @Software: win10 Tensorflow1.13.1 python3.6.3

import base64
import  cv2
from Slient_liveness_detect import *
from flask import Flask
from flask import request
import json
import tensorflow as tf
import os
import numpy as np
# 实例化,可视为固定格式
app = Flask(__name__)

graph = tf.get_default_graph()

cur_dir = os.path.dirname(__file__)

silence_detect = SilenceDetect()
# route()方法用于设定路由;类似spring路由配置
@app.route('/detect', methods = ['POST'])
def detect():
    json_data = None
    ret = {}
    try :
        data = request.get_data()
        json_data = json.loads(data.decode("utf-8"))
        # print(json_data)
    except Exception as e1 :
        print("json is not correct!")
        ret["code"] = 1
        ret["result"] = None
        ret["info"] = "json is not correct!"
        return json.dumps(ret,ensure_ascii=False)

    try:
        img_base64 = json_data.get("img")
        if img_base64.startswith("data:image"):
            img_base64 = img_base64.split(',')[1]
        img_b64decode = base64.b64decode(img_base64)  # base64解码
        img_array = np.fromstring(img_b64decode, np.uint8)  # 转换np序列
        img = cv2.imdecode(img_array, cv2.COLOR_BGR2RGB)  # 转换Opencv格式
    except Exception as e2:
        print("picture is not correct!")
        ret["code"] = 1
        ret["result"] = None
        ret["info"] = "picture is not correct!"

        return json.dumps(ret,ensure_ascii=False)

    try:
        img_result = opera_detect.main(img)
        # print("result", img_result)
        img_encode = cv2.imencode('.jpg', img_result)[1]
        image_code = str(base64.b64encode(img_encode))[2:-1]
        ret["code"] = 0
        ret["result"] = str(image_code)
        ret["info"] = "progress is  correct!"
    except Exception as e2:
        print("progress is not correct!")
        ret["code"] = 1
        ret["result"] = None
        ret["info"] = "progress is not correct!"

    return json.dumps(ret, ensure_ascii=False)


@app.route('/silent_detect', methods = ['POST'])
def silent_detect():
    ret = {}
    try :
        data = request.get_data()
        json_data = json.loads(data.decode("utf-8"))
        # print(json_data)
    except Exception as e1 :
        print("json is not correct!")
        ret["code"] = 1
        ret["result"] = None
        ret["info"] = "json is not correct!"
        return json.dumps(ret,ensure_ascii=False)

    try:
        img_base64 = json_data.get("silent_img")
        if img_base64.startswith("data:image"):
            img_base64 = img_base64.split(',')[1]
        img_b64decode = base64.b64decode(img_base64)  # base64解码
        img_array = np.fromstring(img_b64decode, np.uint8)  # 转换np序列
        img = cv2.imdecode(img_array, cv2.COLOR_BGR2RGB)  # 转换Opencv格式
    except Exception as e2:
        print("picture is not correct!")
        ret["code"] = 1
        ret["result"] = None
        ret["info"] = "picture is not correct!"

        return json.dumps(ret,ensure_ascii=False)

    try:
    # print("img", img.shape)
        global graph
        with graph.as_default():
            img_result = silence_detect.main(img)
        # print("result", img_result)
        img_encode = cv2.imencode('.jpg', img_result)[1]
        image_code = str(base64.b64encode(img_encode))[2:-1]
        ret["code"] = 0
        ret["result"] = str(image_code)
        ret["info"] = "progress is  correct!"
    except Exception as e2:
        print("progress is not correct!")
        ret["code"] = 1
        ret["result"] = None
        ret["info"] = "progress is not correct!"

    return json.dumps(ret, ensure_ascii=False)


if __name__ == '__main__':
    # app.run(host, port, debug, options)
    # 默认值:host="127.0.0.1", port=5000, debug=False
    app.run(host="0.0.0.0", port=5500, debug=False, use_reloader=False)

你可能感兴趣的:(AttributeError: '_thread._local' object has no attribute 'value')