wired_table_rec_utils.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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. """
  88. Utility class for loading and converting images from various input types to a numpy ndarray.
  89. Supported input types:
  90. - str or pathlib.Path: Path to an image file.
  91. - bytes: Image data in bytes format.
  92. - numpy.ndarray: Already loaded image array.
  93. The class attempts to load the image and convert it to a numpy ndarray in BGR format.
  94. Raises LoadImageError for unsupported types or if the image cannot be loaded.
  95. """
  96. def __init__(
  97. self,
  98. ):
  99. pass
  100. def __call__(self, img: InputType) -> np.ndarray:
  101. img = self.load_img(img)
  102. img = self.convert_img(img)
  103. return img
  104. def load_img(self, img: InputType) -> np.ndarray:
  105. if isinstance(img, (str, Path)):
  106. self.verify_exist(img)
  107. try:
  108. img = np.array(Image.open(img))
  109. except UnidentifiedImageError as e:
  110. raise LoadImageError(f"cannot identify image file {img}") from e
  111. return img
  112. elif isinstance(img, bytes):
  113. try:
  114. img = np.array(Image.open(BytesIO(img)))
  115. except UnidentifiedImageError as e:
  116. raise LoadImageError(f"cannot identify image from bytes data") from e
  117. return img
  118. elif isinstance(img, np.ndarray):
  119. return img
  120. else:
  121. raise LoadImageError(f"{type(img)} is not supported!")
  122. def convert_img(self, img: np.ndarray):
  123. if img.ndim == 2:
  124. return cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
  125. if img.ndim == 3:
  126. channel = img.shape[2]
  127. if channel == 1:
  128. return cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
  129. if channel == 2:
  130. return self.cvt_two_to_three(img)
  131. if channel == 4:
  132. return self.cvt_four_to_three(img)
  133. if channel == 3:
  134. return cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
  135. raise LoadImageError(
  136. f"The channel({channel}) of the img is not in [1, 2, 3, 4]"
  137. )
  138. raise LoadImageError(f"The ndim({img.ndim}) of the img is not in [2, 3]")
  139. @staticmethod
  140. def cvt_four_to_three(img: np.ndarray) -> np.ndarray:
  141. """RGBA → BGR"""
  142. r, g, b, a = cv2.split(img)
  143. new_img = cv2.merge((b, g, r))
  144. not_a = cv2.bitwise_not(a)
  145. not_a = cv2.cvtColor(not_a, cv2.COLOR_GRAY2BGR)
  146. new_img = cv2.bitwise_and(new_img, new_img, mask=a)
  147. new_img = cv2.add(new_img, not_a)
  148. return new_img
  149. @staticmethod
  150. def cvt_two_to_three(img: np.ndarray) -> np.ndarray:
  151. """gray + alpha → BGR"""
  152. img_gray = img[..., 0]
  153. img_bgr = cv2.cvtColor(img_gray, cv2.COLOR_GRAY2BGR)
  154. img_alpha = img[..., 1]
  155. not_a = cv2.bitwise_not(img_alpha)
  156. not_a = cv2.cvtColor(not_a, cv2.COLOR_GRAY2BGR)
  157. new_img = cv2.bitwise_and(img_bgr, img_bgr, mask=img_alpha)
  158. new_img = cv2.add(new_img, not_a)
  159. return new_img
  160. @staticmethod
  161. def verify_exist(file_path: Union[str, Path]):
  162. if not Path(file_path).exists():
  163. raise LoadImageError(f"{file_path} does not exist.")
  164. class LoadImageError(Exception):
  165. pass
  166. # Pillow >=v9.1.0 use a slightly different naming scheme for filters.
  167. # Set pillow_interp_codes according to the naming scheme used.
  168. if Image is not None:
  169. if hasattr(Image, "Resampling"):
  170. pillow_interp_codes = {
  171. "nearest": Image.Resampling.NEAREST,
  172. "bilinear": Image.Resampling.BILINEAR,
  173. "bicubic": Image.Resampling.BICUBIC,
  174. "box": Image.Resampling.BOX,
  175. "lanczos": Image.Resampling.LANCZOS,
  176. "hamming": Image.Resampling.HAMMING,
  177. }
  178. else:
  179. pillow_interp_codes = {
  180. "nearest": Image.NEAREST,
  181. "bilinear": Image.BILINEAR,
  182. "bicubic": Image.BICUBIC,
  183. "box": Image.BOX,
  184. "lanczos": Image.LANCZOS,
  185. "hamming": Image.HAMMING,
  186. }
  187. cv2_interp_codes = {
  188. "nearest": cv2.INTER_NEAREST,
  189. "bilinear": cv2.INTER_LINEAR,
  190. "bicubic": cv2.INTER_CUBIC,
  191. "area": cv2.INTER_AREA,
  192. "lanczos": cv2.INTER_LANCZOS4,
  193. }
  194. def resize_img(img, scale, keep_ratio=True):
  195. if keep_ratio:
  196. # 缩小使用area更保真
  197. if min(img.shape[:2]) > min(scale):
  198. interpolation = "area"
  199. else:
  200. interpolation = "bicubic" # bilinear
  201. img_new, scale_factor = imrescale(
  202. img, scale, return_scale=True, interpolation=interpolation
  203. )
  204. # the w_scale and h_scale has minor difference
  205. # a real fix should be done in the mmcv.imrescale in the future
  206. new_h, new_w = img_new.shape[:2]
  207. h, w = img.shape[:2]
  208. w_scale = new_w / w
  209. h_scale = new_h / h
  210. else:
  211. img_new, w_scale, h_scale = imresize(img, scale, return_scale=True)
  212. return img_new, w_scale, h_scale
  213. def imrescale(img, scale, return_scale=False, interpolation="bilinear", backend=None):
  214. """Resize image while keeping the aspect ratio.
  215. Args:
  216. img (ndarray): The input image.
  217. scale (float | tuple[int]): The scaling factor or maximum size.
  218. If it is a float number, then the image will be rescaled by this
  219. factor, else if it is a tuple of 2 integers, then the image will
  220. be rescaled as large as possible within the scale.
  221. return_scale (bool): Whether to return the scaling factor besides the
  222. rescaled image.
  223. interpolation (str): Same as :func:`resize`.
  224. backend (str | None): Same as :func:`resize`.
  225. Returns:
  226. ndarray: The rescaled image.
  227. """
  228. h, w = img.shape[:2]
  229. new_size, scale_factor = rescale_size((w, h), scale, return_scale=True)
  230. rescaled_img = imresize(img, new_size, interpolation=interpolation, backend=backend)
  231. if return_scale:
  232. return rescaled_img, scale_factor
  233. else:
  234. return rescaled_img
  235. def imresize(
  236. img, size, return_scale=False, interpolation="bilinear", out=None, backend=None
  237. ):
  238. """Resize image to a given size.
  239. Args:
  240. img (ndarray): The input image.
  241. size (tuple[int]): Target size (w, h).
  242. return_scale (bool): Whether to return `w_scale` and `h_scale`.
  243. interpolation (str): Interpolation method, accepted values are
  244. "nearest", "bilinear", "bicubic", "area", "lanczos" for 'cv2'
  245. backend, "nearest", "bilinear" for 'pillow' backend.
  246. out (ndarray): The output destination.
  247. backend (str | None): The image resize backend type. Options are `cv2`,
  248. `pillow`, `None`. If backend is None, the global imread_backend
  249. specified by ``mmcv.use_backend()`` will be used. Default: None.
  250. Returns:
  251. tuple | ndarray: (`resized_img`, `w_scale`, `h_scale`) or
  252. `resized_img`.
  253. """
  254. h, w = img.shape[:2]
  255. if backend is None:
  256. backend = "cv2"
  257. if backend not in ["cv2", "pillow"]:
  258. raise ValueError(
  259. f"backend: {backend} is not supported for resize."
  260. f"Supported backends are 'cv2', 'pillow'"
  261. )
  262. if backend == "pillow":
  263. assert img.dtype == np.uint8, "Pillow backend only support uint8 type"
  264. pil_image = Image.fromarray(img)
  265. pil_image = pil_image.resize(size, pillow_interp_codes[interpolation])
  266. resized_img = np.array(pil_image)
  267. else:
  268. resized_img = cv2.resize(
  269. img, size, dst=out, interpolation=cv2_interp_codes[interpolation]
  270. )
  271. if not return_scale:
  272. return resized_img
  273. else:
  274. w_scale = size[0] / w
  275. h_scale = size[1] / h
  276. return resized_img, w_scale, h_scale
  277. def rescale_size(old_size, scale, return_scale=False):
  278. """Calculate the new size to be rescaled to.
  279. Args:
  280. old_size (tuple[int]): The old size (w, h) of image.
  281. scale (float | tuple[int]): The scaling factor or maximum size.
  282. If it is a float number, then the image will be rescaled by this
  283. factor, else if it is a tuple of 2 integers, then the image will
  284. be rescaled as large as possible within the scale.
  285. return_scale (bool): Whether to return the scaling factor besides the
  286. rescaled image size.
  287. Returns:
  288. tuple[int]: The new rescaled image size.
  289. """
  290. w, h = old_size
  291. if isinstance(scale, (float, int)):
  292. if scale <= 0:
  293. raise ValueError(f"Invalid scale {scale}, must be positive.")
  294. scale_factor = scale
  295. elif isinstance(scale, tuple):
  296. max_long_edge = max(scale)
  297. max_short_edge = min(scale)
  298. scale_factor = min(max_long_edge / max(h, w), max_short_edge / min(h, w))
  299. else:
  300. raise TypeError(
  301. f"Scale must be a number or tuple of int, but got {type(scale)}"
  302. )
  303. new_size = _scale_size((w, h), scale_factor)
  304. if return_scale:
  305. return new_size, scale_factor
  306. else:
  307. return new_size
  308. def _scale_size(size, scale):
  309. """Rescale a size by a ratio.
  310. Args:
  311. size (tuple[int]): (w, h).
  312. scale (float | tuple(float)): Scaling factor.
  313. Returns:
  314. tuple[int]: scaled size.
  315. """
  316. if isinstance(scale, (float, int)):
  317. scale = (scale, scale)
  318. w, h = size
  319. return int(w * float(scale[0]) + 0.5), int(h * float(scale[1]) + 0.5)