utility.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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():
  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. return parser.parse_args()
  78. def create_predictor(args, mode, logger):
  79. if mode == "det":
  80. model_dir = args.det_model_dir
  81. elif mode == 'cls':
  82. model_dir = args.cls_model_dir
  83. else:
  84. model_dir = args.rec_model_dir
  85. if model_dir is None:
  86. logger.info("not find {} model file path {}".format(mode, model_dir))
  87. sys.exit(0)
  88. model_file_path = model_dir + "/inference.pdmodel"
  89. params_file_path = model_dir + "/inference.pdiparams"
  90. if not os.path.exists(model_file_path):
  91. logger.info("not find model file path {}".format(model_file_path))
  92. sys.exit(0)
  93. if not os.path.exists(params_file_path):
  94. logger.info("not find params file path {}".format(params_file_path))
  95. sys.exit(0)
  96. config = inference.Config(model_file_path, params_file_path)
  97. if args.use_gpu:
  98. config.enable_use_gpu(args.gpu_mem, 0)
  99. if args.use_tensorrt:
  100. config.enable_tensorrt_engine(
  101. precision_mode=inference.PrecisionType.Half
  102. if args.use_fp16 else inference.PrecisionType.Float32,
  103. max_batch_size=args.max_batch_size)
  104. else:
  105. config.disable_gpu()
  106. config.set_cpu_math_library_num_threads(6)
  107. if args.enable_mkldnn:
  108. # cache 10 different shapes for mkldnn to avoid memory leak
  109. config.set_mkldnn_cache_capacity(10)
  110. config.enable_mkldnn()
  111. # TODO LDOUBLEV: fix mkldnn bug when bach_size > 1
  112. #config.set_mkldnn_op({'conv2d', 'depthwise_conv2d', 'pool2d', 'batch_norm'})
  113. args.rec_batch_num = 1
  114. # config.enable_memory_optim()
  115. config.disable_glog_info()
  116. config.delete_pass("conv_transpose_eltwiseadd_bn_fuse_pass")
  117. config.switch_use_feed_fetch_ops(False)
  118. # create predictor
  119. predictor = inference.create_predictor(config)
  120. input_names = predictor.get_input_names()
  121. for name in input_names:
  122. input_tensor = predictor.get_input_handle(name)
  123. output_names = predictor.get_output_names()
  124. output_tensors = []
  125. for output_name in output_names:
  126. output_tensor = predictor.get_output_handle(output_name)
  127. output_tensors.append(output_tensor)
  128. return predictor, input_tensor, output_tensors
  129. def draw_text_det_res(dt_boxes, img_path):
  130. src_im = cv2.imread(img_path)
  131. for box in dt_boxes:
  132. box = np.array(box).astype(np.int32).reshape(-1, 2)
  133. cv2.polylines(src_im, [box], True, color=(255, 255, 0), thickness=2)
  134. return src_im
  135. def resize_img(img, input_size=600):
  136. """
  137. resize img and limit the longest side of the image to input_size
  138. """
  139. img = np.array(img)
  140. im_shape = img.shape
  141. im_size_max = np.max(im_shape[0:2])
  142. im_scale = float(input_size) / float(im_size_max)
  143. img = cv2.resize(img, None, None, fx=im_scale, fy=im_scale)
  144. return img
  145. def draw_ocr(image,
  146. boxes,
  147. txts=None,
  148. scores=None,
  149. drop_score=0.5,
  150. font_path="./doc/simfang.ttf"):
  151. """
  152. Visualize the results of OCR detection and recognition
  153. args:
  154. image(Image|array): RGB image
  155. boxes(list): boxes with shape(N, 4, 2)
  156. txts(list): the texts
  157. scores(list): txxs corresponding scores
  158. drop_score(float): only scores greater than drop_threshold will be visualized
  159. font_path: the path of font which is used to draw text
  160. return(array):
  161. the visualized img
  162. """
  163. if scores is None:
  164. scores = [1] * len(boxes)
  165. box_num = len(boxes)
  166. for i in range(box_num):
  167. if scores is not None and (scores[i] < drop_score or
  168. math.isnan(scores[i])):
  169. continue
  170. box = np.reshape(np.array(boxes[i]), [-1, 1, 2]).astype(np.int64)
  171. image = cv2.polylines(np.array(image), [box], True, (255, 0, 0), 2)
  172. if txts is not None:
  173. img = np.array(resize_img(image, input_size=600))
  174. txt_img = text_visual(
  175. txts,
  176. scores,
  177. img_h=img.shape[0],
  178. img_w=600,
  179. threshold=drop_score,
  180. font_path=font_path)
  181. img = np.concatenate([np.array(img), np.array(txt_img)], axis=1)
  182. return img
  183. return image
  184. def draw_ocr_box_txt(image,
  185. boxes,
  186. txts,
  187. scores=None,
  188. drop_score=0.5,
  189. font_path="./doc/simfang.ttf"):
  190. h, w = image.height, image.width
  191. img_left = image.copy()
  192. img_right = Image.new('RGB', (w, h), (255, 255, 255))
  193. import random
  194. random.seed(0)
  195. draw_left = ImageDraw.Draw(img_left)
  196. draw_right = ImageDraw.Draw(img_right)
  197. for idx, (box, txt) in enumerate(zip(boxes, txts)):
  198. if scores is not None and scores[idx] < drop_score:
  199. continue
  200. color = (random.randint(0, 255), random.randint(0, 255),
  201. random.randint(0, 255))
  202. draw_left.polygon(box, fill=color)
  203. draw_right.polygon(
  204. [
  205. box[0][0], box[0][1], box[1][0], box[1][1], box[2][0],
  206. box[2][1], box[3][0], box[3][1]
  207. ],
  208. outline=color)
  209. box_height = math.sqrt((box[0][0] - box[3][0])**2 + (box[0][1] - box[3][
  210. 1])**2)
  211. box_width = math.sqrt((box[0][0] - box[1][0])**2 + (box[0][1] - box[1][
  212. 1])**2)
  213. if box_height > 2 * box_width:
  214. font_size = max(int(box_width * 0.9), 10)
  215. font = ImageFont.truetype(font_path, font_size, encoding="utf-8")
  216. cur_y = box[0][1]
  217. for c in txt:
  218. char_size = font.getsize(c)
  219. draw_right.text(
  220. (box[0][0] + 3, cur_y), c, fill=(0, 0, 0), font=font)
  221. cur_y += char_size[1]
  222. else:
  223. font_size = max(int(box_height * 0.8), 10)
  224. font = ImageFont.truetype(font_path, font_size, encoding="utf-8")
  225. draw_right.text(
  226. [box[0][0], box[0][1]], txt, fill=(0, 0, 0), font=font)
  227. img_left = Image.blend(image, img_left, 0.5)
  228. img_show = Image.new('RGB', (w * 2, h), (255, 255, 255))
  229. img_show.paste(img_left, (0, 0, w, h))
  230. img_show.paste(img_right, (w, 0, w * 2, h))
  231. return np.array(img_show)
  232. def str_count(s):
  233. """
  234. Count the number of Chinese characters,
  235. a single English character and a single number
  236. equal to half the length of Chinese characters.
  237. args:
  238. s(string): the input of string
  239. return(int):
  240. the number of Chinese characters
  241. """
  242. import string
  243. count_zh = count_pu = 0
  244. s_len = len(s)
  245. en_dg_count = 0
  246. for c in s:
  247. if c in string.ascii_letters or c.isdigit() or c.isspace():
  248. en_dg_count += 1
  249. elif c.isalpha():
  250. count_zh += 1
  251. else:
  252. count_pu += 1
  253. return s_len - math.ceil(en_dg_count / 2)
  254. def text_visual(texts,
  255. scores,
  256. img_h=400,
  257. img_w=600,
  258. threshold=0.,
  259. font_path="./doc/simfang.ttf"):
  260. """
  261. create new blank img and draw txt on it
  262. args:
  263. texts(list): the text will be draw
  264. scores(list|None): corresponding score of each txt
  265. img_h(int): the height of blank img
  266. img_w(int): the width of blank img
  267. font_path: the path of font which is used to draw text
  268. return(array):
  269. """
  270. if scores is not None:
  271. assert len(texts) == len(
  272. scores), "The number of txts and corresponding scores must match"
  273. def create_blank_img():
  274. blank_img = np.ones(shape=[img_h, img_w], dtype=np.int8) * 255
  275. blank_img[:, img_w - 1:] = 0
  276. blank_img = Image.fromarray(blank_img).convert("RGB")
  277. draw_txt = ImageDraw.Draw(blank_img)
  278. return blank_img, draw_txt
  279. blank_img, draw_txt = create_blank_img()
  280. font_size = 20
  281. txt_color = (0, 0, 0)
  282. font = ImageFont.truetype(font_path, font_size, encoding="utf-8")
  283. gap = font_size + 5
  284. txt_img_list = []
  285. count, index = 1, 0
  286. for idx, txt in enumerate(texts):
  287. index += 1
  288. if scores[idx] < threshold or math.isnan(scores[idx]):
  289. index -= 1
  290. continue
  291. first_line = True
  292. while str_count(txt) >= img_w // font_size - 4:
  293. tmp = txt
  294. txt = tmp[:img_w // font_size - 4]
  295. if first_line:
  296. new_txt = str(index) + ': ' + txt
  297. first_line = False
  298. else:
  299. new_txt = ' ' + txt
  300. draw_txt.text((0, gap * count), new_txt, txt_color, font=font)
  301. txt = tmp[img_w // font_size - 4:]
  302. if count >= img_h // gap - 1:
  303. txt_img_list.append(np.array(blank_img))
  304. blank_img, draw_txt = create_blank_img()
  305. count = 0
  306. count += 1
  307. if first_line:
  308. new_txt = str(index) + ': ' + txt + ' ' + '%.3f' % (scores[idx])
  309. else:
  310. new_txt = " " + txt + " " + '%.3f' % (scores[idx])
  311. draw_txt.text((0, gap * count), new_txt, txt_color, font=font)
  312. # whether add new blank img or not
  313. if count >= img_h // gap - 1 and idx + 1 < len(texts):
  314. txt_img_list.append(np.array(blank_img))
  315. blank_img, draw_txt = create_blank_img()
  316. count = 0
  317. count += 1
  318. txt_img_list.append(np.array(blank_img))
  319. if len(txt_img_list) == 1:
  320. blank_img = np.array(txt_img_list[0])
  321. else:
  322. blank_img = np.concatenate(txt_img_list, axis=1)
  323. return np.array(blank_img)
  324. def base64_to_cv2(b64str):
  325. import base64
  326. data = base64.b64decode(b64str.encode('utf8'))
  327. data = np.fromstring(data, np.uint8)
  328. data = cv2.imdecode(data, cv2.IMREAD_COLOR)
  329. return data
  330. def draw_boxes(image, boxes, scores=None, drop_score=0.5):
  331. if scores is None:
  332. scores = [1] * len(boxes)
  333. for (box, score) in zip(boxes, scores):
  334. if score < drop_score:
  335. continue
  336. box = np.reshape(np.array(box), [-1, 1, 2]).astype(np.int64)
  337. image = cv2.polylines(np.array(image), [box], True, (255, 0, 0), 2)
  338. return image
  339. if __name__ == '__main__':
  340. test_img = "./doc/test_v2"
  341. predict_txt = "./doc/predict.txt"
  342. f = open(predict_txt, 'r')
  343. data = f.readlines()
  344. img_path, anno = data[0].strip().split('\t')
  345. img_name = os.path.basename(img_path)
  346. img_path = os.path.join(test_img, img_name)
  347. image = Image.open(img_path)
  348. data = json.loads(anno)
  349. boxes, txts, scores = [], [], []
  350. for dic in data:
  351. boxes.append(dic['points'])
  352. txts.append(dic['transcription'])
  353. scores.append(round(dic['scores'], 3))
  354. new_img = draw_ocr(image, boxes, txts, scores)
  355. cv2.imwrite(img_name, new_img)