predict_det.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. # encoding=utf8
  2. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import io
  16. import logging
  17. import os
  18. import sys
  19. # __dir__ = os.path.dirname(os.path.abspath(__file__))
  20. import zlib
  21. sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../../../")
  22. import requests
  23. from format_convert import _global
  24. from format_convert.utils import judge_error_code, log, namespace_to_dict
  25. # sys.path.append(__dir__)
  26. # sys.path.append(os.path.abspath(os.path.join(__dir__, '../..')))
  27. os.environ["FLAGS_allocator_strategy"] = 'auto_growth'
  28. import cv2
  29. import numpy as np
  30. import time
  31. import sys
  32. os.environ['FLAGS_eager_delete_tensor_gb'] = '0'
  33. import ocr.tools.infer.utility as utility
  34. from ocr.ppocr.utils.logging import get_logger
  35. from ocr.ppocr.utils.utility import get_image_file_list, check_and_read_gif
  36. from ocr.ppocr.data import create_operators, transform
  37. from ocr.ppocr.postprocess import build_post_process
  38. logger = get_logger()
  39. class TextDetector(object):
  40. shrink_memory_count = 0
  41. def __init__(self, args):
  42. self.args = args
  43. self.det_algorithm = args.det_algorithm
  44. pre_process_list = [{
  45. 'DetResizeForTest': None
  46. }, {
  47. 'NormalizeImage': {
  48. 'std': [0.229, 0.224, 0.225],
  49. 'mean': [0.485, 0.456, 0.406],
  50. 'scale': '1./255.',
  51. 'order': 'hwc'
  52. }
  53. }, {
  54. 'ToCHWImage': None
  55. }, {
  56. 'KeepKeys': {
  57. 'keep_keys': ['image', 'shape']
  58. }
  59. }]
  60. postprocess_params = {}
  61. if self.det_algorithm == "DB":
  62. postprocess_params['name'] = 'DBPostProcess'
  63. postprocess_params["thresh"] = args.det_db_thresh
  64. postprocess_params["box_thresh"] = args.det_db_box_thresh
  65. postprocess_params["max_candidates"] = 1000
  66. postprocess_params["unclip_ratio"] = args.det_db_unclip_ratio
  67. postprocess_params["use_dilation"] = args.use_dilation
  68. elif self.det_algorithm == "EAST":
  69. postprocess_params['name'] = 'EASTPostProcess'
  70. postprocess_params["score_thresh"] = args.det_east_score_thresh
  71. postprocess_params["cover_thresh"] = args.det_east_cover_thresh
  72. postprocess_params["nms_thresh"] = args.det_east_nms_thresh
  73. elif self.det_algorithm == "SAST":
  74. pre_process_list[0] = {
  75. 'DetResizeForTest': {
  76. 'resize_long': args.det_limit_side_len
  77. }
  78. }
  79. postprocess_params['name'] = 'SASTPostProcess'
  80. postprocess_params["score_thresh"] = args.det_sast_score_thresh
  81. postprocess_params["nms_thresh"] = args.det_sast_nms_thresh
  82. self.det_sast_polygon = args.det_sast_polygon
  83. if self.det_sast_polygon:
  84. postprocess_params["sample_pts_num"] = 6
  85. postprocess_params["expand_scale"] = 1.2
  86. postprocess_params["shrink_ratio_of_width"] = 0.2
  87. else:
  88. postprocess_params["sample_pts_num"] = 2
  89. postprocess_params["expand_scale"] = 1.0
  90. postprocess_params["shrink_ratio_of_width"] = 0.3
  91. else:
  92. logger.info("unknown det_algorithm:{}".format(self.det_algorithm))
  93. sys.exit(0)
  94. self.preprocess_op = create_operators(pre_process_list)
  95. self.postprocess_op = build_post_process(postprocess_params)
  96. self.predictor, self.input_tensor, self.output_tensors = utility.create_predictor(
  97. args, 'det', logger) # paddle.jit.load(args.det_model_dir)
  98. # self.predictor.eval()
  99. def order_points_clockwise(self, pts):
  100. """
  101. reference from: https://github.com/jrosebr1/imutils/blob/master/imutils/perspective.py
  102. # sort the points based on their x-coordinates
  103. """
  104. xSorted = pts[np.argsort(pts[:, 0]), :]
  105. # grab the left-most and right-most points from the sorted
  106. # x-roodinate points
  107. leftMost = xSorted[:2, :]
  108. rightMost = xSorted[2:, :]
  109. # now, sort the left-most coordinates according to their
  110. # y-coordinates so we can grab the top-left and bottom-left
  111. # points, respectively
  112. leftMost = leftMost[np.argsort(leftMost[:, 1]), :]
  113. (tl, bl) = leftMost
  114. rightMost = rightMost[np.argsort(rightMost[:, 1]), :]
  115. (tr, br) = rightMost
  116. rect = np.array([tl, tr, br, bl], dtype="float32")
  117. return rect
  118. def clip_det_res(self, points, img_height, img_width):
  119. for pno in range(points.shape[0]):
  120. points[pno, 0] = int(min(max(points[pno, 0], 0), img_width - 1))
  121. points[pno, 1] = int(min(max(points[pno, 1], 0), img_height - 1))
  122. return points
  123. def filter_tag_det_res(self, dt_boxes, image_shape):
  124. img_height, img_width = image_shape[0:2]
  125. dt_boxes_new = []
  126. for box in dt_boxes:
  127. box = self.order_points_clockwise(box)
  128. box = self.clip_det_res(box, img_height, img_width)
  129. rect_width = int(np.linalg.norm(box[0] - box[1]))
  130. rect_height = int(np.linalg.norm(box[0] - box[3]))
  131. if rect_width <= 3 or rect_height <= 3:
  132. continue
  133. dt_boxes_new.append(box)
  134. dt_boxes = np.array(dt_boxes_new)
  135. return dt_boxes
  136. def filter_tag_det_res_only_clip(self, dt_boxes, image_shape):
  137. img_height, img_width = image_shape[0:2]
  138. dt_boxes_new = []
  139. for box in dt_boxes:
  140. box = self.clip_det_res(box, img_height, img_width)
  141. dt_boxes_new.append(box)
  142. dt_boxes = np.array(dt_boxes_new)
  143. return dt_boxes
  144. def __call__(self, img):
  145. ori_im = img.copy()
  146. data = {'image': img}
  147. data = transform(data, self.preprocess_op)
  148. img, shape_list = data
  149. if img is None:
  150. return None, 0
  151. img = np.expand_dims(img, axis=0)
  152. shape_list = np.expand_dims(shape_list, axis=0)
  153. img = img.copy()
  154. starttime = time.time()
  155. self.input_tensor.copy_from_cpu(img)
  156. try:
  157. self.predictor.run()
  158. except RuntimeError:
  159. log("ocr/tools/infer/predict_det.py predict.run error! maybe no gpu memory!")
  160. log("predictor shrink memory!")
  161. self.predictor.clear_intermediate_tensor()
  162. self.predictor.try_shrink_memory()
  163. raise RuntimeError
  164. outputs = []
  165. for output_tensor in self.output_tensors:
  166. output = output_tensor.copy_to_cpu()
  167. outputs.append(output)
  168. preds = {}
  169. if self.det_algorithm == "EAST":
  170. preds['f_geo'] = outputs[0]
  171. preds['f_score'] = outputs[1]
  172. elif self.det_algorithm == 'SAST':
  173. preds['f_border'] = outputs[0]
  174. preds['f_score'] = outputs[1]
  175. preds['f_tco'] = outputs[2]
  176. preds['f_tvo'] = outputs[3]
  177. elif self.det_algorithm == 'DB':
  178. preds['maps'] = outputs[0]
  179. else:
  180. raise NotImplementedError
  181. post_result = self.postprocess_op(preds, shape_list)
  182. dt_boxes = post_result[0]['points']
  183. if self.det_algorithm == "SAST" and self.det_sast_polygon:
  184. dt_boxes = self.filter_tag_det_res_only_clip(dt_boxes, ori_im.shape)
  185. else:
  186. dt_boxes = self.filter_tag_det_res(dt_boxes, ori_im.shape)
  187. elapse = time.time() - starttime
  188. # 释放内存
  189. # print("TextDetector", self.predictor)
  190. # if TextDetector.shrink_memory_count % 100 == 0:
  191. # print("TextDetector shrink memory")
  192. self.predictor.clear_intermediate_tensor()
  193. self.predictor.try_shrink_memory()
  194. # TextDetector.shrink_memory_count += 1
  195. return dt_boxes, elapse
  196. class TextDetector2(object):
  197. shrink_memory_count = 0
  198. def __init__(self, args):
  199. self.args = args
  200. self.det_algorithm = args.det_algorithm
  201. pre_process_list = [{
  202. 'DetResizeForTest': None
  203. }, {
  204. 'NormalizeImage': {
  205. 'std': [0.229, 0.224, 0.225],
  206. 'mean': [0.485, 0.456, 0.406],
  207. 'scale': '1./255.',
  208. 'order': 'hwc'
  209. }
  210. }, {
  211. 'ToCHWImage': None
  212. }, {
  213. 'KeepKeys': {
  214. 'keep_keys': ['image', 'shape']
  215. }
  216. }]
  217. postprocess_params = {}
  218. if self.det_algorithm == "DB":
  219. postprocess_params['name'] = 'DBPostProcess'
  220. postprocess_params["thresh"] = args.det_db_thresh
  221. postprocess_params["box_thresh"] = args.det_db_box_thresh
  222. postprocess_params["max_candidates"] = 1000
  223. postprocess_params["unclip_ratio"] = args.det_db_unclip_ratio
  224. postprocess_params["use_dilation"] = args.use_dilation
  225. else:
  226. logger.info("unknown det_algorithm:{}".format(self.det_algorithm))
  227. sys.exit(0)
  228. self.preprocess_op = create_operators(pre_process_list)
  229. self.postprocess_op = build_post_process(postprocess_params)
  230. def order_points_clockwise(self, pts):
  231. """
  232. reference from: https://github.com/jrosebr1/imutils/blob/master/imutils/perspective.py
  233. # sort the points based on their x-coordinates
  234. """
  235. xSorted = pts[np.argsort(pts[:, 0]), :]
  236. # grab the left-most and right-most points from the sorted
  237. # x-roodinate points
  238. leftMost = xSorted[:2, :]
  239. rightMost = xSorted[2:, :]
  240. # now, sort the left-most coordinates according to their
  241. # y-coordinates so we can grab the top-left and bottom-left
  242. # points, respectively
  243. leftMost = leftMost[np.argsort(leftMost[:, 1]), :]
  244. (tl, bl) = leftMost
  245. rightMost = rightMost[np.argsort(rightMost[:, 1]), :]
  246. (tr, br) = rightMost
  247. rect = np.array([tl, tr, br, bl], dtype="float32")
  248. return rect
  249. def clip_det_res(self, points, img_height, img_width):
  250. for pno in range(points.shape[0]):
  251. points[pno, 0] = int(min(max(points[pno, 0], 0), img_width - 1))
  252. points[pno, 1] = int(min(max(points[pno, 1], 0), img_height - 1))
  253. return points
  254. def filter_tag_det_res(self, dt_boxes, image_shape):
  255. img_height, img_width = image_shape[0:2]
  256. dt_boxes_new = []
  257. for box in dt_boxes:
  258. box = self.order_points_clockwise(box)
  259. box = self.clip_det_res(box, img_height, img_width)
  260. rect_width = int(np.linalg.norm(box[0] - box[1]))
  261. rect_height = int(np.linalg.norm(box[0] - box[3]))
  262. if rect_width <= 3 or rect_height <= 3:
  263. continue
  264. dt_boxes_new.append(box)
  265. dt_boxes = np.array(dt_boxes_new)
  266. return dt_boxes
  267. def filter_tag_det_res_only_clip(self, dt_boxes, image_shape):
  268. img_height, img_width = image_shape[0:2]
  269. dt_boxes_new = []
  270. for box in dt_boxes:
  271. box = self.clip_det_res(box, img_height, img_width)
  272. dt_boxes_new.append(box)
  273. dt_boxes = np.array(dt_boxes_new)
  274. return dt_boxes
  275. def __call__(self, img):
  276. from format_convert.convert_need_interface import from_gpu_interface_redis
  277. # 预处理
  278. ori_im = img.copy()
  279. data = {'image': img}
  280. data = transform(data, self.preprocess_op)
  281. img, shape_list = data
  282. if img is None:
  283. return None, 0
  284. img = np.expand_dims(img, axis=0)
  285. shape_list = np.expand_dims(shape_list, axis=0)
  286. img = img.copy()
  287. starttime = time.time()
  288. # # 压缩numpy
  289. # compressed_array = io.BytesIO()
  290. # np.savez_compressed(compressed_array, img)
  291. # compressed_array.seek(0)
  292. # img = compressed_array.read()
  293. # 调用GPU接口
  294. _dict = {"inputs": img, "args": str(namespace_to_dict(self.args)), "md5": _global.get("md5")}
  295. result = from_gpu_interface_redis(_dict, model_type="ocr", predictor_type="det")
  296. if judge_error_code(result):
  297. logging.error("from_gpu_interface failed! " + str(result))
  298. raise requests.exceptions.RequestException
  299. _preds = result.get("preds")
  300. gpu_time = result.get("gpu_time")
  301. # # 解压numpy
  302. # decompressed_array = io.BytesIO()
  303. # decompressed_array.write(_preds)
  304. # decompressed_array.seek(0)
  305. # _preds = np.load(decompressed_array, allow_pickle=True)['arr_0']
  306. # log("inputs.shape" + str(_preds.shape))
  307. # 后处理
  308. preds = {}
  309. if self.det_algorithm == 'DB':
  310. preds['maps'] = _preds
  311. else:
  312. raise NotImplementedError
  313. post_result = self.postprocess_op(preds, shape_list)
  314. dt_boxes = post_result[0]['points']
  315. dt_boxes = self.filter_tag_det_res(dt_boxes, ori_im.shape)
  316. elapse = time.time() - starttime
  317. log("ocr model predict time - det - time " + str(gpu_time))
  318. return dt_boxes, elapse
  319. if __name__ == "__main__":
  320. args = utility.parse_args()
  321. image_file_list = get_image_file_list(args.image_dir)
  322. text_detector = TextDetector(args)
  323. count = 0
  324. total_time = 0
  325. draw_img_save = "./inference_results"
  326. if not os.path.exists(draw_img_save):
  327. os.makedirs(draw_img_save)
  328. for image_file in image_file_list:
  329. img, flag = check_and_read_gif(image_file)
  330. if not flag:
  331. img = cv2.imread(image_file)
  332. if img is None:
  333. logger.info("error in loading image:{}".format(image_file))
  334. continue
  335. dt_boxes, elapse = text_detector(img)
  336. if count > 0:
  337. total_time += elapse
  338. count += 1
  339. logger.info("Predict time of {}: {}".format(image_file, elapse))
  340. src_im = utility.draw_text_det_res(dt_boxes, image_file)
  341. img_name_pure = os.path.split(image_file)[-1]
  342. img_path = os.path.join(draw_img_save,
  343. "det_res_{}".format(img_name_pure))
  344. cv2.imwrite(img_path, src_im)
  345. logger.info("The visualized image saved in {}".format(img_path))
  346. if count > 1:
  347. logger.info("Avg Time: {}".format(total_time / (count - 1)))