predict_det.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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. self.predictor.run()
  157. outputs = []
  158. for output_tensor in self.output_tensors:
  159. output = output_tensor.copy_to_cpu()
  160. outputs.append(output)
  161. preds = {}
  162. if self.det_algorithm == "EAST":
  163. preds['f_geo'] = outputs[0]
  164. preds['f_score'] = outputs[1]
  165. elif self.det_algorithm == 'SAST':
  166. preds['f_border'] = outputs[0]
  167. preds['f_score'] = outputs[1]
  168. preds['f_tco'] = outputs[2]
  169. preds['f_tvo'] = outputs[3]
  170. elif self.det_algorithm == 'DB':
  171. preds['maps'] = outputs[0]
  172. else:
  173. raise NotImplementedError
  174. post_result = self.postprocess_op(preds, shape_list)
  175. dt_boxes = post_result[0]['points']
  176. if self.det_algorithm == "SAST" and self.det_sast_polygon:
  177. dt_boxes = self.filter_tag_det_res_only_clip(dt_boxes, ori_im.shape)
  178. else:
  179. dt_boxes = self.filter_tag_det_res(dt_boxes, ori_im.shape)
  180. elapse = time.time() - starttime
  181. # 释放内存
  182. # print("TextDetector", self.predictor)
  183. # if TextDetector.shrink_memory_count % 100 == 0:
  184. # print("TextDetector shrink memory")
  185. self.predictor.clear_intermediate_tensor()
  186. self.predictor.try_shrink_memory()
  187. # TextDetector.shrink_memory_count += 1
  188. return dt_boxes, elapse
  189. class TextDetector2(object):
  190. shrink_memory_count = 0
  191. def __init__(self, args):
  192. self.args = args
  193. self.det_algorithm = args.det_algorithm
  194. pre_process_list = [{
  195. 'DetResizeForTest': None
  196. }, {
  197. 'NormalizeImage': {
  198. 'std': [0.229, 0.224, 0.225],
  199. 'mean': [0.485, 0.456, 0.406],
  200. 'scale': '1./255.',
  201. 'order': 'hwc'
  202. }
  203. }, {
  204. 'ToCHWImage': None
  205. }, {
  206. 'KeepKeys': {
  207. 'keep_keys': ['image', 'shape']
  208. }
  209. }]
  210. postprocess_params = {}
  211. if self.det_algorithm == "DB":
  212. postprocess_params['name'] = 'DBPostProcess'
  213. postprocess_params["thresh"] = args.det_db_thresh
  214. postprocess_params["box_thresh"] = args.det_db_box_thresh
  215. postprocess_params["max_candidates"] = 1000
  216. postprocess_params["unclip_ratio"] = args.det_db_unclip_ratio
  217. postprocess_params["use_dilation"] = args.use_dilation
  218. else:
  219. logger.info("unknown det_algorithm:{}".format(self.det_algorithm))
  220. sys.exit(0)
  221. self.preprocess_op = create_operators(pre_process_list)
  222. self.postprocess_op = build_post_process(postprocess_params)
  223. def order_points_clockwise(self, pts):
  224. """
  225. reference from: https://github.com/jrosebr1/imutils/blob/master/imutils/perspective.py
  226. # sort the points based on their x-coordinates
  227. """
  228. xSorted = pts[np.argsort(pts[:, 0]), :]
  229. # grab the left-most and right-most points from the sorted
  230. # x-roodinate points
  231. leftMost = xSorted[:2, :]
  232. rightMost = xSorted[2:, :]
  233. # now, sort the left-most coordinates according to their
  234. # y-coordinates so we can grab the top-left and bottom-left
  235. # points, respectively
  236. leftMost = leftMost[np.argsort(leftMost[:, 1]), :]
  237. (tl, bl) = leftMost
  238. rightMost = rightMost[np.argsort(rightMost[:, 1]), :]
  239. (tr, br) = rightMost
  240. rect = np.array([tl, tr, br, bl], dtype="float32")
  241. return rect
  242. def clip_det_res(self, points, img_height, img_width):
  243. for pno in range(points.shape[0]):
  244. points[pno, 0] = int(min(max(points[pno, 0], 0), img_width - 1))
  245. points[pno, 1] = int(min(max(points[pno, 1], 0), img_height - 1))
  246. return points
  247. def filter_tag_det_res(self, dt_boxes, image_shape):
  248. img_height, img_width = image_shape[0:2]
  249. dt_boxes_new = []
  250. for box in dt_boxes:
  251. box = self.order_points_clockwise(box)
  252. box = self.clip_det_res(box, img_height, img_width)
  253. rect_width = int(np.linalg.norm(box[0] - box[1]))
  254. rect_height = int(np.linalg.norm(box[0] - box[3]))
  255. if rect_width <= 3 or rect_height <= 3:
  256. continue
  257. dt_boxes_new.append(box)
  258. dt_boxes = np.array(dt_boxes_new)
  259. return dt_boxes
  260. def filter_tag_det_res_only_clip(self, dt_boxes, image_shape):
  261. img_height, img_width = image_shape[0:2]
  262. dt_boxes_new = []
  263. for box in dt_boxes:
  264. box = self.clip_det_res(box, img_height, img_width)
  265. dt_boxes_new.append(box)
  266. dt_boxes = np.array(dt_boxes_new)
  267. return dt_boxes
  268. def __call__(self, img):
  269. from format_convert.convert_need_interface import from_gpu_interface_redis
  270. # 预处理
  271. ori_im = img.copy()
  272. data = {'image': img}
  273. data = transform(data, self.preprocess_op)
  274. img, shape_list = data
  275. if img is None:
  276. return None, 0
  277. img = np.expand_dims(img, axis=0)
  278. shape_list = np.expand_dims(shape_list, axis=0)
  279. img = img.copy()
  280. starttime = time.time()
  281. # # 压缩numpy
  282. # compressed_array = io.BytesIO()
  283. # np.savez_compressed(compressed_array, img)
  284. # compressed_array.seek(0)
  285. # img = compressed_array.read()
  286. # 调用GPU接口
  287. _dict = {"inputs": img, "args": str(namespace_to_dict(self.args)), "md5": _global.get("md5")}
  288. result = from_gpu_interface_redis(_dict, model_type="ocr", predictor_type="det")
  289. if judge_error_code(result):
  290. logging.error("from_gpu_interface failed! " + str(result))
  291. raise requests.exceptions.RequestException
  292. _preds = result.get("preds")
  293. gpu_time = result.get("gpu_time")
  294. # # 解压numpy
  295. # decompressed_array = io.BytesIO()
  296. # decompressed_array.write(_preds)
  297. # decompressed_array.seek(0)
  298. # _preds = np.load(decompressed_array, allow_pickle=True)['arr_0']
  299. # log("inputs.shape" + str(_preds.shape))
  300. # 后处理
  301. preds = {}
  302. if self.det_algorithm == 'DB':
  303. preds['maps'] = _preds
  304. else:
  305. raise NotImplementedError
  306. post_result = self.postprocess_op(preds, shape_list)
  307. dt_boxes = post_result[0]['points']
  308. dt_boxes = self.filter_tag_det_res(dt_boxes, ori_im.shape)
  309. elapse = time.time() - starttime
  310. log("ocr model predict time - det - time " + str(gpu_time))
  311. return dt_boxes, elapse
  312. if __name__ == "__main__":
  313. args = utility.parse_args()
  314. image_file_list = get_image_file_list(args.image_dir)
  315. text_detector = TextDetector(args)
  316. count = 0
  317. total_time = 0
  318. draw_img_save = "./inference_results"
  319. if not os.path.exists(draw_img_save):
  320. os.makedirs(draw_img_save)
  321. for image_file in image_file_list:
  322. img, flag = check_and_read_gif(image_file)
  323. if not flag:
  324. img = cv2.imread(image_file)
  325. if img is None:
  326. logger.info("error in loading image:{}".format(image_file))
  327. continue
  328. dt_boxes, elapse = text_detector(img)
  329. if count > 0:
  330. total_time += elapse
  331. count += 1
  332. logger.info("Predict time of {}: {}".format(image_file, elapse))
  333. src_im = utility.draw_text_det_res(dt_boxes, image_file)
  334. img_name_pure = os.path.split(image_file)[-1]
  335. img_path = os.path.join(draw_img_save,
  336. "det_res_{}".format(img_name_pure))
  337. cv2.imwrite(img_path, src_im)
  338. logger.info("The visualized image saved in {}".format(img_path))
  339. if count > 1:
  340. logger.info("Avg Time: {}".format(total_time / (count - 1)))