idc_interface.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. import base64
  2. import copy
  3. import json
  4. import os
  5. import time
  6. import sys
  7. import traceback
  8. from glob import glob
  9. os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
  10. sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../")
  11. from format_convert import _global
  12. import cv2
  13. import numpy as np
  14. from PIL import Image
  15. # from idc.model import direction_model
  16. from format_convert.utils import log, get_md5_from_bytes, request_post, np2pil, bytes2np, pil2np, pil_resize, np2bytes
  17. import tensorflow as tf
  18. from flask import Flask, request
  19. tf.compat.v1.disable_eager_execution()
  20. sess = tf.compat.v1.Session(graph=tf.Graph())
  21. image_shape = (640, 640)
  22. def adjust_direction(image_np, model, if_return_angle=False):
  23. # 4个方向
  24. cls_num = 4
  25. # 构建数据
  26. origin_image = copy.deepcopy(image_np)
  27. # image_np = pil_resize(image_np, image_shape[0], image_shape[1])
  28. X = np.expand_dims(np.array(image_np), 0)
  29. # 预测
  30. with sess.as_default():
  31. with sess.graph.as_default():
  32. pred = model.predict(X, batch_size=1)
  33. pred = pred.astype(np.float64)
  34. pred = np.argmax(pred[0])
  35. # 根据分类计算角度
  36. angle = int(360 - pred*int((360/cls_num)))
  37. if if_return_angle:
  38. return angle
  39. else:
  40. # 根据角度旋转
  41. image_pil = Image.fromarray(origin_image)
  42. image_rotate = np.array(image_pil.rotate(angle, expand=1))
  43. return image_rotate
  44. def idc(data, model):
  45. log("into idc_interface idc")
  46. try:
  47. # start_time = time.time()
  48. img_data = base64.b64decode(data)
  49. img_np = bytes2np(img_data)
  50. angle = adjust_direction(img_np, model, if_return_angle=True)
  51. # print(time.time()-start_time)
  52. return {"angle": angle}
  53. except TimeoutError:
  54. return {"angle": [-5]}
  55. except:
  56. traceback.print_exc()
  57. return {"angle": [-1]}
  58. # 接口配置
  59. app = Flask(__name__)
  60. @app.route('/idc', methods=['POST'])
  61. def _idc():
  62. _global._init()
  63. _global.update({"port": globals().get("port")})
  64. start_time = time.time()
  65. log("into idc_interface _idc")
  66. try:
  67. if not request.form:
  68. log("idc no data!")
  69. return json.dumps({"text": str([-9]), "bbox": str([-9])})
  70. data = request.form.get("data")
  71. log("idc_interface get data time" + str(time.time()-start_time))
  72. img_data = base64.b64decode(data)
  73. img_np = bytes2np(img_data)
  74. _md5 = request.form.get("md5")
  75. _global.update({"md5": _md5})
  76. idc_model = globals().get("global_idc_model")
  77. if idc_model is None:
  78. print("=========== init idc model ===========")
  79. idc_model = IdcModels().get_model()
  80. globals().update({"global_idc_model": idc_model})
  81. angle = adjust_direction(img_np, idc_model, if_return_angle=True)
  82. return json.dumps({"angle": angle})
  83. except TimeoutError:
  84. return json.dumps({"angle": str([-5])})
  85. except:
  86. traceback.print_exc()
  87. return json.dumps({"angle": str([-1])})
  88. finally:
  89. log("idc interface finish time " + str(time.time()-start_time))
  90. # class IdcModels:
  91. # def __init__(self):
  92. # # python文件所在目录
  93. # _dir = os.path.abspath(os.path.dirname(__file__))
  94. #
  95. # # detect
  96. # model_path = _dir + "/models/model.h5"
  97. # with sess.as_default():
  98. # with sess.graph.as_default():
  99. # self.model = direction_model(input_shape=(image_shape[0], image_shape[1], 3),
  100. # output_shape=4)
  101. # self.model.load_weights(model_path)
  102. #
  103. # def get_model(self):
  104. # return self.model
  105. def test_idc_model(from_remote=False):
  106. idc_model = IdcModels().get_model()
  107. paths = glob("C:/Users/Administrator/Desktop/test_image/*")
  108. # file_path = "C:/Users/Administrator/Desktop/test_image/error10.jpg"
  109. for file_path in paths:
  110. img_np = cv2.imread(file_path)
  111. img_np = pil_resize(img_np, 640, 640)
  112. print(img_np.shape)
  113. file_bytes = np2bytes(img_np)
  114. file_base64 = base64.b64encode(file_bytes)
  115. _md5 = get_md5_from_bytes(file_bytes)[0]
  116. _global._init()
  117. _global.update({"port": 15010, "md5": _md5})
  118. if from_remote:
  119. file_json = {"data": file_base64, "md5": _md5}
  120. # _url = "http://192.168.2.102:17000/ocr"
  121. _url = "http://127.0.0.1:17000/ocr"
  122. print(json.loads(request_post(_url, file_json)))
  123. else:
  124. result = idc(file_base64, idc_model)
  125. # print(result)
  126. if type(result.get("angle")) == list:
  127. print(result)
  128. else:
  129. angle = result.get("angle")
  130. img = Image.fromarray(img_np)
  131. img = np.array(img.rotate(angle, expand=1))
  132. print(img.shape)
  133. cv2.namedWindow('img', cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO)
  134. cv2.imshow("img", img)
  135. cv2.waitKey(0)
  136. # print(result)
  137. if __name__ == "__main__":
  138. test_idc_model()