utility.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import argparse
  15. import os
  16. import sys
  17. import cv2
  18. import numpy as np
  19. import json
  20. from PIL import Image, ImageDraw, ImageFont
  21. import math
  22. from paddle import inference
  23. def parse_args(return_parse=False):
  24. def str2bool(v):
  25. return v.lower() in ("true", "t", "1")
  26. parser = argparse.ArgumentParser()
  27. # params for prediction engine
  28. parser.add_argument("--use_gpu", type=str2bool, default=True)
  29. parser.add_argument("--ir_optim", type=str2bool, default=True)
  30. parser.add_argument("--use_tensorrt", type=str2bool, default=False)
  31. parser.add_argument("--use_fp16", type=str2bool, default=False)
  32. parser.add_argument("--gpu_mem", type=int, default=500)
  33. # params for text detector
  34. parser.add_argument("--image_dir", type=str)
  35. parser.add_argument("--det_algorithm", type=str, default='DB')
  36. parser.add_argument("--det_model_dir", type=str)
  37. parser.add_argument("--det_limit_side_len", type=float, default=960)
  38. parser.add_argument("--det_limit_type", type=str, default='max')
  39. # DB parmas
  40. parser.add_argument("--det_db_thresh", type=float, default=0.3)
  41. parser.add_argument("--det_db_box_thresh", type=float, default=0.5)
  42. parser.add_argument("--det_db_unclip_ratio", type=float, default=1.6)
  43. parser.add_argument("--max_batch_size", type=int, default=10)
  44. parser.add_argument("--use_dilation", type=bool, default=False)
  45. # EAST parmas
  46. parser.add_argument("--det_east_score_thresh", type=float, default=0.8)
  47. parser.add_argument("--det_east_cover_thresh", type=float, default=0.1)
  48. parser.add_argument("--det_east_nms_thresh", type=float, default=0.2)
  49. # SAST parmas
  50. parser.add_argument("--det_sast_score_thresh", type=float, default=0.5)
  51. parser.add_argument("--det_sast_nms_thresh", type=float, default=0.2)
  52. parser.add_argument("--det_sast_polygon", type=bool, default=False)
  53. # params for text recognizer
  54. parser.add_argument("--rec_algorithm", type=str, default='CRNN')
  55. parser.add_argument("--rec_model_dir", type=str)
  56. parser.add_argument("--rec_image_shape", type=str, default="3, 32, 320")
  57. parser.add_argument("--rec_char_type", type=str, default='ch')
  58. parser.add_argument("--rec_batch_num", type=int, default=6)
  59. parser.add_argument("--max_text_length", type=int, default=25)
  60. parser.add_argument(
  61. "--rec_char_dict_path",
  62. type=str,
  63. default="./ppocr/utils/ppocr_keys_v1.txt")
  64. parser.add_argument("--use_space_char", type=str2bool, default=True)
  65. parser.add_argument(
  66. "--vis_font_path", type=str, default="./doc/fonts/simfang.ttf")
  67. parser.add_argument("--drop_score", type=float, default=0.5)
  68. # params for text classifier
  69. parser.add_argument("--use_angle_cls", type=str2bool, default=False)
  70. parser.add_argument("--cls_model_dir", type=str)
  71. parser.add_argument("--cls_image_shape", type=str, default="3, 48, 192")
  72. parser.add_argument("--label_list", type=list, default=['0', '180'])
  73. parser.add_argument("--cls_batch_num", type=int, default=6)
  74. parser.add_argument("--cls_thresh", type=float, default=0.9)
  75. parser.add_argument("--enable_mkldnn", type=str2bool, default=False)
  76. parser.add_argument("--use_pdserving", type=str2bool, default=False)
  77. if return_parse:
  78. return parser
  79. return parser.parse_args()
  80. def create_predictor(args, mode, logger):
  81. if mode == "det":
  82. model_dir = args.det_model_dir
  83. elif mode == 'cls':
  84. model_dir = args.cls_model_dir
  85. else:
  86. model_dir = args.rec_model_dir
  87. if model_dir is None:
  88. logger.info("not find {} model file path {}".format(mode, model_dir))
  89. sys.exit(0)
  90. model_file_path = model_dir + "/inference.pdmodel"
  91. params_file_path = model_dir + "/inference.pdiparams"
  92. if not os.path.exists(model_file_path):
  93. logger.info("not find model file path {}".format(model_file_path))
  94. sys.exit(0)
  95. if not os.path.exists(params_file_path):
  96. logger.info("not find params file path {}".format(params_file_path))
  97. sys.exit(0)
  98. config = inference.Config(model_file_path, params_file_path)
  99. if args.use_gpu:
  100. config.enable_use_gpu(args.gpu_mem, 0)
  101. if args.use_tensorrt:
  102. config.enable_tensorrt_engine(
  103. precision_mode=inference.PrecisionType.Half
  104. if args.use_fp16 else inference.PrecisionType.Float32,
  105. max_batch_size=args.max_batch_size)
  106. else:
  107. config.disable_gpu()
  108. config.set_cpu_math_library_num_threads(6)
  109. if args.enable_mkldnn:
  110. # cache 10 different shapes for mkldnn to avoid memory leak
  111. config.set_mkldnn_cache_capacity(10)
  112. config.enable_mkldnn()
  113. # TODO LDOUBLEV: fix mkldnn bug when bach_size > 1
  114. #config.set_mkldnn_op({'conv2d', 'depthwise_conv2d', 'pool2d', 'batch_norm'})
  115. args.rec_batch_num = 1
  116. # config.enable_memory_optim()
  117. config.disable_glog_info()
  118. config.delete_pass("conv_transpose_eltwiseadd_bn_fuse_pass")
  119. config.switch_use_feed_fetch_ops(False)
  120. # create predictor
  121. predictor = inference.create_predictor(config)
  122. input_names = predictor.get_input_names()
  123. for name in input_names:
  124. input_tensor = predictor.get_input_handle(name)
  125. output_names = predictor.get_output_names()
  126. output_tensors = []
  127. for output_name in output_names:
  128. output_tensor = predictor.get_output_handle(output_name)
  129. output_tensors.append(output_tensor)
  130. return predictor, input_tensor, output_tensors
  131. def draw_text_det_res(dt_boxes, img_path):
  132. src_im = cv2.imread(img_path)
  133. for box in dt_boxes:
  134. box = np.array(box).astype(np.int32).reshape(-1, 2)
  135. cv2.polylines(src_im, [box], True, color=(255, 255, 0), thickness=2)
  136. return src_im
  137. def resize_img(img, input_size=600):
  138. """
  139. resize img and limit the longest side of the image to input_size
  140. """
  141. img = np.array(img)
  142. im_shape = img.shape
  143. im_size_max = np.max(im_shape[0:2])
  144. im_scale = float(input_size) / float(im_size_max)
  145. img = cv2.resize(img, None, None, fx=im_scale, fy=im_scale)
  146. return img
  147. def draw_ocr(image,
  148. boxes,
  149. txts=None,
  150. scores=None,
  151. drop_score=0.5,
  152. font_path="./doc/simfang.ttf"):
  153. """
  154. Visualize the results of OCR detection and recognition
  155. args:
  156. image(Image|array): RGB image
  157. boxes(list): boxes with shape(N, 4, 2)
  158. txts(list): the texts
  159. scores(list): txxs corresponding scores
  160. drop_score(float): only scores greater than drop_threshold will be visualized
  161. font_path: the path of font which is used to draw text
  162. return(array):
  163. the visualized img
  164. """
  165. if scores is None:
  166. scores = [1] * len(boxes)
  167. box_num = len(boxes)
  168. for i in range(box_num):
  169. if scores is not None and (scores[i] < drop_score or
  170. math.isnan(scores[i])):
  171. continue
  172. box = np.reshape(np.array(boxes[i]), [-1, 1, 2]).astype(np.int64)
  173. image = cv2.polylines(np.array(image), [box], True, (255, 0, 0), 2)
  174. if txts is not None:
  175. img = np.array(resize_img(image, input_size=600))
  176. txt_img = text_visual(
  177. txts,
  178. scores,
  179. img_h=img.shape[0],
  180. img_w=600,
  181. threshold=drop_score,
  182. font_path=font_path)
  183. img = np.concatenate([np.array(img), np.array(txt_img)], axis=1)
  184. return img
  185. return image
  186. def draw_ocr_box_txt(image,
  187. boxes,
  188. txts,
  189. scores=None,
  190. drop_score=0.5,
  191. font_path="./doc/simfang.ttf"):
  192. h, w = image.height, image.width
  193. img_left = image.copy()
  194. img_right = Image.new('RGB', (w, h), (255, 255, 255))
  195. import random
  196. random.seed(0)
  197. draw_left = ImageDraw.Draw(img_left)
  198. draw_right = ImageDraw.Draw(img_right)
  199. for idx, (box, txt) in enumerate(zip(boxes, txts)):
  200. if scores is not None and scores[idx] < drop_score:
  201. continue
  202. color = (random.randint(0, 255), random.randint(0, 255),
  203. random.randint(0, 255))
  204. draw_left.polygon(box, fill=color)
  205. draw_right.polygon(
  206. [
  207. box[0][0], box[0][1], box[1][0], box[1][1], box[2][0],
  208. box[2][1], box[3][0], box[3][1]
  209. ],
  210. outline=color)
  211. box_height = math.sqrt((box[0][0] - box[3][0])**2 + (box[0][1] - box[3][
  212. 1])**2)
  213. box_width = math.sqrt((box[0][0] - box[1][0])**2 + (box[0][1] - box[1][
  214. 1])**2)
  215. if box_height > 2 * box_width:
  216. font_size = max(int(box_width * 0.9), 10)
  217. font = ImageFont.truetype(font_path, font_size, encoding="utf-8")
  218. cur_y = box[0][1]
  219. for c in txt:
  220. char_size = font.getsize(c)
  221. draw_right.text(
  222. (box[0][0] + 3, cur_y), c, fill=(0, 0, 0), font=font)
  223. cur_y += char_size[1]
  224. else:
  225. font_size = max(int(box_height * 0.8), 10)
  226. font = ImageFont.truetype(font_path, font_size, encoding="utf-8")
  227. draw_right.text(
  228. [box[0][0], box[0][1]], txt, fill=(0, 0, 0), font=font)
  229. img_left = Image.blend(image, img_left, 0.5)
  230. img_show = Image.new('RGB', (w * 2, h), (255, 255, 255))
  231. img_show.paste(img_left, (0, 0, w, h))
  232. img_show.paste(img_right, (w, 0, w * 2, h))
  233. return np.array(img_show)
  234. def str_count(s):
  235. """
  236. Count the number of Chinese characters,
  237. a single English character and a single number
  238. equal to half the length of Chinese characters.
  239. args:
  240. s(string): the input of string
  241. return(int):
  242. the number of Chinese characters
  243. """
  244. import string
  245. count_zh = count_pu = 0
  246. s_len = len(s)
  247. en_dg_count = 0
  248. for c in s:
  249. if c in string.ascii_letters or c.isdigit() or c.isspace():
  250. en_dg_count += 1
  251. elif c.isalpha():
  252. count_zh += 1
  253. else:
  254. count_pu += 1
  255. return s_len - math.ceil(en_dg_count / 2)
  256. def text_visual(texts,
  257. scores,
  258. img_h=400,
  259. img_w=600,
  260. threshold=0.,
  261. font_path="./doc/simfang.ttf"):
  262. """
  263. create new blank img and draw txt on it
  264. args:
  265. texts(list): the text will be draw
  266. scores(list|None): corresponding score of each txt
  267. img_h(int): the height of blank img
  268. img_w(int): the width of blank img
  269. font_path: the path of font which is used to draw text
  270. return(array):
  271. """
  272. if scores is not None:
  273. assert len(texts) == len(
  274. scores), "The number of txts and corresponding scores must match"
  275. def create_blank_img():
  276. blank_img = np.ones(shape=[img_h, img_w], dtype=np.int8) * 255
  277. blank_img[:, img_w - 1:] = 0
  278. blank_img = Image.fromarray(blank_img).convert("RGB")
  279. draw_txt = ImageDraw.Draw(blank_img)
  280. return blank_img, draw_txt
  281. blank_img, draw_txt = create_blank_img()
  282. font_size = 20
  283. txt_color = (0, 0, 0)
  284. font = ImageFont.truetype(font_path, font_size, encoding="utf-8")
  285. gap = font_size + 5
  286. txt_img_list = []
  287. count, index = 1, 0
  288. for idx, txt in enumerate(texts):
  289. index += 1
  290. if scores[idx] < threshold or math.isnan(scores[idx]):
  291. index -= 1
  292. continue
  293. first_line = True
  294. while str_count(txt) >= img_w // font_size - 4:
  295. tmp = txt
  296. txt = tmp[:img_w // font_size - 4]
  297. if first_line:
  298. new_txt = str(index) + ': ' + txt
  299. first_line = False
  300. else:
  301. new_txt = ' ' + txt
  302. draw_txt.text((0, gap * count), new_txt, txt_color, font=font)
  303. txt = tmp[img_w // font_size - 4:]
  304. if count >= img_h // gap - 1:
  305. txt_img_list.append(np.array(blank_img))
  306. blank_img, draw_txt = create_blank_img()
  307. count = 0
  308. count += 1
  309. if first_line:
  310. new_txt = str(index) + ': ' + txt + ' ' + '%.3f' % (scores[idx])
  311. else:
  312. new_txt = " " + txt + " " + '%.3f' % (scores[idx])
  313. draw_txt.text((0, gap * count), new_txt, txt_color, font=font)
  314. # whether add new blank img or not
  315. if count >= img_h // gap - 1 and idx + 1 < len(texts):
  316. txt_img_list.append(np.array(blank_img))
  317. blank_img, draw_txt = create_blank_img()
  318. count = 0
  319. count += 1
  320. txt_img_list.append(np.array(blank_img))
  321. if len(txt_img_list) == 1:
  322. blank_img = np.array(txt_img_list[0])
  323. else:
  324. blank_img = np.concatenate(txt_img_list, axis=1)
  325. return np.array(blank_img)
  326. def base64_to_cv2(b64str):
  327. import base64
  328. data = base64.b64decode(b64str.encode('utf8'))
  329. data = np.fromstring(data, np.uint8)
  330. data = cv2.imdecode(data, cv2.IMREAD_COLOR)
  331. return data
  332. def draw_boxes(image, boxes, scores=None, drop_score=0.5):
  333. if scores is None:
  334. scores = [1] * len(boxes)
  335. for (box, score) in zip(boxes, scores):
  336. if score < drop_score:
  337. continue
  338. box = np.reshape(np.array(box), [-1, 1, 2]).astype(np.int64)
  339. image = cv2.polylines(np.array(image), [box], True, (255, 0, 0), 2)
  340. return image
  341. if __name__ == '__main__':
  342. test_img = "./doc/test_v2"
  343. predict_txt = "./doc/predict.txt"
  344. f = open(predict_txt, 'r')
  345. data = f.readlines()
  346. img_path, anno = data[0].strip().split('\t')
  347. img_name = os.path.basename(img_path)
  348. img_path = os.path.join(test_img, img_name)
  349. image = Image.open(img_path)
  350. data = json.loads(anno)
  351. boxes, txts, scores = [], [], []
  352. for dic in data:
  353. boxes.append(dic['points'])
  354. txts.append(dic['transcription'])
  355. scores.append(round(dic['scores'], 3))
  356. new_img = draw_ocr(image, boxes, txts, scores)
  357. cv2.imwrite(img_name, new_img)