isr_interface.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. import base64
  2. import json
  3. import os
  4. import time
  5. import sys
  6. import traceback
  7. os.environ["CUDA_VISIBLE_DEVICES"] = "0"
  8. import tensorflow as tf
  9. MAX_COMPUTE = False
  10. if not MAX_COMPUTE:
  11. # tensorflow 内存设置
  12. try:
  13. gpus = tf.config.list_physical_devices('GPU')
  14. if len(gpus) > 0:
  15. tf.config.experimental.set_virtual_device_configuration(
  16. gpus[0],
  17. [tf.config.experimental.VirtualDeviceConfiguration(memory_limit=1024)])
  18. except:
  19. traceback.print_exc()
  20. # pass
  21. # gpus = tf.config.list_physical_devices('GPU')
  22. # for gpu in gpus: # 如果使用多块GPU时
  23. # tf.config.experimental.set_memory_growth(gpu, True)
  24. os.environ['CUDA_CACHE_MAXSIZE'] = str(2147483648)
  25. os.environ['CUDA_CACHE_DISABLE'] = str(0)
  26. gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.1)
  27. sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))
  28. sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../")
  29. from format_convert import _global
  30. import cv2
  31. import numpy as np
  32. from PIL import Image
  33. from format_convert.utils import log, get_md5_from_bytes, request_post, np2pil, bytes2np, pil2np, get_platform
  34. from isr.post_process import get_seal_part, replace_seal_part
  35. from isr.model import get_tiny_inference_model, seal_model, seal_model_se
  36. from isr.pre_process import count_red_pixel, get_anchors, get_classes, get_colors
  37. from isr.utils import get_best_predict_size, pil_resize, letterbox_image, draw_boxes, adjust_boxes
  38. from flask import Flask, request
  39. tf.compat.v1.disable_eager_execution()
  40. sess1 = tf.compat.v1.Session(graph=tf.Graph())
  41. sess2 = tf.compat.v1.Session(graph=tf.Graph())
  42. def remove_seal(image_np, model):
  43. # inference data
  44. image_seal = image_np
  45. h, w = image_seal.shape[:2]
  46. best_h, best_w = get_best_predict_size(image_seal)
  47. X = np.zeros((1, best_h, best_w, 3))
  48. # resize
  49. image_seal = pil_resize(image_seal, best_h, best_w)
  50. # cv2.imshow("resize", image_seal)
  51. X[0] = image_seal / 255
  52. # predict
  53. with sess2.as_default():
  54. with sess2.graph.as_default():
  55. pred = model.predict(X)
  56. pred = pred[0]*255.
  57. pred = pred.astype(np.uint8)
  58. pred = pil_resize(pred, h, w)
  59. # cv2.imshow("pred", pred)
  60. # cv2.waitKey(0)
  61. return pred
  62. def detect_seal(image_np, model):
  63. image_pil = np2pil(image_np)
  64. # 首先判断红色像素
  65. # if not count_red_pixel(image_np):
  66. # return image_np, [], []
  67. # create image input
  68. h, w = image_np.shape[:2]
  69. # best_h, best_w = get_best_predict_size(image_np, times=32, max_size=1280)
  70. best_h, best_w = 1024, 1024
  71. image_resize = letterbox_image(image_pil, tuple(reversed([best_h, best_w])))
  72. # cv2.imshow("letterbox_image", pil2np(image_resize))
  73. # cv2.waitKey(0)
  74. # image_resize = pil_resize(image_np, best_h, best_w)
  75. # image_resize = image_pil.resize((int(416), int(416)), Image.BICUBIC)
  76. image_resize = np.array(image_resize, dtype='float32')
  77. image_resize = image_resize.astype('float32') / 255.
  78. image_resize = np.expand_dims(image_resize, 0)
  79. # create image shape input
  80. image_shape = np.array([image_pil.size[1], image_pil.size[0]])
  81. image_shape = np.expand_dims(image_shape, 0)
  82. # inference data
  83. with sess1.as_default():
  84. with sess1.graph.as_default():
  85. out_boxes, out_scores, out_classes = model.predict([image_resize, image_shape], steps=1)
  86. if int(out_boxes.shape[0]) == 0:
  87. log("there is no seal!")
  88. return image_np, [], []
  89. else:
  90. log("there are " + str(out_boxes.shape[0]) + " seals!")
  91. out_boxes = out_boxes.astype(np.int32)
  92. out_classes = out_classes.astype(np.int32)
  93. boxes = adjust_boxes(image_pil, out_boxes)
  94. # else:
  95. # boxes = out_boxes
  96. # # draw
  97. # class_names = get_classes(os.path.abspath(os.path.dirname(__file__))+"/yolo_data/my_classes.txt")
  98. # colors = get_colors(len(class_names))
  99. # image_draw = draw_boxes(image_pil, out_boxes, out_classes, out_scores, class_names, colors)
  100. # image_draw = cv2.cvtColor(np.array(image_draw), cv2.COLOR_RGB2BGR)
  101. # cv2.namedWindow('detect', cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO)
  102. # cv2.imshow("detect", image_draw)
  103. # cv2.waitKey(0)
  104. return image_np, boxes, out_classes
  105. def isr(data, isr_yolo_model, isr_model):
  106. log("into isr_interface isr")
  107. try:
  108. img_data = base64.b64decode(data)
  109. img_np = bytes2np(img_data)
  110. _img, boxes, classes = detect_seal(img_np, isr_yolo_model)
  111. if not boxes and not classes:
  112. return {"image": img_np}
  113. part_list = get_seal_part(_img, boxes, classes)
  114. new_part_list = []
  115. for part in part_list:
  116. part_remove = remove_seal(part, isr_model)
  117. new_part_list.append(part_remove)
  118. img_replace = replace_seal_part(img_np, new_part_list, boxes)
  119. return {"image": img_replace}
  120. except TimeoutError:
  121. return {"image": [-5]}
  122. except:
  123. traceback.print_exc()
  124. return {"image": [-1]}
  125. # 接口配置
  126. app = Flask(__name__)
  127. @app.route('/isr', methods=['POST'])
  128. def _isr():
  129. _global._init()
  130. _global.update({"port": globals().get("port")})
  131. start_time = time.time()
  132. log("into isr_interface _isr")
  133. try:
  134. if not request.form:
  135. log("isr no data!")
  136. return json.dumps({"text": str([-9]), "bbox": str([-9])})
  137. data = request.form.get("data")
  138. log("isr_interface get data time" + str(time.time()-start_time))
  139. img_data = base64.b64decode(data)
  140. img_np = bytes2np(img_data)
  141. _md5 = request.form.get("md5")
  142. _global.update({"md5": _md5})
  143. # 初始化模型
  144. isr_yolo_model = globals().get("global_isr_yolo_model")
  145. isr_model = globals().get("global_isr_model")
  146. if isr_model is None or isr_yolo_model is None:
  147. print("=========== init isr model ===========")
  148. isr_yolo_model, isr_model = IsrModels().get_model()
  149. globals().update({"global_isr_yolo_model": isr_yolo_model})
  150. globals().update({"global_isr_model": isr_model})
  151. # 检测印章
  152. _img, boxes, classes = detect_seal(img_np, isr_yolo_model)
  153. # 检测不到,直接返回
  154. if not boxes and not classes:
  155. log("no seal detected! return 1")
  156. return json.dumps({"image": [1]})
  157. else:
  158. log("there are " + str(len(boxes)) + " seals")
  159. # 截取
  160. part_list = get_seal_part(_img, boxes, classes)
  161. # 去除印章
  162. new_part_list = []
  163. for part in part_list:
  164. part_remove = remove_seal(part, isr_model)
  165. new_part_list.append(part_remove)
  166. # 替换
  167. img_replace = replace_seal_part(img_np, new_part_list, boxes)
  168. # numpy转为可序列化的string
  169. success, img_encode = cv2.imencode(".jpg", img_replace)
  170. # numpy -> bytes
  171. img_bytes = img_encode.tobytes()
  172. # bytes -> base64 bytes
  173. img_base64 = base64.b64encode(img_bytes)
  174. # base64 bytes -> string (utf-8)
  175. base64_string = img_base64.decode('utf-8')
  176. return json.dumps({"image": base64_string})
  177. except TimeoutError:
  178. return json.dumps({"image": [-5]})
  179. except:
  180. traceback.print_exc()
  181. return json.dumps({"image": [-1]})
  182. finally:
  183. log("isr interface finish time " + str(time.time()-start_time))
  184. class IsrModels:
  185. def __init__(self):
  186. # python文件所在目录
  187. _dir = os.path.abspath(os.path.dirname(__file__))
  188. # detect
  189. model_path = _dir + "/models/seal_detect_yolo.h5"
  190. anchors = get_anchors(_dir + "/yolo_data/my_anchors.txt")
  191. class_names = get_classes(_dir + "/yolo_data/my_classes.txt")
  192. colors = get_colors(len(class_names))
  193. with sess1.as_default():
  194. with sess1.graph.as_default():
  195. self.isr_yolo_model = get_tiny_inference_model(anchors, len(class_names), weights_path=model_path)
  196. self.isr_yolo_model.load_weights(model_path)
  197. # remove
  198. model_path = _dir + "/models/seal_remove_unet.h5"
  199. with sess2.as_default():
  200. with sess2.graph.as_default():
  201. self.isr_model = seal_model_se(input_shape=(None, None, 3),
  202. output_shape=(None, None, 3))
  203. self.isr_model.load_weights(model_path)
  204. def get_model(self):
  205. return [self.isr_yolo_model, self.isr_model]
  206. def test_isr_model(from_remote=False):
  207. if get_platform() == "Windows":
  208. file_path = "C:/Users/Administrator/Desktop/test_image/error10.jpg"
  209. file_path = "C:\\Users\\Administrator\\Downloads\\1647913696016.jpg"
  210. else:
  211. file_path = "error10.jpg"
  212. with open(file_path, "rb") as f:
  213. file_bytes = f.read()
  214. file_base64 = base64.b64encode(file_bytes)
  215. _md5 = get_md5_from_bytes(file_bytes)[0]
  216. _global._init()
  217. _global.update({"port": 15010, "md5": _md5})
  218. if from_remote:
  219. file_json = {"data": file_base64, "md5": _md5}
  220. # _url = "http://192.168.2.102:18040/isr"
  221. _url = "http://127.0.0.1:18040/isr"
  222. result = json.loads(request_post(_url, file_json))
  223. if type(result.get("image")) == list:
  224. print("result", result)
  225. else:
  226. img = result.get("image")
  227. image_base64 = img.encode("utf-8")
  228. image_bytes = base64.b64decode(image_base64)
  229. buffer = np.frombuffer(image_bytes, dtype=np.uint8)
  230. image_np = cv2.imdecode(buffer, 1)
  231. print(image_np.shape)
  232. else:
  233. isr_yolo_model, isr_model = IsrModels().get_model()
  234. result = isr(file_base64, isr_yolo_model, isr_model)
  235. # print(result)
  236. if type(result.get("image")) == list:
  237. print("result", len(result))
  238. else:
  239. img = result.get("image")
  240. print(img.shape)
  241. cv2.namedWindow('img', cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO)
  242. cv2.imshow("img", img)
  243. cv2.waitKey(0)
  244. # print(result)
  245. if __name__ == "__main__":
  246. for i in range(100):
  247. s_t = time.time()
  248. test_isr_model(from_remote=False)
  249. print("finish test_isr_model", time.time()-s_t)