otr_interface.py 16 KB

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