otr_interface.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. import base64
  2. import json
  3. import multiprocessing as mp
  4. import os
  5. # os.environ['TF_XLA_FLAGS'] = '--tf_xla_cpu_global_jit'
  6. import sys
  7. sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../")
  8. import time
  9. import traceback
  10. from multiprocessing.context import Process
  11. import multiprocessing
  12. import logging
  13. # from table_line import *
  14. import cv2
  15. import numpy as np
  16. import tensorflow as tf
  17. from flask import Flask, request
  18. from format_convert.utils import request_post, judge_error_code, get_intranet_ip, log, get_md5_from_bytes
  19. from otr.table_line import get_best_predict_size, table_line, get_points, get_split_line, get_points_row, \
  20. get_points_col, \
  21. delete_close_points, fix_outline, get_bbox, get_outline_point, table_net, delete_contain_bbox, points_to_line, \
  22. fix_inner, merge_line, fix_corner, add_continue_bbox, delete_outline
  23. from format_convert import _global
  24. # 接口配置
  25. app = Flask(__name__)
  26. @app.route('/otr', methods=['POST'])
  27. def _otr():
  28. try:
  29. if not request.form:
  30. log("otr no data!")
  31. return json.dumps({"list_line": str([-9])})
  32. otr_model = globals().get("global_otr_model")
  33. if otr_model is None:
  34. otr_model = OtrModels().get_model()
  35. globals().update({"global_otr_model": otr_model})
  36. data = request.form.get("data")
  37. is_from_pdf = request.form.get("is_from_pdf")
  38. img_data = base64.b64decode(data)
  39. _md5 = get_md5_from_bytes(img_data)[0]
  40. _global.update({"md5": _md5})
  41. if is_from_pdf:
  42. list_lines = line_detect(img_data, otr_model, prob=0.2)
  43. else:
  44. list_lines = line_detect(img_data, otr_model, prob=0.5)
  45. return json.dumps(list_lines)
  46. except TimeoutError:
  47. return json.dumps({"list_line": str([-5])})
  48. except:
  49. traceback.print_exc()
  50. return json.dumps({"list_line": str([-1])})
  51. def otr(data, otr_model, is_from_pdf):
  52. try:
  53. img_data = base64.b64decode(data)
  54. # points_and_lines = pool.apply(table_detect, (img_data,))
  55. if is_from_pdf:
  56. list_lines = line_detect(img_data, otr_model, prob=0.2)
  57. else:
  58. list_lines = line_detect(img_data, otr_model, prob=0.5)
  59. return list_lines
  60. except TimeoutError:
  61. raise TimeoutError
  62. flag = 0
  63. # model_path = "models/table-line.h5"
  64. def table_detect2(img_data, otr_model):
  65. log("into otr_interface table_detect")
  66. start_time = time.time()
  67. try:
  68. start_time1 = time.time()
  69. # 二进制数据流转np.ndarray [np.uint8: 8位像素]
  70. img = cv2.imdecode(np.frombuffer(img_data, np.uint8), cv2.IMREAD_COLOR)
  71. # log("into otr_interface table_detect 1")
  72. # cv2.imwrite("111111.jpg", img)
  73. # 将bgr转为rbg
  74. image_np = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
  75. # log("into otr_interface table_detect 2")
  76. # 选择与图片最接近分辨率,以防失真
  77. # best_h, best_w = get_best_predict_size(img)
  78. print("image_np.shape", image_np.shape)
  79. best_h, best_w, _ = image_np.shape
  80. log("otr preprocess time: " + str(round(float(time.time()-start_time1), 4)) + "s")
  81. # 调用模型
  82. # rows, cols = table_line(image_np, otr_model)
  83. start_time1 = time.time()
  84. rows, cols, image_np = table_line(image_np, otr_model, size=(best_w, best_h), hprob=0.5, vprob=0.5)
  85. log("otr model predict time: " + str(round(float(time.time()-start_time1), 4)) + "s")
  86. start_time1 = time.time()
  87. if not rows or not cols:
  88. print("points", 0, "split_lines", 0, "bboxes", 0)
  89. return {"points": str([]), "split_lines": str([]),
  90. "bboxes": str([]), "outline_points": str([]),
  91. "lines": str([])}
  92. # 查看是否正确输出rows,cols
  93. # for line in rows+cols:
  94. # cv2.line(img, (int(line[0]), int(line[1])), (int(line[2]), int(line[3])),
  95. # (255, 0, 0), 2)
  96. # cv2.imshow("rows-cols1", img)
  97. # cv2.waitKey(0)
  98. # 处理结果
  99. # 合并错开线
  100. rows = merge_line(rows, axis=0)
  101. cols = merge_line(cols, axis=1)
  102. # 计算交点、分割线
  103. points = get_points(rows, cols, (image_np.shape[0], image_np.shape[1]))
  104. # log("into otr_interface table_detect 5")
  105. if not points:
  106. print("points", 0, "split_lines", 0, "bboxes", 0)
  107. return {"points": str([]), "split_lines": str([]),
  108. "bboxes": str([]), "outline_points": str([]),
  109. "lines": str([])}
  110. # 清掉外围的没用的线
  111. rows, cols = delete_outline(rows, cols, points)
  112. split_lines, split_y = get_split_line(points, cols, image_np)
  113. # log("into otr_interface table_detect 6")
  114. # 计算交点所在行列,剔除相近交点
  115. row_point_list = get_points_row(points, split_y, 5)
  116. col_point_list = get_points_col(points, split_y, 5)
  117. # log("into otr_interface table_detect 7")
  118. points = delete_close_points(points, row_point_list, col_point_list)
  119. # log("into otr_interface table_detect 8")
  120. # 查看是否正确输出点
  121. # for p in points:
  122. # cv2.circle(img, (p[0], p[1]), 3, (0, 0, 255))
  123. # cv2.imshow("points", img)
  124. # cv2.waitKey(0)
  125. # 查看是否正确输出rows,cols
  126. # for line in rows+cols:
  127. # cv2.line(img, (int(line[0]), int(line[1])), (int(line[2]), int(line[3])),
  128. # (0, 255, 0), 2)
  129. # cv2.imshow("rows-cols0", img)
  130. # cv2.waitKey(0)
  131. # 修复边框
  132. new_rows, new_cols, long_rows, long_cols = fix_outline(image_np, rows, cols, points,
  133. split_y)
  134. # print(new_cols, new_rows)
  135. if new_rows or new_cols:
  136. # 连接至补线的延长线
  137. if long_rows:
  138. rows = long_rows
  139. if long_cols:
  140. cols = long_cols
  141. # 新的补线
  142. if new_rows:
  143. rows += new_rows
  144. if new_cols:
  145. cols += new_cols
  146. # 修复边框后重新计算交点、分割线
  147. points = get_points(rows, cols, (image_np.shape[0], image_np.shape[1]))
  148. # log("into otr_interface table_detect 10")
  149. split_lines, split_y = get_split_line(points, cols, image_np)
  150. # 计算交点所在行列,剔除相近交点
  151. row_point_list = get_points_row(points, split_y, 0)
  152. col_point_list = get_points_col(points, split_y, 0)
  153. # log("into otr_interface table_detect 11")
  154. points = delete_close_points(points, row_point_list, col_point_list)
  155. # row_point_list = get_points_row(points, split_y)
  156. # col_point_list = get_points_col(points, split_y)
  157. # log("into otr_interface table_detect 12")
  158. # 查看是否正确输出rows,cols
  159. # for line in rows+cols:
  160. # cv2.line(img, (int(line[0]), int(line[1])), (int(line[2]), int(line[3])),
  161. # (255, 0, 0), 2)
  162. # cv2.imshow("rows-cols1", img)
  163. # cv2.waitKey(0)
  164. # 修复表格4个角
  165. rows, cols = fix_corner(rows, cols, split_y)
  166. points = get_points(rows, cols, (image_np.shape[0], image_np.shape[1]))
  167. # row_point_list = get_points_row(points, split_y, 5)
  168. # col_point_list = get_points_col(points, split_y, 5)
  169. # print("row_point_list", row_point_list)
  170. # print("col_point_list", col_point_list)
  171. # 修复内部缺线
  172. points = fix_inner(rows, cols, points, split_y)
  173. if not points:
  174. print("points", 0, "split_lines", 0, "bboxes", 0)
  175. return {"points": str([]), "split_lines": str([]),
  176. "bboxes": str([]), "outline_points": str([]),
  177. "lines": str([])}
  178. row_point_list = get_points_row(points, split_y, 5)
  179. col_point_list = get_points_col(points, split_y, 5)
  180. # 查看是否正确输出点
  181. # for p in points:
  182. # cv2.circle(img, (p[0], p[1]), 1, (0, 255, 0), 3)
  183. # cv2.imshow("points fix", img)
  184. # cv2.waitKey(0)
  185. # 查看是否正确输出rows,cols
  186. # for line in rows+cols:
  187. # cv2.line(img, (int(line[0]), int(line[1])), (int(line[2]), int(line[3])),
  188. # (255, 0, 0), 2)
  189. # cv2.imshow("rows-cols2", img)
  190. # cv2.waitKey(0)
  191. # 根据分行分列重新得到rows、cols,避免线延长导致后续bbox生成失败
  192. # rows = points_to_line(row_point_list, axis=0)
  193. # cols = points_to_line(col_point_list, axis=1)
  194. # points = get_points(rows, cols, (image_np.shape[0], image_np.shape[1]))
  195. # row_point_list = get_points_row(points, split_y, 0)
  196. # col_point_list = get_points_col(points, split_y, 0)
  197. # 获取bbox 单元格
  198. bboxes = get_bbox(image_np, row_point_list, col_point_list, split_y, rows, cols)
  199. # log("into otr_interface table_detect 13")
  200. # 删除包含bbox
  201. if bboxes:
  202. bboxes = delete_contain_bbox(bboxes)
  203. # 查看是否能输出正确框
  204. # for box in bboxes:
  205. # cv2.rectangle(img, box[0], box[1], (0, 0, 255), 3)
  206. # cv2.imshow("bbox", img)
  207. # cv2.waitKey(0)
  208. # 补充连续框
  209. # if bboxes:
  210. # bboxes = add_continue_bbox(bboxes)
  211. #
  212. # # 删除包含bbox
  213. # bboxes = delete_contain_bbox(bboxes)
  214. # 查看是否能输出正确框
  215. # cv2.namedWindow('bbox', 0)
  216. # for box in bboxes:
  217. # cv2.rectangle(img, box[0], box[1], (0, 255, 0), 3)
  218. # cv2.imshow("bbox", img)
  219. # cv2.waitKey(0)
  220. # 查看是否正确输出点
  221. # cv2.namedWindow('points', 0)
  222. # for p in points:
  223. # cv2.circle(img, (p[0], p[1]), 3, (0, 0, 255))
  224. # cv2.imshow("points", img)
  225. # cv2.waitKey(0)
  226. # 查看是否正确输出区域分割线
  227. # cv2.namedWindow('split_lines', 0)
  228. # for line in split_lines:
  229. # cv2.line(img, line[0], line[1], (0, 0, 255), 2)
  230. # cv2.imshow("split_lines", img)
  231. # cv2.waitKey(0)
  232. # 获取每个表格的左上右下两个点
  233. outline_points = get_outline_point(points, split_y)
  234. # log("into otr_interface table_detect 14")
  235. if bboxes:
  236. print("bboxes number", len(bboxes))
  237. # print("bboxes", bboxes)
  238. else:
  239. print("bboxes number", "None")
  240. log("otr postprocess time: " + str(round(float(time.time()-start_time1), 4)) + "s")
  241. log("use time: " + str(time.time()-start_time))
  242. return {"points": str(points), "split_lines": str(split_lines),
  243. "bboxes": str(bboxes), "outline_points": str(outline_points),
  244. "lines": str(rows+cols)}
  245. except TimeoutError:
  246. raise TimeoutError
  247. except Exception as e:
  248. log("otr_interface cannot detected table!")
  249. print("otr_interface cannot detected table!", traceback.print_exc())
  250. print("points", 0, "split_lines", 0, "bboxes", 0)
  251. log("otr postprocess time: " + str(round(float(time.time()-start_time1), 4)) + "s")
  252. return {"points": str([]), "split_lines": str([]), "bboxes": str([]),
  253. "outline_points": str([]), "lines": str([])}
  254. def line_detect(img_data, otr_model, prob=0.2):
  255. log("into otr_interface table_detect")
  256. start_time = time.time()
  257. try:
  258. start_time1 = time.time()
  259. # 二进制数据流转np.ndarray [np.uint8: 8位像素]
  260. img = cv2.imdecode(np.frombuffer(img_data, np.uint8), cv2.IMREAD_COLOR)
  261. # log("into otr_interface table_detect 1")
  262. # cv2.imwrite("111111.jpg", img)
  263. # 将bgr转为rbg
  264. image_np = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
  265. # log("into otr_interface table_detect 2")
  266. # 选择与图片最接近分辨率,以防失真
  267. # best_h, best_w = get_best_predict_size(img)
  268. log("image_np.shape" + str(image_np.shape))
  269. best_h, best_w, _ = image_np.shape
  270. log("otr preprocess time: " + str(round(float(time.time()-start_time1), 4)) + "s")
  271. # 调用模型
  272. # rows, cols = table_line(image_np, otr_model)
  273. start_time1 = time.time()
  274. list_line = table_line(image_np, otr_model, size=(best_w, best_h), prob=prob)
  275. log("otr finish " + str(round(float(time.time()-start_time1), 4)) + "s")
  276. return {"list_line": str(list_line)}
  277. except TimeoutError:
  278. raise TimeoutError
  279. except Exception as e:
  280. log("otr_interface cannot detected table!")
  281. print("otr_interface cannot detected table!", traceback.print_exc())
  282. log("otr postprocess time: " + str(round(float(time.time()-start_time1), 4)) + "s")
  283. return {"list_line": str([])}
  284. class OtrModels:
  285. def __init__(self):
  286. # python文件所在目录
  287. _dir = os.path.abspath(os.path.dirname(os.path.abspath(__file__)))
  288. model_path = _dir + "/models/table-line.h5"
  289. self.otr_model = table_net((None, None, 3), 2)
  290. self.otr_model.load_weights(model_path)
  291. def get_model(self):
  292. return self.otr_model
  293. def test_otr_model():
  294. file_path = "C:/Users/Administrator/Desktop/error2.png"
  295. with open(file_path, "rb") as f:
  296. file_bytes = f.read()
  297. file_base64 = base64.b64encode(file_bytes)
  298. file_json = {"data": file_base64, "is_from_pdf": False}
  299. _url = "http://192.168.2.103:18000/otr"
  300. r = json.loads(request_post(_url, file_json))
  301. print(r)
  302. # otr_model = table_net((None, None, 3), 2)
  303. # otr_model.load_weights(model_path)
  304. if __name__ == '__main__':
  305. if len(sys.argv) == 2:
  306. port = int(sys.argv[1])
  307. elif len(sys.argv) == 3:
  308. port = int(sys.argv[1])
  309. using_gpu_index = int(sys.argv[2])
  310. else:
  311. port = 18000
  312. using_gpu_index = 0
  313. _global._init()
  314. _global.update({"port": str(port)})
  315. # 日志格式设置
  316. # ip = get_intranet_ip()
  317. # logging.basicConfig(level=logging.INFO,
  318. # format='%(asctime)s - %(name)s - %(levelname)s - '
  319. # + ip + ' - ' + str(port) + ' - %(message)s')
  320. # 限制tensorflow显存
  321. memory_limit_scale = 0.3
  322. os.environ['CUDA_VISIBLE_DEVICES'] = str(using_gpu_index)
  323. os.environ['CUDA_CACHE_MAXSIZE'] = str(2147483648)
  324. os.environ['CUDA_CACHE_DISABLE'] = str(0)
  325. gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=memory_limit_scale)
  326. sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))
  327. app.run(host='0.0.0.0', port=port, processes=1, threaded=False, debug=False)
  328. log("OTR running "+str(port))
  329. # test_otr_model()
  330. # print(json.dumps([-2]))
  331. # otr_model = OtrModels().get_model()
  332. # otr("11", otr_model)