import base64 import json import logging import os import sys import time import traceback from glob import glob import cv2 import numpy as np os.environ["CUDA_VISIBLE_DEVICES"] = "-1" import tensorflow as tf from flask import Flask, request sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../") from captcha_classify.inference_classify import classify from captcha_classify.model import cnn_net_tiny from utils import pil_resize, np2bytes, request_post, bytes2np, base64_decode, image_to_str, str_to_image logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') tf.compat.v1.disable_eager_execution() sess = tf.compat.v1.Session(graph=tf.Graph()) package_dir = os.path.abspath(os.path.dirname(__file__)) model_path = package_dir + "/models/e262-acc0.81-classify.h5" image_shape = (128, 128, 1) class_num = 3 # 接口配置 app = Flask(__name__) @app.route('/cac', methods=['POST']) def cac(): start_time = time.time() logging.info("into cac_interface cac") try: # 接收网络数据 if not request.form: logging.info("cac no data!") return json.dumps({"data": "", "success": 0}) data = request.form.get("data") logging.info("cac_interface get data time" + str(time.time()-start_time)) # 加载模型 cac_model = globals().get("global_cac_model") if cac_model is None: print("=========== init cac model ===========") cac_model = CacModels().get_model() globals().update({"global_cac_model": cac_model}) # 数据转换 data = base64_decode(data) image_np = bytes2np(data) # 预测 result = classify(image_np, cac_model, sess) logging.info('cac result ' + str(result)) if result is None: return json.dumps({"data": "", "success": 0}) return json.dumps({"data": result, "success": 1}) except: traceback.print_exc() return json.dumps({"data": "", "success": 0}) finally: logging.info("cac interface finish time " + str(time.time()-start_time)) class CacModels: def __init__(self): with sess.as_default(): with sess.graph.as_default(): self.model = cnn_net_tiny(input_shape=image_shape, output_shape=class_num) self.model.load_weights(model_path) def get_model(self): return self.model def test_cac_model(from_remote=True): paths = glob("D:/Project/captcha/data/chinese/1.jpg") for file_path in paths: img_np = cv2.imread(file_path) h, w = img_np.shape[:2] file_bytes = np2bytes(img_np) file_base64 = base64.b64encode(file_bytes) if from_remote: file_json = {"data": file_base64} # _url = "http://192.168.2.102:17061/cac" _url = "http://127.0.0.1:17062/cac" result = json.loads(request_post(_url, file_json)) if result.get("success"): result = int(result.get("data")) cv2.imshow("img_np", img_np) print("classify result", result) cv2.waitKey(0) else: print("failed!") if __name__ == "__main__": # app.run(host='127.0.0.1', port=17062, debug=False) test_cac_model()