您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

recognizer.py 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. # Licensed under the Apache License, Version 2.0 (the "License");
  2. # you may not use this file except in compliance with the License.
  3. # You may obtain a copy of the License at
  4. #
  5. # http://www.apache.org/licenses/LICENSE-2.0
  6. #
  7. # Unless required by applicable law or agreed to in writing, software
  8. # distributed under the License is distributed on an "AS IS" BASIS,
  9. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. # See the License for the specific language governing permissions and
  11. # limitations under the License.
  12. #
  13. import os
  14. from copy import deepcopy
  15. import onnxruntime as ort
  16. from huggingface_hub import snapshot_download
  17. from .operators import *
  18. from rag.settings import cron_logger
  19. class Recognizer(object):
  20. def __init__(self, label_list, task_name, model_dir=None):
  21. """
  22. If you have trouble downloading HuggingFace models, -_^ this might help!!
  23. For Linux:
  24. export HF_ENDPOINT=https://hf-mirror.com
  25. For Windows:
  26. Good luck
  27. ^_-
  28. """
  29. if not model_dir:
  30. model_dir = snapshot_download(repo_id="InfiniFlow/deepdoc")
  31. model_file_path = os.path.join(model_dir, task_name + ".onnx")
  32. if not os.path.exists(model_file_path):
  33. raise ValueError("not find model file path {}".format(
  34. model_file_path))
  35. if ort.get_device() == "GPU":
  36. self.ort_sess = ort.InferenceSession(model_file_path, providers=['CUDAExecutionProvider'])
  37. else:
  38. self.ort_sess = ort.InferenceSession(model_file_path, providers=['CPUExecutionProvider'])
  39. self.input_names = [node.name for node in self.ort_sess.get_inputs()]
  40. self.output_names = [node.name for node in self.ort_sess.get_outputs()]
  41. self.input_shape = self.ort_sess.get_inputs()[0].shape[2:4]
  42. self.label_list = label_list
  43. @staticmethod
  44. def sort_Y_firstly(arr, threashold):
  45. # sort using y1 first and then x1
  46. arr = sorted(arr, key=lambda r: (r["top"], r["x0"]))
  47. for i in range(len(arr) - 1):
  48. for j in range(i, -1, -1):
  49. # restore the order using th
  50. if abs(arr[j + 1]["top"] - arr[j]["top"]) < threashold \
  51. and arr[j + 1]["x0"] < arr[j]["x0"]:
  52. tmp = deepcopy(arr[j])
  53. arr[j] = deepcopy(arr[j + 1])
  54. arr[j + 1] = deepcopy(tmp)
  55. return arr
  56. @staticmethod
  57. def sort_X_firstly(arr, threashold, copy=True):
  58. # sort using y1 first and then x1
  59. arr = sorted(arr, key=lambda r: (r["x0"], r["top"]))
  60. for i in range(len(arr) - 1):
  61. for j in range(i, -1, -1):
  62. # restore the order using th
  63. if abs(arr[j + 1]["x0"] - arr[j]["x0"]) < threashold \
  64. and arr[j + 1]["top"] < arr[j]["top"]:
  65. tmp = deepcopy(arr[j]) if copy else arr[j]
  66. arr[j] = deepcopy(arr[j + 1]) if copy else arr[j + 1]
  67. arr[j + 1] = deepcopy(tmp) if copy else tmp
  68. return arr
  69. @staticmethod
  70. def sort_C_firstly(arr, thr=0):
  71. # sort using y1 first and then x1
  72. # sorted(arr, key=lambda r: (r["x0"], r["top"]))
  73. arr = Recognizer.sort_X_firstly(arr, thr)
  74. for i in range(len(arr) - 1):
  75. for j in range(i, -1, -1):
  76. # restore the order using th
  77. if "C" not in arr[j] or "C" not in arr[j + 1]:
  78. continue
  79. if arr[j + 1]["C"] < arr[j]["C"] \
  80. or (
  81. arr[j + 1]["C"] == arr[j]["C"]
  82. and arr[j + 1]["top"] < arr[j]["top"]
  83. ):
  84. tmp = arr[j]
  85. arr[j] = arr[j + 1]
  86. arr[j + 1] = tmp
  87. return arr
  88. return sorted(arr, key=lambda r: (r.get("C", r["x0"]), r["top"]))
  89. @staticmethod
  90. def sort_R_firstly(arr, thr=0):
  91. # sort using y1 first and then x1
  92. # sorted(arr, key=lambda r: (r["top"], r["x0"]))
  93. arr = Recognizer.sort_Y_firstly(arr, thr)
  94. for i in range(len(arr) - 1):
  95. for j in range(i, -1, -1):
  96. if "R" not in arr[j] or "R" not in arr[j + 1]:
  97. continue
  98. if arr[j + 1]["R"] < arr[j]["R"] \
  99. or (
  100. arr[j + 1]["R"] == arr[j]["R"]
  101. and arr[j + 1]["x0"] < arr[j]["x0"]
  102. ):
  103. tmp = arr[j]
  104. arr[j] = arr[j + 1]
  105. arr[j + 1] = tmp
  106. return arr
  107. @staticmethod
  108. def overlapped_area(a, b, ratio=True):
  109. tp, btm, x0, x1 = a["top"], a["bottom"], a["x0"], a["x1"]
  110. if b["x0"] > x1 or b["x1"] < x0:
  111. return 0
  112. if b["bottom"] < tp or b["top"] > btm:
  113. return 0
  114. x0_ = max(b["x0"], x0)
  115. x1_ = min(b["x1"], x1)
  116. assert x0_ <= x1_, "Fuckedup! T:{},B:{},X0:{},X1:{} ==> {}".format(
  117. tp, btm, x0, x1, b)
  118. tp_ = max(b["top"], tp)
  119. btm_ = min(b["bottom"], btm)
  120. assert tp_ <= btm_, "Fuckedup! T:{},B:{},X0:{},X1:{} => {}".format(
  121. tp, btm, x0, x1, b)
  122. ov = (btm_ - tp_) * (x1_ - x0_) if x1 - \
  123. x0 != 0 and btm - tp != 0 else 0
  124. if ov > 0 and ratio:
  125. ov /= (x1 - x0) * (btm - tp)
  126. return ov
  127. @staticmethod
  128. def layouts_cleanup(boxes, layouts, far=2, thr=0.7):
  129. def notOverlapped(a, b):
  130. return any([a["x1"] < b["x0"],
  131. a["x0"] > b["x1"],
  132. a["bottom"] < b["top"],
  133. a["top"] > b["bottom"]])
  134. i = 0
  135. while i + 1 < len(layouts):
  136. j = i + 1
  137. while j < min(i + far, len(layouts)) \
  138. and (layouts[i].get("type", "") != layouts[j].get("type", "")
  139. or notOverlapped(layouts[i], layouts[j])):
  140. j += 1
  141. if j >= min(i + far, len(layouts)):
  142. i += 1
  143. continue
  144. if Recognizer.overlapped_area(layouts[i], layouts[j]) < thr \
  145. and Recognizer.overlapped_area(layouts[j], layouts[i]) < thr:
  146. i += 1
  147. continue
  148. if layouts[i].get("score") and layouts[j].get("score"):
  149. if layouts[i]["score"] > layouts[j]["score"]:
  150. layouts.pop(j)
  151. else:
  152. layouts.pop(i)
  153. continue
  154. area_i, area_i_1 = 0, 0
  155. for b in boxes:
  156. if not notOverlapped(b, layouts[i]):
  157. area_i += Recognizer.overlapped_area(b, layouts[i], False)
  158. if not notOverlapped(b, layouts[j]):
  159. area_i_1 += Recognizer.overlapped_area(b, layouts[j], False)
  160. if area_i > area_i_1:
  161. layouts.pop(j)
  162. else:
  163. layouts.pop(i)
  164. return layouts
  165. def create_inputs(self, imgs, im_info):
  166. """generate input for different model type
  167. Args:
  168. imgs (list(numpy)): list of images (np.ndarray)
  169. im_info (list(dict)): list of image info
  170. Returns:
  171. inputs (dict): input of model
  172. """
  173. inputs = {}
  174. im_shape = []
  175. scale_factor = []
  176. if len(imgs) == 1:
  177. inputs['image'] = np.array((imgs[0],)).astype('float32')
  178. inputs['im_shape'] = np.array(
  179. (im_info[0]['im_shape'],)).astype('float32')
  180. inputs['scale_factor'] = np.array(
  181. (im_info[0]['scale_factor'],)).astype('float32')
  182. return inputs
  183. for e in im_info:
  184. im_shape.append(np.array((e['im_shape'],)).astype('float32'))
  185. scale_factor.append(np.array((e['scale_factor'],)).astype('float32'))
  186. inputs['im_shape'] = np.concatenate(im_shape, axis=0)
  187. inputs['scale_factor'] = np.concatenate(scale_factor, axis=0)
  188. imgs_shape = [[e.shape[1], e.shape[2]] for e in imgs]
  189. max_shape_h = max([e[0] for e in imgs_shape])
  190. max_shape_w = max([e[1] for e in imgs_shape])
  191. padding_imgs = []
  192. for img in imgs:
  193. im_c, im_h, im_w = img.shape[:]
  194. padding_im = np.zeros(
  195. (im_c, max_shape_h, max_shape_w), dtype=np.float32)
  196. padding_im[:, :im_h, :im_w] = img
  197. padding_imgs.append(padding_im)
  198. inputs['image'] = np.stack(padding_imgs, axis=0)
  199. return inputs
  200. @staticmethod
  201. def find_overlapped(box, boxes_sorted_by_y, naive=False):
  202. if not boxes_sorted_by_y:
  203. return
  204. bxs = boxes_sorted_by_y
  205. s, e, ii = 0, len(bxs), 0
  206. while s < e and not naive:
  207. ii = (e + s) // 2
  208. pv = bxs[ii]
  209. if box["bottom"] < pv["top"]:
  210. e = ii
  211. continue
  212. if box["top"] > pv["bottom"]:
  213. s = ii + 1
  214. continue
  215. break
  216. while s < ii:
  217. if box["top"] > bxs[s]["bottom"]:
  218. s += 1
  219. break
  220. while e - 1 > ii:
  221. if box["bottom"] < bxs[e - 1]["top"]:
  222. e -= 1
  223. break
  224. max_overlaped_i, max_overlaped = None, 0
  225. for i in range(s, e):
  226. ov = Recognizer.overlapped_area(bxs[i], box)
  227. if ov <= max_overlaped:
  228. continue
  229. max_overlaped_i = i
  230. max_overlaped = ov
  231. return max_overlaped_i
  232. @staticmethod
  233. def find_overlapped_with_threashold(box, boxes, thr=0.3):
  234. if not boxes:
  235. return
  236. max_overlaped_i, max_overlaped, _max_overlaped = None, thr, 0
  237. s, e = 0, len(boxes)
  238. for i in range(s, e):
  239. ov = Recognizer.overlapped_area(box, boxes[i])
  240. _ov = Recognizer.overlapped_area(boxes[i], box)
  241. if (ov, _ov) < (max_overlaped, _max_overlaped):
  242. continue
  243. max_overlaped_i = i
  244. max_overlaped = ov
  245. _max_overlaped = _ov
  246. return max_overlaped_i
  247. def preprocess(self, image_list):
  248. inputs = []
  249. if "scale_factor" in self.input_names:
  250. preprocess_ops = []
  251. for op_info in [
  252. {'interp': 2, 'keep_ratio': False, 'target_size': [800, 608], 'type': 'LinearResize'},
  253. {'is_scale': True, 'mean': [0.485, 0.456, 0.406], 'std': [0.229, 0.224, 0.225], 'type': 'StandardizeImage'},
  254. {'type': 'Permute'},
  255. {'stride': 32, 'type': 'PadStride'}
  256. ]:
  257. new_op_info = op_info.copy()
  258. op_type = new_op_info.pop('type')
  259. preprocess_ops.append(eval(op_type)(**new_op_info))
  260. for im_path in image_list:
  261. im, im_info = preprocess(im_path, preprocess_ops)
  262. inputs.append({"image": np.array((im,)).astype('float32'),
  263. "scale_factor": np.array((im_info["scale_factor"],)).astype('float32')})
  264. else:
  265. hh, ww = self.input_shape
  266. for img in image_list:
  267. h, w = img.shape[:2]
  268. img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
  269. img = cv2.resize(np.array(img).astype('float32'), (ww, hh))
  270. # Scale input pixel values to 0 to 1
  271. img /= 255.0
  272. img = img.transpose(2, 0, 1)
  273. img = img[np.newaxis, :, :, :].astype(np.float32)
  274. inputs.append({self.input_names[0]: img, "scale_factor": [w/ww, h/hh]})
  275. return inputs
  276. def postprocess(self, boxes, inputs, thr):
  277. if "scale_factor" in self.input_names:
  278. bb = []
  279. for b in boxes:
  280. clsid, bbox, score = int(b[0]), b[2:], b[1]
  281. if score < thr:
  282. continue
  283. if clsid >= len(self.label_list):
  284. cron_logger.warning(f"bad category id")
  285. continue
  286. bb.append({
  287. "type": self.label_list[clsid].lower(),
  288. "bbox": [float(t) for t in bbox.tolist()],
  289. "score": float(score)
  290. })
  291. return bb
  292. def xywh2xyxy(x):
  293. # [x, y, w, h] to [x1, y1, x2, y2]
  294. y = np.copy(x)
  295. y[:, 0] = x[:, 0] - x[:, 2] / 2
  296. y[:, 1] = x[:, 1] - x[:, 3] / 2
  297. y[:, 2] = x[:, 0] + x[:, 2] / 2
  298. y[:, 3] = x[:, 1] + x[:, 3] / 2
  299. return y
  300. def compute_iou(box, boxes):
  301. # Compute xmin, ymin, xmax, ymax for both boxes
  302. xmin = np.maximum(box[0], boxes[:, 0])
  303. ymin = np.maximum(box[1], boxes[:, 1])
  304. xmax = np.minimum(box[2], boxes[:, 2])
  305. ymax = np.minimum(box[3], boxes[:, 3])
  306. # Compute intersection area
  307. intersection_area = np.maximum(0, xmax - xmin) * np.maximum(0, ymax - ymin)
  308. # Compute union area
  309. box_area = (box[2] - box[0]) * (box[3] - box[1])
  310. boxes_area = (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1])
  311. union_area = box_area + boxes_area - intersection_area
  312. # Compute IoU
  313. iou = intersection_area / union_area
  314. return iou
  315. def iou_filter(boxes, scores, iou_threshold):
  316. sorted_indices = np.argsort(scores)[::-1]
  317. keep_boxes = []
  318. while sorted_indices.size > 0:
  319. # Pick the last box
  320. box_id = sorted_indices[0]
  321. keep_boxes.append(box_id)
  322. # Compute IoU of the picked box with the rest
  323. ious = compute_iou(boxes[box_id, :], boxes[sorted_indices[1:], :])
  324. # Remove boxes with IoU over the threshold
  325. keep_indices = np.where(ious < iou_threshold)[0]
  326. # print(keep_indices.shape, sorted_indices.shape)
  327. sorted_indices = sorted_indices[keep_indices + 1]
  328. return keep_boxes
  329. boxes = np.squeeze(boxes).T
  330. # Filter out object confidence scores below threshold
  331. scores = np.max(boxes[:, 4:], axis=1)
  332. boxes = boxes[scores > thr, :]
  333. scores = scores[scores > thr]
  334. if len(boxes) == 0: return []
  335. # Get the class with the highest confidence
  336. class_ids = np.argmax(boxes[:, 4:], axis=1)
  337. boxes = boxes[:, :4]
  338. input_shape = np.array([inputs["scale_factor"][0], inputs["scale_factor"][1], inputs["scale_factor"][0], inputs["scale_factor"][1]])
  339. boxes = np.multiply(boxes, input_shape, dtype=np.float32)
  340. boxes = xywh2xyxy(boxes)
  341. unique_class_ids = np.unique(class_ids)
  342. indices = []
  343. for class_id in unique_class_ids:
  344. class_indices = np.where(class_ids == class_id)[0]
  345. class_boxes = boxes[class_indices, :]
  346. class_scores = scores[class_indices]
  347. class_keep_boxes = iou_filter(class_boxes, class_scores, 0.2)
  348. indices.extend(class_indices[class_keep_boxes])
  349. return [{
  350. "type": self.label_list[class_ids[i]].lower(),
  351. "bbox": [float(t) for t in boxes[i].tolist()],
  352. "score": float(scores[i])
  353. } for i in indices]
  354. def __call__(self, image_list, thr=0.7, batch_size=16):
  355. res = []
  356. imgs = []
  357. for i in range(len(image_list)):
  358. if not isinstance(image_list[i], np.ndarray):
  359. imgs.append(np.array(image_list[i]))
  360. else: imgs.append(image_list[i])
  361. batch_loop_cnt = math.ceil(float(len(imgs)) / batch_size)
  362. for i in range(batch_loop_cnt):
  363. start_index = i * batch_size
  364. end_index = min((i + 1) * batch_size, len(imgs))
  365. batch_image_list = imgs[start_index:end_index]
  366. inputs = self.preprocess(batch_image_list)
  367. print("preprocess")
  368. for ins in inputs:
  369. bb = self.postprocess(self.ort_sess.run(None, {k:v for k,v in ins.items() if k in self.input_names})[0], ins, thr)
  370. res.append(bb)
  371. #seeit.save_results(image_list, res, self.label_list, threshold=thr)
  372. return res