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" sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../") import tensorflow as tf from flask import Flask, request from border_recognize.model import u_net_drag from border_recognize.inference_drag import recognize from utils import pil_resize, np2bytes, request_post, bytes2np 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/drag_f1_0.42.h5" image_shape = (128, 256, 3) # 接口配置 app = Flask(__name__) @app.route('/bdr', methods=['POST']) def bdr(): start_time = time.time() logging.info("into bdr_interface bdr") try: # 接收网络数据 if not request.form: logging.info("bdr no data!") return json.dumps({"data": "", "success": 0}) data = request.form.get("data") logging.info("bdr_interface get data time" + str(time.time()-start_time)) # 加载模型 bdr_model = globals().get("global_bdr_model") if bdr_model is None: print("=========== init bdr model ===========") bdr_model = BdrModels().get_model() globals().update({"global_bdr_model": bdr_model}) # 数据转换 data = base64.b64decode(data) image_np = bytes2np(data) # 预测 w = recognize(image_np, bdr_model, sess) return json.dumps({"data": w, "success": 1}) except: traceback.print_exc() return json.dumps({"data": "", "success": 0}) finally: logging.info("bdr interface finish time " + str(time.time()-start_time)) class BdrModels: def __init__(self): with sess.as_default(): with sess.graph.as_default(): self.model = u_net_drag(input_shape=image_shape) self.model.load_weights(model_path) def get_model(self): return self.model def test_bdr_model(from_remote=True): paths = glob("D:/Project/captcha/data/test/yolo_18.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:17000/ocr" _url = "http://127.0.0.1:17000/bdr" result = json.loads(request_post(_url, file_json)) if result.get("success"): w = int(result.get("data")) print("w", w) img_new = np.concatenate([img_np[:, w:, :], img_np[:, :w, :]], axis=1) cv2.imshow("img_np", img_np) cv2.imshow("img_new", img_new) cv2.waitKey(0) else: print("failed!") if __name__ == "__main__": # app.run(host='127.0.0.1', port=17000, debug=False) test_bdr_model()