wired_table_rec_utils.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. import os
  2. import traceback
  3. from enum import Enum
  4. from io import BytesIO
  5. from pathlib import Path
  6. from typing import List, Union, Dict, Any, Tuple
  7. import cv2
  8. import numpy as np
  9. from onnxruntime import (
  10. GraphOptimizationLevel,
  11. InferenceSession,
  12. SessionOptions,
  13. get_available_providers,
  14. )
  15. from PIL import Image, UnidentifiedImageError
  16. root_dir = Path(__file__).resolve().parent
  17. InputType = Union[str, np.ndarray, bytes, Path]
  18. class EP(Enum):
  19. CPU_EP = "CPUExecutionProvider"
  20. class OrtInferSession:
  21. def __init__(self, config: Dict[str, Any]):
  22. model_path = config.get("model_path", None)
  23. self._verify_model(model_path)
  24. self.had_providers: List[str] = get_available_providers()
  25. EP_list = self._get_ep_list()
  26. sess_opt = self._init_sess_opts(config)
  27. self.session = InferenceSession(
  28. model_path,
  29. sess_options=sess_opt,
  30. providers=EP_list,
  31. )
  32. @staticmethod
  33. def _init_sess_opts(config: Dict[str, Any]) -> SessionOptions:
  34. sess_opt = SessionOptions()
  35. sess_opt.log_severity_level = 4
  36. sess_opt.enable_cpu_mem_arena = False
  37. sess_opt.graph_optimization_level = GraphOptimizationLevel.ORT_ENABLE_ALL
  38. cpu_nums = os.cpu_count()
  39. intra_op_num_threads = config.get("intra_op_num_threads", -1)
  40. if intra_op_num_threads != -1 and 1 <= intra_op_num_threads <= cpu_nums:
  41. sess_opt.intra_op_num_threads = intra_op_num_threads
  42. inter_op_num_threads = config.get("inter_op_num_threads", -1)
  43. if inter_op_num_threads != -1 and 1 <= inter_op_num_threads <= cpu_nums:
  44. sess_opt.inter_op_num_threads = inter_op_num_threads
  45. return sess_opt
  46. def get_metadata(self, key: str = "character") -> list:
  47. meta_dict = self.session.get_modelmeta().custom_metadata_map
  48. content_list = meta_dict[key].splitlines()
  49. return content_list
  50. def _get_ep_list(self) -> List[Tuple[str, Dict[str, Any]]]:
  51. cpu_provider_opts = {
  52. "arena_extend_strategy": "kSameAsRequested",
  53. }
  54. EP_list = [(EP.CPU_EP.value, cpu_provider_opts)]
  55. return EP_list
  56. def __call__(self, input_content: List[np.ndarray]) -> np.ndarray:
  57. input_dict = dict(zip(self.get_input_names(), input_content))
  58. try:
  59. return self.session.run(None, input_dict)
  60. except Exception as e:
  61. error_info = traceback.format_exc()
  62. raise ONNXRuntimeError(error_info) from e
  63. def get_input_names(self) -> List[str]:
  64. return [v.name for v in self.session.get_inputs()]
  65. def get_output_names(self) -> List[str]:
  66. return [v.name for v in self.session.get_outputs()]
  67. def get_character_list(self, key: str = "character") -> List[str]:
  68. meta_dict = self.session.get_modelmeta().custom_metadata_map
  69. return meta_dict[key].splitlines()
  70. def have_key(self, key: str = "character") -> bool:
  71. meta_dict = self.session.get_modelmeta().custom_metadata_map
  72. if key in meta_dict.keys():
  73. return True
  74. return False
  75. @staticmethod
  76. def _verify_model(model_path: Union[str, Path, None]):
  77. if model_path is None:
  78. raise ValueError("model_path is None!")
  79. model_path = Path(model_path)
  80. if not model_path.exists():
  81. raise FileNotFoundError(f"{model_path} does not exists.")
  82. if not model_path.is_file():
  83. raise FileExistsError(f"{model_path} is not a file.")
  84. class ONNXRuntimeError(Exception):
  85. pass
  86. class LoadImage:
  87. def __init__(
  88. self,
  89. ):
  90. pass
  91. def __call__(self, img: InputType) -> np.ndarray:
  92. img = self.load_img(img)
  93. img = self.convert_img(img)
  94. return img
  95. def load_img(self, img: InputType) -> np.ndarray:
  96. if isinstance(img, (str, Path)):
  97. self.verify_exist(img)
  98. try:
  99. img = np.array(Image.open(img))
  100. except UnidentifiedImageError as e:
  101. raise LoadImageError(f"cannot identify image file {img}") from e
  102. return img
  103. elif isinstance(img, bytes):
  104. try:
  105. img = np.array(Image.open(BytesIO(img)))
  106. except UnidentifiedImageError as e:
  107. raise LoadImageError(f"cannot identify image from bytes data") from e
  108. return img
  109. elif isinstance(img, np.ndarray):
  110. return img
  111. else:
  112. raise LoadImageError(f"{type(img)} is not supported!")
  113. def convert_img(self, img: np.ndarray):
  114. if img.ndim == 2:
  115. return cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
  116. if img.ndim == 3:
  117. channel = img.shape[2]
  118. if channel == 1:
  119. return cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
  120. if channel == 2:
  121. return self.cvt_two_to_three(img)
  122. if channel == 4:
  123. return self.cvt_four_to_three(img)
  124. if channel == 3:
  125. return cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
  126. raise LoadImageError(
  127. f"The channel({channel}) of the img is not in [1, 2, 3, 4]"
  128. )
  129. raise LoadImageError(f"The ndim({img.ndim}) of the img is not in [2, 3]")
  130. @staticmethod
  131. def cvt_four_to_three(img: np.ndarray) -> np.ndarray:
  132. """RGBA → BGR"""
  133. r, g, b, a = cv2.split(img)
  134. new_img = cv2.merge((b, g, r))
  135. not_a = cv2.bitwise_not(a)
  136. not_a = cv2.cvtColor(not_a, cv2.COLOR_GRAY2BGR)
  137. new_img = cv2.bitwise_and(new_img, new_img, mask=a)
  138. new_img = cv2.add(new_img, not_a)
  139. return new_img
  140. @staticmethod
  141. def cvt_two_to_three(img: np.ndarray) -> np.ndarray:
  142. """gray + alpha → BGR"""
  143. img_gray = img[..., 0]
  144. img_bgr = cv2.cvtColor(img_gray, cv2.COLOR_GRAY2BGR)
  145. img_alpha = img[..., 1]
  146. not_a = cv2.bitwise_not(img_alpha)
  147. not_a = cv2.cvtColor(not_a, cv2.COLOR_GRAY2BGR)
  148. new_img = cv2.bitwise_and(img_bgr, img_bgr, mask=img_alpha)
  149. new_img = cv2.add(new_img, not_a)
  150. return new_img
  151. @staticmethod
  152. def verify_exist(file_path: Union[str, Path]):
  153. if not Path(file_path).exists():
  154. raise LoadImageError(f"{file_path} does not exist.")
  155. class LoadImageError(Exception):
  156. pass
  157. # Pillow >=v9.1.0 use a slightly different naming scheme for filters.
  158. # Set pillow_interp_codes according to the naming scheme used.
  159. if Image is not None:
  160. if hasattr(Image, "Resampling"):
  161. pillow_interp_codes = {
  162. "nearest": Image.Resampling.NEAREST,
  163. "bilinear": Image.Resampling.BILINEAR,
  164. "bicubic": Image.Resampling.BICUBIC,
  165. "box": Image.Resampling.BOX,
  166. "lanczos": Image.Resampling.LANCZOS,
  167. "hamming": Image.Resampling.HAMMING,
  168. }
  169. else:
  170. pillow_interp_codes = {
  171. "nearest": Image.NEAREST,
  172. "bilinear": Image.BILINEAR,
  173. "bicubic": Image.BICUBIC,
  174. "box": Image.BOX,
  175. "lanczos": Image.LANCZOS,
  176. "hamming": Image.HAMMING,
  177. }
  178. cv2_interp_codes = {
  179. "nearest": cv2.INTER_NEAREST,
  180. "bilinear": cv2.INTER_LINEAR,
  181. "bicubic": cv2.INTER_CUBIC,
  182. "area": cv2.INTER_AREA,
  183. "lanczos": cv2.INTER_LANCZOS4,
  184. }
  185. def resize_img(img, scale, keep_ratio=True):
  186. if keep_ratio:
  187. # 缩小使用area更保真
  188. if min(img.shape[:2]) > min(scale):
  189. interpolation = "area"
  190. else:
  191. interpolation = "bicubic" # bilinear
  192. img_new, scale_factor = imrescale(
  193. img, scale, return_scale=True, interpolation=interpolation
  194. )
  195. # the w_scale and h_scale has minor difference
  196. # a real fix should be done in the mmcv.imrescale in the future
  197. new_h, new_w = img_new.shape[:2]
  198. h, w = img.shape[:2]
  199. w_scale = new_w / w
  200. h_scale = new_h / h
  201. else:
  202. img_new, w_scale, h_scale = imresize(img, scale, return_scale=True)
  203. return img_new, w_scale, h_scale
  204. def imrescale(img, scale, return_scale=False, interpolation="bilinear", backend=None):
  205. """Resize image while keeping the aspect ratio.
  206. Args:
  207. img (ndarray): The input image.
  208. scale (float | tuple[int]): The scaling factor or maximum size.
  209. If it is a float number, then the image will be rescaled by this
  210. factor, else if it is a tuple of 2 integers, then the image will
  211. be rescaled as large as possible within the scale.
  212. return_scale (bool): Whether to return the scaling factor besides the
  213. rescaled image.
  214. interpolation (str): Same as :func:`resize`.
  215. backend (str | None): Same as :func:`resize`.
  216. Returns:
  217. ndarray: The rescaled image.
  218. """
  219. h, w = img.shape[:2]
  220. new_size, scale_factor = rescale_size((w, h), scale, return_scale=True)
  221. rescaled_img = imresize(img, new_size, interpolation=interpolation, backend=backend)
  222. if return_scale:
  223. return rescaled_img, scale_factor
  224. else:
  225. return rescaled_img
  226. def imresize(
  227. img, size, return_scale=False, interpolation="bilinear", out=None, backend=None
  228. ):
  229. """Resize image to a given size.
  230. Args:
  231. img (ndarray): The input image.
  232. size (tuple[int]): Target size (w, h).
  233. return_scale (bool): Whether to return `w_scale` and `h_scale`.
  234. interpolation (str): Interpolation method, accepted values are
  235. "nearest", "bilinear", "bicubic", "area", "lanczos" for 'cv2'
  236. backend, "nearest", "bilinear" for 'pillow' backend.
  237. out (ndarray): The output destination.
  238. backend (str | None): The image resize backend type. Options are `cv2`,
  239. `pillow`, `None`. If backend is None, the global imread_backend
  240. specified by ``mmcv.use_backend()`` will be used. Default: None.
  241. Returns:
  242. tuple | ndarray: (`resized_img`, `w_scale`, `h_scale`) or
  243. `resized_img`.
  244. """
  245. h, w = img.shape[:2]
  246. if backend is None:
  247. backend = "cv2"
  248. if backend not in ["cv2", "pillow"]:
  249. raise ValueError(
  250. f"backend: {backend} is not supported for resize."
  251. f"Supported backends are 'cv2', 'pillow'"
  252. )
  253. if backend == "pillow":
  254. assert img.dtype == np.uint8, "Pillow backend only support uint8 type"
  255. pil_image = Image.fromarray(img)
  256. pil_image = pil_image.resize(size, pillow_interp_codes[interpolation])
  257. resized_img = np.array(pil_image)
  258. else:
  259. resized_img = cv2.resize(
  260. img, size, dst=out, interpolation=cv2_interp_codes[interpolation]
  261. )
  262. if not return_scale:
  263. return resized_img
  264. else:
  265. w_scale = size[0] / w
  266. h_scale = size[1] / h
  267. return resized_img, w_scale, h_scale
  268. def rescale_size(old_size, scale, return_scale=False):
  269. """Calculate the new size to be rescaled to.
  270. Args:
  271. old_size (tuple[int]): The old size (w, h) of image.
  272. scale (float | tuple[int]): The scaling factor or maximum size.
  273. If it is a float number, then the image will be rescaled by this
  274. factor, else if it is a tuple of 2 integers, then the image will
  275. be rescaled as large as possible within the scale.
  276. return_scale (bool): Whether to return the scaling factor besides the
  277. rescaled image size.
  278. Returns:
  279. tuple[int]: The new rescaled image size.
  280. """
  281. w, h = old_size
  282. if isinstance(scale, (float, int)):
  283. if scale <= 0:
  284. raise ValueError(f"Invalid scale {scale}, must be positive.")
  285. scale_factor = scale
  286. elif isinstance(scale, tuple):
  287. max_long_edge = max(scale)
  288. max_short_edge = min(scale)
  289. scale_factor = min(max_long_edge / max(h, w), max_short_edge / min(h, w))
  290. else:
  291. raise TypeError(
  292. f"Scale must be a number or tuple of int, but got {type(scale)}"
  293. )
  294. new_size = _scale_size((w, h), scale_factor)
  295. if return_scale:
  296. return new_size, scale_factor
  297. else:
  298. return new_size
  299. def _scale_size(size, scale):
  300. """Rescale a size by a ratio.
  301. Args:
  302. size (tuple[int]): (w, h).
  303. scale (float | tuple(float)): Scaling factor.
  304. Returns:
  305. tuple[int]: scaled size.
  306. """
  307. if isinstance(scale, (float, int)):
  308. scale = (scale, scale)
  309. w, h = size
  310. return int(w * float(scale[0]) + 0.5), int(h * float(scale[1]) + 0.5)